internal/control/diffcomment.go
236 lines · 7796 bytes
1package control
2
3import (
4 "errors"
5 "fmt"
6 "io"
7 "slices"
8 "strconv"
9 "strings"
10
11 "gitbay.org/gitbay/internal/gitutil"
12 "gitbay.org/gitbay/internal/policy"
13 "gitbay.org/gitbay/internal/protocol"
14 "gitbay.org/gitbay/internal/store"
15)
16
17func init() {
18 register(Command{Path: []string{"mr", "diff-comment"},
19 Summary: "comment on a diff line",
20 Usage: "mr diff-comment <owner/name> <n> --path <file> --line <l> [--old] [--reply <id>] [--message <m> | --file -]",
21 ReadsStdin: true, Run: runDiffComment})
22 register(Command{Path: []string{"mr", "threads"},
23 Summary: "review threads on an MR",
24 Usage: "mr threads <owner/name> <n>", ReadOnly: true, Run: runMRThreads})
25 register(Command{Path: []string{"mr", "resolve"},
26 Summary: "resolve a review thread",
27 Usage: "mr resolve <owner/name> <n> <thread-id>", Run: runMRResolve})
28 register(Command{Path: []string{"mr", "unresolve"},
29 Summary: "reopen a review thread",
30 Usage: "mr unresolve <owner/name> <n> <thread-id>", Run: runMRUnresolve})
31}
32
33func runDiffComment(c *Ctx, args []string) int {
34 f, err := parseFlags(args, flagSpec{Values: []string{"--path", "--line", "--reply", "--message", "--file"}, Bools: []string{"--old"}, MaxPos: -1,
35 Usage: "mr diff-comment <owner/name> <n> --path <file> --line <l> [--old] [--reply <id>] [--message <m> | --file -]"})
36 if err != nil {
37 return c.fail(protocol.ExitUsage, "%v", err)
38 }
39 rest := f.Pos
40 path, message, file, old := f.Value("--path"), f.Value("--message"), f.Value("--file"), f.Has("--old")
41 var line, replyTo int64
42 if f.Has("--line") {
43 n, err := strconv.ParseInt(f.Value("--line"), 10, 64)
44 if err != nil || n < 1 {
45 return c.fail(protocol.ExitUsage, "--line must be a positive number")
46 }
47 line = n
48 }
49 if f.Has("--reply") {
50 n, err := strconv.ParseInt(f.Value("--reply"), 10, 64)
51 if err != nil || n < 1 {
52 return c.fail(protocol.ExitUsage, "--reply must be a thread id")
53 }
54 replyTo = n
55 }
56 repo, mr, code := mrRef(c, rest, policy.CanRead)
57 if code >= 0 {
58 return code
59 }
60 if code := refuseArchived(c, repo); code >= 0 {
61 return code
62 }
63 if replyTo == 0 && (path == "" || line == 0) {
64 return c.fail(protocol.ExitUsage, "a new thread needs --path and --line (or reply to one with --reply <id>)")
65 }
66 body, err := bodyFrom(c, message, file)
67 if err != nil {
68 return c.failErr(err)
69 }
70 if strings.TrimSpace(body) == "" {
71 return c.fail(protocol.ExitUsage, "empty comment; use --message or --file -")
72 }
73
74 side := "new"
75 if old {
76 side = "old"
77 }
78 if replyTo == 0 {
79 // The path must actually be part of the MR's diff.
80 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
81 base := mr.MergedBase
82 if base == "" {
83 b, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, mrHeadRef(mr.Number))
84 if err != nil {
85 return c.fail(protocol.ExitFailure, "%v", err)
86 }
87 base = b
88 }
89 files, err := gitutil.DiffFiles(dir, base, mrHeadRef(mr.Number))
90 if err != nil {
91 return c.fail(protocol.ExitFailure, "%v", err)
92 }
93 if !slices.Contains(files, path) {
94 return c.fail(protocol.ExitUsage, "%s is not part of this merge request's diff", path)
95 }
96 }
97
98 id, err := c.Store.AddDiffComment(mr.ID, c.User.ID, mr.HeadSHA, path, side, line, body, replyTo)
99 if err != nil {
100 if errors.Is(err, store.ErrNotFound) {
101 return c.fail(protocol.ExitNotFound, "%v", err)
102 }
103 return c.failErr(err)
104 }
105 if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
106 notify(c, parts, notice{repo: repo, kind: "mr",
107 subject: mrSubject(repo, mr.Number, mr.Title),
108 action: fmt.Sprintf("commented on %s:%d in !%d", path, line, mr.Number),
109 excerpt: body, path: fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
110 }
111 return c.emit(map[string]any{"id": id, "thread": firstNonZero(replyTo, id)}, func(w io.Writer) {
112 if replyTo != 0 {
113 fmt.Fprintf(w, "replied to thread %d on %s!%d\n", replyTo, repo.Path(), mr.Number)
114 } else {
115 fmt.Fprintf(w, "thread %d opened on %s:%d in %s!%d\n", id, path, line, repo.Path(), mr.Number)
116 }
117 })
118}
119
120func firstNonZero(a, b int64) int64 {
121 if a != 0 {
122 return a
123 }
124 return b
125}
126
127func runMRThreads(c *Ctx, args []string) int {
128 repo, mr, code := mrRef(c, args, policy.CanRead)
129 if code >= 0 {
130 return code
131 }
132 if len(args) != 2 {
133 return c.fail(protocol.ExitUsage, "usage: mr threads <owner/name> <n>")
134 }
135 comments, err := c.Store.ListDiffComments(mr.ID)
136 if err != nil {
137 return c.fail(protocol.ExitFailure, "%v", err)
138 }
139 type commentOut struct {
140 ID int64 `json:"id"`
141 Author string `json:"author"`
142 Body string `json:"body"`
143 CreatedAt string `json:"created_at"`
144 }
145 type threadOut struct {
146 ID int64 `json:"id"`
147 Path string `json:"path"`
148 Side string `json:"side"`
149 Line int64 `json:"line"`
150 Stale bool `json:"stale"`
151 Resolved string `json:"resolved_by,omitempty"`
152 Comments []commentOut `json:"comments"`
153 }
154 byRoot := map[int64]*threadOut{}
155 var order []int64
156 for _, cm := range comments {
157 if cm.ReplyTo == 0 {
158 byRoot[cm.ID] = &threadOut{
159 ID: cm.ID, Path: cm.Path, Side: cm.Side, Line: cm.Line,
160 Stale: cm.HeadSHA != mr.HeadSHA, Resolved: cm.ResolvedBy,
161 Comments: []commentOut{{cm.ID, cm.Author, cm.Body, cm.CreatedAt}},
162 }
163 order = append(order, cm.ID)
164 } else if th, ok := byRoot[cm.ReplyTo]; ok {
165 th.Comments = append(th.Comments, commentOut{cm.ID, cm.Author, cm.Body, cm.CreatedAt})
166 }
167 }
168 var ds []threadOut
169 for _, id := range order {
170 ds = append(ds, *byRoot[id])
171 }
172 _ = repo
173 return c.emit(ds, func(w io.Writer) {
174 for _, th := range ds {
175 marks := ""
176 if th.Resolved != "" {
177 marks += " [resolved by " + th.Resolved + "]"
178 }
179 if th.Stale {
180 marks += " [stale]"
181 }
182 fmt.Fprintf(w, "thread %d %s:%d (%s)%s\n", th.ID, th.Path, th.Line, th.Side, marks)
183 for _, cm := range th.Comments {
184 fmt.Fprintf(w, " %s: %s\n", cm.Author, cm.Body)
185 }
186 }
187 })
188}
189
190func setThreadResolved(c *Ctx, args []string, resolved bool) int {
191 if len(args) != 3 {
192 return c.fail(protocol.ExitUsage, "usage: mr resolve|unresolve <owner/name> <n> <thread-id>")
193 }
194 repo, mr, code := mrRef(c, args[:2], policy.CanRead)
195 if code >= 0 {
196 return code
197 }
198 if code := refuseArchived(c, repo); code >= 0 {
199 return code
200 }
201 threadID, err := strconv.ParseInt(args[2], 10, 64)
202 if err != nil {
203 return c.fail(protocol.ExitUsage, "bad thread id %q", args[2])
204 }
205 // Thread author, MR author, or anyone with write may resolve.
206 author, err := c.Store.DiffCommentAuthor(mr.ID, threadID)
207 if errors.Is(err, store.ErrNotFound) {
208 return c.fail(protocol.ExitNotFound, "no thread %d on %s!%d", threadID, repo.Path(), mr.Number)
209 }
210 if err != nil {
211 return c.fail(protocol.ExitFailure, "%v", err)
212 }
213 grant, err := c.Store.AccessRole(repo.ID, c.User.ID)
214 if err != nil {
215 return c.fail(protocol.ExitFailure, "%v", err)
216 }
217 if author != c.User.ID && mr.Author != c.User.Username && !policy.CanWrite(c.User, repo, grant) {
218 return c.fail(protocol.ExitDenied, "only the thread author, the MR author, or users with write access can resolve threads")
219 }
220 if err := c.Store.SetThreadResolved(mr.ID, threadID, c.User.ID, resolved); err != nil {
221 if errors.Is(err, store.ErrNotFound) {
222 return c.fail(protocol.ExitNotFound, "no thread %d (replies cannot be resolved; use the root id)", threadID)
223 }
224 return c.fail(protocol.ExitFailure, "%v", err)
225 }
226 verb := "resolved"
227 if !resolved {
228 verb = "reopened"
229 }
230 return c.emit(map[string]any{"thread": threadID, "resolved": resolved}, func(w io.Writer) {
231 fmt.Fprintf(w, "%s thread %d on %s!%d\n", verb, threadID, repo.Path(), mr.Number)
232 })
233}
234
235func runMRResolve(c *Ctx, args []string) int { return setThreadResolved(c, args, true) }
236func runMRUnresolve(c *Ctx, args []string) int { return setThreadResolved(c, args, false) }