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