-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathgithub.go
More file actions
1067 lines (975 loc) · 31.2 KB
/
github.go
File metadata and controls
1067 lines (975 loc) · 31.2 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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
)
// ghComment represents a GitHub PR review comment from the API.
type ghComment struct {
ID int64 `json:"id"`
Path string `json:"path"`
Line int `json:"line"` // end line in the diff (RIGHT side = new file line)
StartLine int `json:"start_line"` // start line for multi-line comments (0 if single-line)
Side string `json:"side"` // "RIGHT" or "LEFT"
Body string `json:"body"`
User struct {
Login string `json:"login"`
} `json:"user"`
CreatedAt string `json:"created_at"`
InReplyToID int64 `json:"in_reply_to_id"`
}
// requireGH checks that the gh CLI is installed and authenticated.
func requireGH() error {
if _, err := exec.LookPath("gh"); err != nil {
return fmt.Errorf("gh CLI not found. Install it: https://cli.github.com")
}
cmd := exec.Command("gh", "auth", "status")
cmd.Stdout = nil
cmd.Stderr = nil
if err := cmd.Run(); err != nil {
return fmt.Errorf("gh is not authenticated. Run: gh auth login")
}
return nil
}
// detectPR returns the PR number for the current branch.
// If prFlag is non-zero, it's used directly.
func detectPR(prFlag int) (int, error) {
if prFlag > 0 {
return prFlag, nil
}
out, err := exec.Command("gh", "pr", "view", "--json", "number", "--jq", ".number").Output()
if err != nil {
return 0, fmt.Errorf("no PR found for current branch (try: crit pull <pr-number>)")
}
n, err := strconv.Atoi(strings.TrimSpace(string(out)))
if err != nil {
return 0, fmt.Errorf("unexpected PR number: %s", string(out))
}
return n, nil
}
// PRInfo holds metadata about the PR for the current branch.
type PRInfo struct {
URL string `json:"url"`
Number int `json:"number"`
Title string `json:"title"`
IsDraft bool `json:"isDraft"`
State string `json:"state"`
Body string `json:"body"`
BaseRefName string `json:"baseRefName"`
HeadRefName string `json:"headRefName"`
Additions int `json:"additions"`
Deletions int `json:"deletions"`
ChangedFiles int `json:"changedFiles"`
AuthorLogin string `json:"authorLogin"`
CreatedAt string `json:"createdAt"`
}
// prAuthor is used to unmarshal the nested author field from gh output.
type prAuthor struct {
Login string `json:"login"`
}
// prInfoRaw mirrors the gh JSON output shape (author is nested).
type prInfoRaw struct {
URL string `json:"url"`
Number int `json:"number"`
Title string `json:"title"`
IsDraft bool `json:"isDraft"`
State string `json:"state"`
Body string `json:"body"`
BaseRefName string `json:"baseRefName"`
HeadRefName string `json:"headRefName"`
Additions int `json:"additions"`
Deletions int `json:"deletions"`
ChangedFiles int `json:"changedFiles"`
Author prAuthor `json:"author"`
CreatedAt string `json:"createdAt"`
}
// detectPRInfo returns PR metadata for the current branch.
// Returns nil if gh is unavailable or no PR exists.
func detectPRInfo() *PRInfo {
if err := requireGH(); err != nil {
return nil
}
out, err := exec.Command("gh", "pr", "view", "--json",
"number,url,title,isDraft,state,body,baseRefName,headRefName,additions,deletions,changedFiles,author,createdAt").Output()
if err != nil {
return nil
}
var raw prInfoRaw
if err := json.Unmarshal(out, &raw); err != nil {
return nil
}
if raw.URL == "" {
return nil
}
return &PRInfo{
URL: raw.URL,
Number: raw.Number,
Title: raw.Title,
IsDraft: raw.IsDraft,
State: raw.State,
Body: raw.Body,
BaseRefName: raw.BaseRefName,
HeadRefName: raw.HeadRefName,
Additions: raw.Additions,
Deletions: raw.Deletions,
ChangedFiles: raw.ChangedFiles,
AuthorLogin: raw.Author.Login,
CreatedAt: raw.CreatedAt,
}
}
// fetchPRComments fetches all review comments for a PR.
func fetchPRComments(prNumber int) ([]ghComment, error) {
// Use --paginate --slurp to collect all pages into a single JSON structure.
// --slurp wraps each page into an outer array: [[page1...], [page2...], ...]
// So we unmarshal into [][]ghComment and flatten.
out, err := exec.Command("gh", "api",
fmt.Sprintf("repos/{owner}/{repo}/pulls/%d/comments", prNumber),
"--paginate",
"--slurp",
).Output()
if err != nil {
return nil, fmt.Errorf("fetching PR comments: %w", err)
}
var pages [][]ghComment
if err := json.Unmarshal(out, &pages); err != nil {
return nil, fmt.Errorf("parsing PR comments: %w", err)
}
var comments []ghComment
for _, page := range pages {
comments = append(comments, page...)
}
return comments, nil
}
// nextCommentID scans ALL files' comments in a CritJSON and returns the next
// available globally-unique cN ID. This ensures IDs don't collide across files.
func nextCommentID(files map[string]CritJSONFile) int {
next := 1
for _, cf := range files {
for _, c := range cf.Comments {
id := 0
_, _ = fmt.Sscanf(c.ID, "c%d", &id)
if id >= next {
next = id + 1
}
}
}
return next
}
// isDuplicateGHComment checks if a GitHub comment already exists in the comment list.
// If ghID is non-zero, matches by GitHubID. Otherwise falls back to author+lines+body.
func isDuplicateGHComment(comments []Comment, ghID int64, author string, startLine, endLine int, body string) bool {
for _, c := range comments {
if ghID != 0 && c.GitHubID == ghID {
return true
}
if c.Author == author && c.StartLine == startLine && c.EndLine == endLine && c.Body == body {
return true
}
}
return false
}
// isDuplicateGHReply checks if a GitHub reply already exists in the reply list by GitHubID.
func isDuplicateGHReply(replies []Reply, ghID int64) bool {
for _, r := range replies {
if r.GitHubID == ghID {
return true
}
}
return false
}
// findCommentByGitHubID searches all files in a CritJSON for a comment with the given GitHubID.
// Returns the file path, comment index, and true if found.
func findCommentByGitHubID(cj *CritJSON, ghID int64) (string, int, bool) {
for path, cf := range cj.Files {
for i, c := range cf.Comments {
if c.GitHubID == ghID {
return path, i, true
}
}
}
return "", 0, false
}
// mergeGHComments appends GitHub PR comments into an existing CritJSON.
// Only includes RIGHT-side comments (comments on the new version of the file).
// Handles threading: root comments become top-level Comments, replies become Reply entries.
// Deduplicates by GitHubID (preferred) or author+lines+body to prevent duplicates from repeated pulls.
func mergeGHComments(cj *CritJSON, ghComments []ghComment) int {
now := time.Now().UTC().Format(time.RFC3339)
cj.UpdatedAt = now
added := 0
// Separate roots from replies, filtering as we go
var roots []ghComment
var replies []ghComment
for _, gc := range ghComments {
if gc.Line == 0 {
continue // skip PR-level comments not attached to a line
}
if gc.Side == "LEFT" {
continue // skip comments on deleted/old lines
}
if gc.InReplyToID == 0 {
roots = append(roots, gc)
} else {
replies = append(replies, gc)
}
}
// Group replies by their parent (InReplyToID)
replyMap := make(map[int64][]ghComment)
for _, r := range replies {
replyMap[r.InReplyToID] = append(replyMap[r.InReplyToID], r)
}
// Sort each reply group by created_at
for parentID := range replyMap {
sort.Slice(replyMap[parentID], func(i, j int) bool {
return replyMap[parentID][i].CreatedAt < replyMap[parentID][j].CreatedAt
})
}
// Process root comments: create Comment with attached replies
for _, gc := range roots {
cf, ok := cj.Files[gc.Path]
if !ok {
cf = CritJSONFile{
Status: "modified",
Comments: []Comment{},
}
}
startLine := gc.StartLine
if startLine == 0 {
startLine = gc.Line // single-line comment
}
// Skip if this root comment already exists (dedup for repeated pulls)
if isDuplicateGHComment(cf.Comments, gc.ID, gc.User.Login, startLine, gc.Line, gc.Body) {
// Even if root is a dupe, check if there are new replies to add
if childReplies, hasReplies := replyMap[gc.ID]; hasReplies {
// Find the existing comment
for ci, c := range cf.Comments {
if c.GitHubID == gc.ID {
for _, r := range childReplies {
if isDuplicateGHReply(cf.Comments[ci].Replies, r.ID) {
continue
}
cf.Comments[ci].Replies = append(cf.Comments[ci].Replies, Reply{
ID: nextReplyID(c.ID, cf.Comments[ci].Replies),
Body: r.Body,
Author: r.User.Login,
CreatedAt: r.CreatedAt,
GitHubID: r.ID,
})
added++
}
break
}
}
cj.Files[gc.Path] = cf
}
continue
}
commentID := fmt.Sprintf("c%d", nextCommentID(cj.Files))
comment := Comment{
ID: commentID,
StartLine: startLine,
EndLine: gc.Line,
Body: gc.Body,
Author: gc.User.Login,
CreatedAt: gc.CreatedAt,
UpdatedAt: now,
GitHubID: gc.ID,
}
// Attach replies for this root
if childReplies, hasReplies := replyMap[gc.ID]; hasReplies {
for _, r := range childReplies {
comment.Replies = append(comment.Replies, Reply{
ID: nextReplyID(commentID, comment.Replies),
Body: r.Body,
Author: r.User.Login,
CreatedAt: r.CreatedAt,
GitHubID: r.ID,
})
added++
}
}
cf.Comments = append(cf.Comments, comment)
cj.Files[gc.Path] = cf
added++ // count the root
}
// Process orphan replies: parent already exists in cj (from a previous pull)
for parentID, childReplies := range replyMap {
// Skip if we already handled this parent in the roots loop above
handled := false
for _, gc := range roots {
if gc.ID == parentID {
handled = true
break
}
}
if handled {
continue
}
// Find the parent comment in the existing CritJSON
filePath, ci, found := findCommentByGitHubID(cj, parentID)
if !found {
continue // orphan reply with no known parent — skip
}
cf := cj.Files[filePath]
for _, r := range childReplies {
if isDuplicateGHReply(cf.Comments[ci].Replies, r.ID) {
continue
}
cf.Comments[ci].Replies = append(cf.Comments[ci].Replies, Reply{
ID: nextReplyID(cf.Comments[ci].ID, cf.Comments[ci].Replies),
Body: r.Body,
Author: r.User.Login,
CreatedAt: r.CreatedAt,
GitHubID: r.ID,
})
added++
}
cj.Files[filePath] = cf
}
return added
}
// resolveCritDir returns the directory where .crit.json should be read/written.
// If outputDir is non-empty it is used directly. Otherwise falls back to repo root then CWD.
func resolveCritDir(outputDir string) (string, error) {
if outputDir != "" {
abs, err := filepath.Abs(outputDir)
if err != nil {
return "", fmt.Errorf("resolving output directory: %w", err)
}
return abs, nil
}
// When crit is launched as "crit file.md", .crit.json is written to
// filepath.Dir(file.md), not the repo root. If there is exactly one
// running session for this cwd with file args, mirror that logic so
// crit comment finds the right .crit.json without needing --output.
if cwd, err := resolvedCWD(); err == nil {
if sessions, _ := listSessionsForCWD(cwd); len(sessions) == 1 && len(sessions[0].Args) > 0 {
return filepath.Dir(filepath.Join(sessions[0].CWD, sessions[0].Args[0])), nil
}
}
root, err := RepoRoot()
if err != nil {
root, err = os.Getwd()
if err != nil {
return "", fmt.Errorf("getting working directory: %w", err)
}
}
return root, nil
}
// writeCritJSON resolves the output directory and writes a CritJSON via saveCritJSON.
// Deprecated: prefer saveCritJSON directly when the crit path is already known.
func writeCritJSON(cj CritJSON, outputDir string) error {
root, err := resolveCritDir(outputDir)
if err != nil {
return err
}
return saveCritJSON(filepath.Join(root, ".crit.json"), cj)
}
// ghReplyForPush represents a reply that needs to be posted to GitHub.
type ghReplyForPush struct {
ParentGHID int64
Body string
}
// collectNewRepliesForPush finds replies that haven't been pushed to GitHub yet.
// A reply needs pushing if its GitHubID is 0 (local-only) and its parent Comment has a GitHubID (on GitHub).
func collectNewRepliesForPush(cf CritJSONFile) []ghReplyForPush {
var replies []ghReplyForPush
for _, c := range cf.Comments {
if c.GitHubID == 0 {
continue // root not on GitHub, can't reply to it
}
for _, r := range c.Replies {
if r.GitHubID == 0 {
replies = append(replies, ghReplyForPush{
ParentGHID: c.GitHubID,
Body: r.Body,
})
}
}
}
return replies
}
// postGHReply posts a reply to an existing GitHub PR review comment.
// Returns the GitHub ID of the newly created reply.
func postGHReply(prNumber int, parentGHID int64, body string) (int64, error) {
payload, err := json.Marshal(map[string]any{
"body": body,
"in_reply_to": parentGHID,
})
if err != nil {
return 0, fmt.Errorf("marshal reply: %w", err)
}
cmd := exec.Command("gh", "api",
fmt.Sprintf("repos/{owner}/{repo}/pulls/%d/comments", prNumber),
"--method", "POST",
"--input", "-",
)
cmd.Stdin = bytes.NewReader(payload)
output, err := cmd.CombinedOutput()
if err != nil {
return 0, fmt.Errorf("gh api: %s: %w", string(output), err)
}
var resp struct {
ID int64 `json:"id"`
}
if err := json.Unmarshal(output, &resp); err != nil {
return 0, fmt.Errorf("parsing reply response: %w", err)
}
return resp.ID, nil
}
// critJSONToGHComments converts .crit.json comments to GitHub review comment format.
// Returns the list of comments suitable for the GitHub "create review" API.
func critJSONToGHComments(cj CritJSON) []map[string]any {
var result []map[string]any
for path, cf := range cj.Files {
for _, c := range cf.Comments {
if c.Resolved {
continue // don't post resolved comments
}
if c.GitHubID != 0 {
continue // already pushed
}
comment := map[string]any{
"path": path,
"line": c.EndLine,
"side": "RIGHT",
"body": c.Body,
}
if c.StartLine != c.EndLine {
comment["start_line"] = c.StartLine
comment["start_side"] = "RIGHT"
}
result = append(result, comment)
}
}
return result
}
// parsePushEvent maps a user-facing event flag value to the GitHub API event string.
// Valid values: "" or "comment" -> "COMMENT", "approve" -> "APPROVE", "request-changes" -> "REQUEST_CHANGES".
func parsePushEvent(flag string) (string, error) {
switch flag {
case "", "comment":
return "COMMENT", nil
case "approve":
return "APPROVE", nil
case "request-changes":
return "REQUEST_CHANGES", nil
default:
return "", fmt.Errorf("invalid --event value %q (valid: comment, approve, request-changes)", flag)
}
}
// buildReviewPayload constructs the JSON body for a GitHub PR review request.
func buildReviewPayload(comments []map[string]any, message string, event string) ([]byte, error) {
if comments == nil {
comments = []map[string]any{}
}
review := map[string]any{
"event": event,
"body": message,
"comments": comments,
}
return json.Marshal(review)
}
// createGHReview posts a review with inline comments to a GitHub PR.
// message is the top-level review body (empty string posts no top-level comment).
// Returns a map of "path:endLine" -> GitHubID for each created comment.
func createGHReview(prNumber int, comments []map[string]any, message string, event string) (map[string]int64, error) {
data, err := buildReviewPayload(comments, message, event)
if err != nil {
return nil, fmt.Errorf("marshaling review: %w", err)
}
var stdout, stderr bytes.Buffer
cmd := exec.Command("gh", "api",
fmt.Sprintf("repos/{owner}/{repo}/pulls/%d/reviews", prNumber),
"--method", "POST",
"--input", "-",
)
cmd.Stdin = bytes.NewReader(data)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
if stderr.Len() > 0 {
return nil, fmt.Errorf("creating review: %s", strings.TrimSpace(stderr.String()))
}
return nil, fmt.Errorf("creating review: %w", err)
}
// Parse review ID from response, then fetch its comments in a second call.
// The create-review response does not include comment objects — only the review itself.
var reviewResp struct {
ID int64 `json:"id"`
}
idMap := make(map[string]int64)
if err := json.Unmarshal(stdout.Bytes(), &reviewResp); err != nil || reviewResp.ID == 0 {
return idMap, nil // non-fatal: review was created, just can't map IDs
}
// Fetch this review's comments and zip with our input to map IDs by position.
// We use the review-scoped endpoint (only returns this review's comments, in order).
commentOut, err := exec.Command("gh", "api",
fmt.Sprintf("repos/{owner}/{repo}/pulls/%d/reviews/%d/comments", prNumber, reviewResp.ID),
).Output()
if err != nil {
return idMap, nil // non-fatal
}
var reviewComments []struct {
ID int64 `json:"id"`
}
if err := json.Unmarshal(commentOut, &reviewComments); err == nil {
for i, rc := range reviewComments {
if i < len(comments) {
path, _ := comments[i]["path"].(string)
line, _ := comments[i]["line"].(int)
key := fmt.Sprintf("%s:%d", path, line)
idMap[key] = rc.ID
}
}
}
return idMap, nil
}
// replyKey uniquely identifies a reply for GitHubID mapping after push.
type replyKey struct {
ParentGHID int64
BodyPrefix string
}
// updateCritJSONWithGitHubIDs writes GitHub IDs back to .crit.json after a push.
// commentIDs maps "path:endLine" -> GitHubID for root comments.
// replyIDs maps replyKey -> GitHubID for replies.
func updateCritJSONWithGitHubIDs(critPath string, commentIDs map[string]int64, replyIDs map[replyKey]int64) error {
data, err := os.ReadFile(critPath)
if err != nil {
return err
}
var cj CritJSON
if err := json.Unmarshal(data, &cj); err != nil {
return err
}
for path, cf := range cj.Files {
for i, c := range cf.Comments {
if c.GitHubID == 0 {
key := fmt.Sprintf("%s:%d", path, c.EndLine)
if id, ok := commentIDs[key]; ok {
cf.Comments[i].GitHubID = id
}
}
for j, r := range c.Replies {
if r.GitHubID == 0 && cf.Comments[i].GitHubID != 0 {
rk := replyKey{ParentGHID: cf.Comments[i].GitHubID, BodyPrefix: truncateStr(r.Body, 60)}
if id, ok := replyIDs[rk]; ok {
cf.Comments[i].Replies[j].GitHubID = id
}
}
}
}
cj.Files[path] = cf
}
out, err := json.MarshalIndent(cj, "", " ")
if err != nil {
return err
}
return os.WriteFile(critPath, append(out, '\n'), 0644)
}
// truncateStr returns the first n runes of s, or all of s if shorter.
func truncateStr(s string, n int) string {
r := []rune(s)
if len(r) <= n {
return s
}
return string(r[:n])
}
// loadCritJSON reads .crit.json from disk, or returns a fresh CritJSON if the file doesn't exist.
func loadCritJSON(critPath string) (CritJSON, error) {
var cj CritJSON
if data, err := os.ReadFile(critPath); err == nil {
if err := json.Unmarshal(data, &cj); err != nil {
return cj, fmt.Errorf("invalid existing .crit.json: %w", err)
}
} else if os.IsNotExist(err) {
branch := CurrentBranch()
cfg := LoadConfig(filepath.Dir(critPath))
base := cfg.BaseBranch
if base == "" {
base = DefaultBranch()
}
baseRef, _ := MergeBase(base)
cj = CritJSON{
Branch: branch,
BaseRef: baseRef,
ReviewRound: 1,
Files: make(map[string]CritJSONFile),
}
} else {
return cj, fmt.Errorf("reading .crit.json: %w", err)
}
return cj, nil
}
// saveCritJSON writes the CritJSON struct to disk with pretty-printed JSON
// and a trailing newline for POSIX compliance and consistency with updateCritJSONWithGitHubIDs.
func saveCritJSON(critPath string, cj CritJSON) error {
data, err := json.MarshalIndent(cj, "", " ")
if err != nil {
return fmt.Errorf("marshaling .crit.json: %w", err)
}
return os.WriteFile(critPath, append(data, '\n'), 0644)
}
// appendComment adds a comment to the CritJSON struct in memory. Does not write to disk.
func appendComment(cj *CritJSON, filePath string, startLine, endLine int, body, author string) {
now := time.Now().UTC().Format(time.RFC3339)
cj.UpdatedAt = now
cf, ok := cj.Files[filePath]
if !ok {
cf = CritJSONFile{
Status: "modified",
Comments: []Comment{},
}
}
cf.Comments = append(cf.Comments, Comment{
ID: fmt.Sprintf("c%d", nextCommentID(cj.Files)),
StartLine: startLine,
EndLine: endLine,
Body: body,
Author: author,
CreatedAt: now,
UpdatedAt: now,
})
cj.Files[filePath] = cf
}
// appendReply adds a reply to an existing comment in the CritJSON struct in memory.
// Returns an error if the comment ID is not found or is ambiguous across files.
// Searches both file comments and review_comments.
func appendReply(cj *CritJSON, commentID, body, author string, resolve bool, filterPath string) error {
now := time.Now().UTC().Format(time.RFC3339)
cj.UpdatedAt = now
// Check all review comments (not just those starting with "r" — web-fetched ones use "web-N").
for i, c := range cj.ReviewComments {
if c.ID == commentID {
reply := Reply{
ID: nextReplyID(commentID, c.Replies),
Body: body,
Author: author,
CreatedAt: now,
}
cj.ReviewComments[i].Replies = append(cj.ReviewComments[i].Replies, reply)
cj.ReviewComments[i].UpdatedAt = now
if resolve {
cj.ReviewComments[i].Resolved = true
}
return nil
}
}
// Search file comments
var found bool
var foundPaths []string
for filePath, cf := range cj.Files {
if filterPath != "" && filePath != filterPath {
continue
}
for i, c := range cf.Comments {
if c.ID == commentID {
foundPaths = append(foundPaths, filePath)
if !found {
found = true
reply := Reply{
ID: nextReplyID(commentID, c.Replies),
Body: body,
Author: author,
CreatedAt: now,
}
cf.Comments[i].Replies = append(cf.Comments[i].Replies, reply)
cf.Comments[i].UpdatedAt = now
if resolve {
cf.Comments[i].Resolved = true
}
cj.Files[filePath] = cf
}
}
}
}
if len(foundPaths) > 1 {
return fmt.Errorf("comment %q found in multiple files (%s); specify the file with \"file\" field",
commentID, strings.Join(foundPaths, ", "))
}
if !found {
if filterPath != "" {
return fmt.Errorf("comment %q not found in file %q in .crit.json", commentID, filterPath)
}
return fmt.Errorf("comment %q not found in .crit.json", commentID)
}
return nil
}
// addCommentToCritJSON appends a comment to .crit.json for the given file and line range.
// Creates .crit.json if it doesn't exist. Appends to existing comments if it does.
// Works in both git repos and plain directories (file mode).
// outputDir overrides the default location (repo root or CWD) when non-empty.
func addCommentToCritJSON(filePath string, startLine, endLine int, body string, author string, outputDir string) error {
root, err := resolveCritDir(outputDir)
if err != nil {
return err
}
cleaned := filepath.Clean(filePath)
if filepath.IsAbs(cleaned) || strings.HasPrefix(cleaned, "..") {
return fmt.Errorf("path %q must be relative and within the repository", filePath)
}
critPath := filepath.Join(root, ".crit.json")
cj, err := loadCritJSON(critPath)
if err != nil {
return err
}
appendComment(&cj, cleaned, startLine, endLine, body, author)
return saveCritJSON(critPath, cj)
}
// addReplyToCritJSON adds a reply to an existing comment in .crit.json.
// It searches all files for the comment ID. If resolve is true, it also marks the comment as resolved.
func addReplyToCritJSON(commentID, body, author string, resolve bool, outputDir string, filterPath string) error {
root, err := resolveCritDir(outputDir)
if err != nil {
return err
}
critPath := filepath.Join(root, ".crit.json")
cj, err := loadCritJSON(critPath)
if err != nil {
return err
}
if err := appendReply(&cj, commentID, body, author, resolve, filterPath); err != nil {
return err
}
return saveCritJSON(critPath, cj)
}
// clearCritJSON removes .crit.json from the repo root, working directory, or outputDir.
func clearCritJSON(outputDir string) error {
root, err := resolveCritDir(outputDir)
if err != nil {
return err
}
critPath := filepath.Join(root, ".crit.json")
if err := os.Remove(critPath); err != nil && !os.IsNotExist(err) {
return err
}
return nil
}
// BulkCommentEntry represents one entry in a bulk comment JSON array.
// Supports review-level, file-level, line-level comments, and replies.
type BulkCommentEntry struct {
// New comment fields
File string `json:"file,omitempty"`
Path string `json:"path,omitempty"` // alias for File
Line int `json:"-"` // parsed from "line" (int or string like "45-47")
LineSpec string `json:"-"` // string line spec like "45-47" (from "line" field)
EndLine int `json:"end_line,omitempty"` // defaults to Line if omitted
Body string `json:"body"`
Author string `json:"author,omitempty"` // overrides per-entry; falls back to global
Scope string `json:"scope,omitempty"` // "review", "file", or "" (inferred)
// Reply fields
ReplyTo string `json:"reply_to,omitempty"`
Resolve bool `json:"resolve,omitempty"`
}
// UnmarshalJSON implements custom JSON unmarshaling for BulkCommentEntry
// to handle the "line" field being either an int (42) or a string ("45-47").
func (e *BulkCommentEntry) UnmarshalJSON(data []byte) error {
// Use an alias to avoid infinite recursion
type Alias BulkCommentEntry
aux := &struct {
Line json.RawMessage `json:"line,omitempty"`
*Alias
}{
Alias: (*Alias)(e),
}
if err := json.Unmarshal(data, aux); err != nil {
return err
}
if len(aux.Line) > 0 {
// Try int first
var lineInt int
if err := json.Unmarshal(aux.Line, &lineInt); err == nil {
e.Line = lineInt
return nil
}
// Try string
var lineStr string
if err := json.Unmarshal(aux.Line, &lineStr); err == nil {
e.LineSpec = lineStr
return nil
}
}
return nil
}
// bulkAddCommentsToCritJSON applies multiple comments and replies in a single load-save cycle.
// globalAuthor is used when an entry doesn't specify its own author.
// outputDir overrides the .crit.json location (empty = repo root or CWD).
func bulkAddCommentsToCritJSON(entries []BulkCommentEntry, globalAuthor string, outputDir string) error {
if len(entries) == 0 {
return fmt.Errorf("no comment entries provided")
}
root, err := resolveCritDir(outputDir)
if err != nil {
return err
}
critPath := filepath.Join(root, ".crit.json")
cj, err := loadCritJSON(critPath)
if err != nil {
return err
}
for i, e := range entries {
if e.Body == "" {
return fmt.Errorf("entry %d: body is required", i)
}
author := e.Author
if author == "" {
author = globalAuthor
}
if e.ReplyTo != "" {
// Reply mode
if err := appendReply(&cj, e.ReplyTo, e.Body, author, e.Resolve, e.File); err != nil {
return fmt.Errorf("entry %d: %w", i, err)
}
} else if e.Scope == "review" || (e.File == "" && e.Path == "" && e.Line <= 0 && e.LineSpec == "") {
// Review-level comment: explicit scope OR no file/line at all.
// But if Line > 0 or LineSpec is set, it's a line comment missing a file — error.
if e.Line > 0 || e.LineSpec != "" {
return fmt.Errorf("entry %d: file is required for new comments", i)
}
if e.Scope != "review" && (e.File != "" || e.Path != "") {
// Has a file but no scope — not a review comment
return fmt.Errorf("entry %d: file is required for new comments", i)
}
appendReviewComment(&cj, e.Body, author)
} else {
// Determine file path from File or Path field
filePath := e.File
if filePath == "" {
filePath = e.Path
}
if filePath == "" {
return fmt.Errorf("entry %d: file is required for new comments", i)
}
cleaned := filepath.Clean(filePath)
if filepath.IsAbs(cleaned) || strings.HasPrefix(cleaned, "..") {
return fmt.Errorf("entry %d: path %q must be relative and within the repository", i, filePath)
}
if e.Scope == "file" {
// Explicit file-level comment
appendFileComment(&cj, cleaned, e.Body, author)
} else if e.Line <= 0 && e.LineSpec == "" {
// No line specified — infer file-level only when using "path" field (new API),
// not "file" field (backward compat: "file" without line is an error).
if e.Path != "" && e.File == "" {
appendFileComment(&cj, cleaned, e.Body, author)
} else {
return fmt.Errorf("entry %d: line must be > 0", i)
}
} else {
// Line-level comment
startLine := e.Line
endLine := e.EndLine
// Support "line": "45-47" string format
if e.LineSpec != "" && startLine == 0 {
if dashIdx := strings.Index(e.LineSpec, "-"); dashIdx >= 0 {
s, err1 := strconv.Atoi(e.LineSpec[:dashIdx])
eVal, err2 := strconv.Atoi(e.LineSpec[dashIdx+1:])
if err1 != nil || err2 != nil {
return fmt.Errorf("entry %d: invalid line spec %q", i, e.LineSpec)
}
startLine, endLine = s, eVal
} else {
n, err := strconv.Atoi(e.LineSpec)
if err != nil {
return fmt.Errorf("entry %d: invalid line spec %q", i, e.LineSpec)
}
startLine, endLine = n, n
}
}
if startLine <= 0 {
return fmt.Errorf("entry %d: line must be > 0", i)
}
if endLine == 0 {
endLine = startLine
}
appendComment(&cj, cleaned, startLine, endLine, e.Body, author)
}
}
}
return saveCritJSON(critPath, cj)
}
// addReviewCommentToCritJSON adds a review-level comment to .crit.json.
func addReviewCommentToCritJSON(body, author, outputDir string) error {
root, err := resolveCritDir(outputDir)
if err != nil {
return err
}
critPath := filepath.Join(root, ".crit.json")
cj, err := loadCritJSON(critPath)
if err != nil {
return err
}
appendReviewComment(&cj, body, author)
return saveCritJSON(critPath, cj)
}
// addFileCommentToCritJSON adds a file-level comment to .crit.json.
func addFileCommentToCritJSON(filePath, body, author, outputDir string) error {
root, err := resolveCritDir(outputDir)
if err != nil {
return err
}