-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathgithub.go
More file actions
466 lines (405 loc) · 14 KB
/
github.go
File metadata and controls
466 lines (405 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
package github
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"log"
"github.com/livereview/internal/aisanitize"
"github.com/livereview/internal/capture"
"github.com/livereview/internal/providers"
"github.com/livereview/pkg/models"
)
type GitHubProvider struct {
PAT string
}
func NewGitHubProvider(pat string) *GitHubProvider {
log.Printf("[DEBUG] NewGitHubProvider called with PAT length: %d", len(pat))
return &GitHubProvider{PAT: pat}
}
func (p *GitHubProvider) Name() string {
return "github"
}
func (p *GitHubProvider) Configure(config map[string]interface{}) error {
log.Printf("[DEBUG] GitHubProvider.Configure called with config keys: %v", getKeys(config))
if pat, ok := config["pat_token"].(string); ok {
log.Printf("[DEBUG] Setting PAT token, length: %d", len(pat))
p.PAT = pat
return nil
}
log.Printf("[DEBUG] pat_token not found in config")
return fmt.Errorf("pat_token missing in config")
}
func getKeys(m map[string]interface{}) []string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
return keys
}
func (p *GitHubProvider) PostComment(ctx context.Context, prID string, comment *models.ReviewComment) error {
log.Printf("[DEBUG] PostComment called with prID: '%s', FilePath: '%s', Line: %d", prID, comment.FilePath, comment.Line)
// prID format: owner/repo/number
parts := strings.Split(prID, "/")
if len(parts) != 3 {
return fmt.Errorf("invalid GitHub PR ID format: expected 'owner/repo/number', got '%s'", prID)
}
owner := parts[0]
repo := parts[1]
number := parts[2]
// If this is a line comment (has FilePath and Line), use the pull request review comments API
if comment.FilePath != "" && comment.Line > 0 {
return p.postLineComment(ctx, owner, repo, number, comment)
}
// Otherwise, post as a general PR comment (issue comment)
return p.postGeneralComment(ctx, owner, repo, number, comment)
}
// formatGitHubComment creates a consistently formatted comment for GitHub
// with severity information and suggestions properly formatted
func formatGitHubComment(comment *models.ReviewComment) string {
safeContent, contentReport := aisanitize.SanitizationPostflight(context.Background(), comment.Content)
if contentReport.PIIRedactError {
log.Printf("[WARN] GitHub comment sanitization reported internal error for content")
}
safeSuggestions := make([]string, 0, len(comment.Suggestions))
for _, suggestion := range comment.Suggestions {
safeSuggestion, suggestionReport := aisanitize.SanitizationPostflight(context.Background(), suggestion)
if suggestionReport.PIIRedactError {
log.Printf("[WARN] GitHub comment sanitization reported internal error for suggestion")
}
safeSuggestions = append(safeSuggestions, safeSuggestion)
}
// Start with the content
formattedComment := safeContent
// Add severity information at the beginning
if comment.Severity != "" {
formattedComment = fmt.Sprintf("**Severity: %s**\n\n%s", comment.Severity, formattedComment)
}
// Add suggestions section if we have any
if len(safeSuggestions) > 0 {
formattedComment += "\n\n**Suggestions:**\n"
for i, suggestion := range safeSuggestions {
formattedComment += fmt.Sprintf("%d. %s\n", i+1, suggestion)
}
}
return formattedComment
}
func (p *GitHubProvider) postGeneralComment(ctx context.Context, owner, repo, number string, comment *models.ReviewComment) error {
url := fmt.Sprintf("https://api.github.com/repos/%s/%s/issues/%s/comments", owner, repo, number)
payload := map[string]string{"body": formatGitHubComment(comment)}
data, _ := json.Marshal(payload)
req, _ := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(data))
req.Header.Set("Authorization", "token "+p.PAT)
req.Header.Set("Accept", "application/vnd.github.v3+json")
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 201 {
return fmt.Errorf("GitHub general comment failed: %s", resp.Status)
}
log.Printf("[DEBUG] Successfully posted general comment")
return nil
}
func (p *GitHubProvider) postLineComment(ctx context.Context, owner, repo, number string, comment *models.ReviewComment) error {
// First get the PR details to get the head commit SHA
prDetailsURL := fmt.Sprintf("https://api.github.com/repos/%s/%s/pulls/%s", owner, repo, number)
req, _ := http.NewRequestWithContext(ctx, "GET", prDetailsURL, nil)
req.Header.Set("Authorization", "token "+p.PAT)
req.Header.Set("Accept", "application/vnd.github.v3+json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("failed to get PR details for line comment: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("GitHub PR details failed for line comment: %s", resp.Status)
}
var pr struct {
Head struct {
SHA string `json:"sha"`
} `json:"head"`
}
if err := json.NewDecoder(resp.Body).Decode(&pr); err != nil {
return fmt.Errorf("failed to decode PR details: %w", err)
}
// Now create the line comment using the pull request comments API
url := fmt.Sprintf("https://api.github.com/repos/%s/%s/pulls/%s/comments", owner, repo, number)
payload := map[string]interface{}{
"body": formatGitHubComment(comment),
"commit_id": pr.Head.SHA,
"path": comment.FilePath,
"line": comment.Line,
}
// Determine side based on IsDeletedLine field
if comment.IsDeletedLine {
payload["side"] = "LEFT" // Comment on the old version (deleted line)
} else {
payload["side"] = "RIGHT" // Comment on the new version (added line)
}
data, _ := json.Marshal(payload)
req, _ = http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(data))
req.Header.Set("Authorization", "token "+p.PAT)
req.Header.Set("Accept", "application/vnd.github.v3+json")
req.Header.Set("Content-Type", "application/json")
resp, err = http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("failed to post line comment: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode == http.StatusUnprocessableEntity {
log.Printf("[WARN] Skipping GitHub line comment due to 422 response. Payload path=%s line=%d, body=%s", comment.FilePath, comment.Line, string(body))
return nil
}
log.Printf("[DEBUG] Line comment failed. Status: %s, Response: %s", resp.Status, string(body))
return fmt.Errorf("GitHub line comment failed: %s", resp.Status)
}
log.Printf("[DEBUG] Successfully posted line comment on %s:%d", comment.FilePath, comment.Line)
return nil
}
func (p *GitHubProvider) PostComments(ctx context.Context, prID string, comments []*models.ReviewComment) error {
for _, comment := range comments {
err := p.PostComment(ctx, prID, comment)
if err != nil {
return err
}
}
return nil
}
func (p *GitHubProvider) GetMergeRequestDetails(ctx context.Context, mrURL string) (*providers.MergeRequestDetails, error) {
parsed, err := url.Parse(mrURL)
if err != nil {
return nil, fmt.Errorf("invalid GitHub PR URL: %w", err)
}
parts := strings.Split(parsed.Path, "/")
if len(parts) < 5 || parts[3] != "pull" {
return nil, fmt.Errorf("invalid GitHub PR URL: expected /owner/repo/pull/number")
}
owner := parts[1]
repo := parts[2]
number := parts[4]
apiURL := fmt.Sprintf("https://api.github.com/repos/%s/%s/pulls/%s", owner, repo, number)
log.Printf("[DEBUG] GitHubProvider: Try this curl command to debug:")
log.Printf("curl -H 'Authorization: token %s' -H 'Accept: application/vnd.github.v3+json' '%s'", p.PAT, apiURL)
req, _ := http.NewRequestWithContext(ctx, "GET", apiURL, nil)
req.Header.Set("Authorization", "token "+p.PAT)
req.Header.Set("Accept", "application/vnd.github.v3+json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("GitHub PR details failed: %s", resp.Status)
}
var pr struct {
ID int `json:"id"`
Number int `json:"number"`
Title string `json:"title"`
Body string `json:"body"`
State string `json:"state"`
User struct {
Login string `json:"login"`
Name string `json:"name"`
AvatarURL string `json:"avatar_url"`
} `json:"user"`
Head struct {
SHA string `json:"sha"`
Ref string `json:"ref"`
Repo struct {
FullName string `json:"full_name"`
} `json:"repo"`
} `json:"head"`
Base struct {
SHA string `json:"sha"`
Ref string `json:"ref"`
Repo struct {
FullName string `json:"full_name"`
} `json:"repo"`
} `json:"base"`
CreatedAt string `json:"created_at"`
HTMLURL string `json:"html_url"`
}
if err := json.NewDecoder(resp.Body).Decode(&pr); err != nil {
return nil, err
}
authorName := pr.User.Name
if authorName == "" {
authorName = pr.User.Login
}
details := &providers.MergeRequestDetails{
ID: fmt.Sprintf("%d", pr.Number),
Title: pr.Title,
Description: pr.Body,
Author: pr.User.Login,
AuthorName: authorName,
AuthorUsername: pr.User.Login,
AuthorAvatar: pr.User.AvatarURL,
CreatedAt: pr.CreatedAt,
URL: mrURL,
State: pr.State,
WebURL: pr.HTMLURL,
SourceBranch: pr.Head.Ref,
TargetBranch: pr.Base.Ref,
DiffRefs: providers.DiffRefs{
BaseSHA: pr.Base.SHA,
HeadSHA: pr.Head.SHA,
},
ProviderType: "github",
RepositoryURL: fmt.Sprintf("https://github.com/%s/%s", owner, repo),
}
if capture.Enabled() {
payload := map[string]interface{}{
"owner": owner,
"repo": repo,
"number": number,
"api_url": apiURL,
"details": details,
}
capture.WriteJSON("github-pr-details", payload)
}
return details, nil
}
func (p *GitHubProvider) GetMergeRequestChanges(ctx context.Context, mrID string) ([]*models.CodeDiff, error) {
log.Printf("[DEBUG] GetMergeRequestChanges called with mrID: '%s', PAT length: %d", mrID, len(p.PAT))
// Simple string splitting instead of complex scanf
parts := strings.Split(mrID, "/")
if len(parts) != 3 {
log.Printf("[DEBUG] Invalid mrID format, expected 'owner/repo/number', got '%s' with %d parts: %v", mrID, len(parts), parts)
return nil, fmt.Errorf("invalid GitHub PR ID format: expected 'owner/repo/number', got '%s'", mrID)
}
owner := parts[0]
repo := parts[1]
number := parts[2]
log.Printf("[DEBUG] Parsed GitHub PR: owner='%s', repo='%s', number='%s'", owner, repo, number)
url := fmt.Sprintf("https://api.github.com/repos/%s/%s/pulls/%s/files", owner, repo, number)
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
req.Header.Set("Authorization", "token "+p.PAT)
req.Header.Set("Accept", "application/vnd.github.v3+json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("GitHub PR files failed: %s", resp.Status)
}
var files []struct {
Filename string `json:"filename"`
Status string `json:"status"`
Additions int `json:"additions"`
Deletions int `json:"deletions"`
Changes int `json:"changes"`
Patch string `json:"patch"`
SHA string `json:"sha"`
}
if err := json.NewDecoder(resp.Body).Decode(&files); err != nil {
return nil, err
}
if capture.Enabled() {
payload := map[string]interface{}{
"owner": owner,
"repo": repo,
"number": number,
"files": files,
}
capture.WriteJSON("github-pr-files", payload)
}
log.Printf("[DEBUG] GitHub API returned %d files", len(files))
var diffs []*models.CodeDiff
for _, f := range files {
log.Printf("[DEBUG] Processing file: %s, status: %s, patch length: %d", f.Filename, f.Status, len(f.Patch))
// Parse the patch into hunks
hunks := p.parsePatchIntoHunks(f.Patch)
diff := &models.CodeDiff{
FilePath: f.Filename,
CommitID: f.SHA,
FileType: p.getFileType(f.Filename),
IsNew: f.Status == "added",
IsDeleted: f.Status == "removed",
IsRenamed: f.Status == "renamed",
Hunks: hunks,
}
log.Printf("[DEBUG] Created CodeDiff for %s with %d hunks", f.Filename, len(hunks))
diffs = append(diffs, diff)
}
log.Printf("[DEBUG] Returning %d diffs with actual content", len(diffs))
if capture.Enabled() {
payload := map[string]interface{}{
"owner": owner,
"repo": repo,
"number": number,
"diffs": diffs,
}
capture.WriteJSON("github-pr-diffs", payload)
}
return diffs, nil
}
// parsePatchIntoHunks parses a GitHub patch string into DiffHunk objects
func (p *GitHubProvider) parsePatchIntoHunks(patch string) []models.DiffHunk {
if patch == "" {
return nil
}
lines := strings.Split(patch, "\n")
var hunks []models.DiffHunk
var currentHunk *models.DiffHunk
var hunkContent strings.Builder
// Regex to match hunk headers like @@ -1,3 +1,4 @@
hunkHeaderRegex := regexp.MustCompile(`^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@`)
for _, line := range lines {
if match := hunkHeaderRegex.FindStringSubmatch(line); match != nil {
// Save previous hunk if exists
if currentHunk != nil {
currentHunk.Content = strings.TrimSuffix(hunkContent.String(), "\n")
hunks = append(hunks, *currentHunk)
hunkContent.Reset()
}
// Parse hunk header
oldStart, _ := strconv.Atoi(match[1])
oldCount := 1
if match[2] != "" {
oldCount, _ = strconv.Atoi(match[2])
}
newStart, _ := strconv.Atoi(match[3])
newCount := 1
if match[4] != "" {
newCount, _ = strconv.Atoi(match[4])
}
currentHunk = &models.DiffHunk{
OldStartLine: oldStart,
OldLineCount: oldCount,
NewStartLine: newStart,
NewLineCount: newCount,
}
// Include the header line in the content
hunkContent.WriteString(line + "\n")
} else if currentHunk != nil {
// Add content lines to current hunk
hunkContent.WriteString(line + "\n")
}
}
// Save the last hunk
if currentHunk != nil {
currentHunk.Content = strings.TrimSuffix(hunkContent.String(), "\n")
hunks = append(hunks, *currentHunk)
}
return hunks
}
// getFileType determines file type based on extension
func (p *GitHubProvider) getFileType(filename string) string {
parts := strings.Split(filename, ".")
if len(parts) > 1 {
return parts[len(parts)-1]
}
return "unknown"
}