internal/control/mr.go
1613 lines · 58988 bytes
1package control
2
3import (
4 "errors"
5 "fmt"
6 "io"
7 "slices"
8 "strconv"
9 "strings"
10 "time"
11
12 "gitbay.org/gitbay/internal/gitutil"
13 "gitbay.org/gitbay/internal/policy"
14 "gitbay.org/gitbay/internal/protocol"
15 "gitbay.org/gitbay/internal/sig"
16 "gitbay.org/gitbay/internal/store"
17)
18
19func init() {
20 register(Command{Path: []string{"repo", "fork"},
21 Summary: "fork a repository under your account",
22 Usage: "repo fork <owner/name> [--name <n>]", Run: runRepoFork})
23 register(Command{Path: []string{"repo", "settings", "require-approvals"},
24 Summary: "require N fresh approvals to merge",
25 Usage: "repo settings require-approvals <owner/name> <n> (0 = off)", Run: runRequireApprovals})
26 register(Command{Path: []string{"repo", "settings", "require-resolved"},
27 Summary: "require all review threads resolved to merge",
28 Usage: "repo settings require-resolved <owner/name> on|off", Run: runRequireResolved})
29 register(Command{Path: []string{"repo", "settings", "require-codeowners"},
30 Summary: "require an owner's approval for every file CODEOWNERS covers",
31 Usage: "repo settings require-codeowners <owner/name> on|off", Run: runRequireCodeowners})
32 register(Command{Path: []string{"repo", "settings", "require-checks"},
33 Summary: "gate merges on green statuses",
34 Usage: "repo settings require-checks <owner/name> on|off", Run: runRequireChecks})
35 register(Command{Path: []string{"repo", "settings", "require-mr"},
36 Summary: "protected branches take changes through merge requests only",
37 Usage: "repo settings require-mr <owner/name> on|off", Run: runRequireMR})
38 register(Command{Path: []string{"repo", "settings", "require-signed"},
39 Summary: "require verified commit signatures",
40 Usage: "repo settings require-signed <owner/name> on|off", Run: runRequireSigned})
41 register(Command{Path: []string{"mr", "create"},
42 Summary: "open a merge request",
43 Usage: "mr create <target owner/name> --source [owner/name:]<branch> --target <branch> --title <t> [--body <b> | --file -] [--format md|org] [--draft]",
44 ReadsStdin: true, Run: runMRCreate})
45 register(Command{Path: []string{"mr", "range-diff"},
46 Summary: "what changed between two revisions of a merge request",
47 Usage: "mr range-diff <owner/name> <n> [--from <sha>] [--to <sha>]",
48 ReadOnly: true, Run: runMRRangeDiff})
49 register(Command{Path: []string{"mr", "revisions"},
50 Summary: "the heads a merge request has had",
51 Usage: "mr revisions <owner/name> <n>",
52 ReadOnly: true, Run: runMRRevisions})
53 register(Command{Path: []string{"mr", "draft"},
54 Summary: "mark a merge request as work in progress",
55 Usage: "mr draft <owner/name> <n>", Run: runMRDraft})
56 register(Command{Path: []string{"mr", "ready"},
57 Summary: "take the draft mark off, so it can merge",
58 Usage: "mr ready <owner/name> <n>", Run: runMRReady})
59 register(Command{Path: []string{"mr", "list"},
60 Summary: "list merge requests",
61 Usage: "mr list <owner/name> [--state open|merged|closed|source_gone|all] [--author <user>] [--milestone <title>|none] [--search <text>] [--limit <n>] [--cursor <c>]", ReadOnly: true, Run: runMRList})
62 register(Command{Path: []string{"mr", "show"},
63 Summary: "show a merge request",
64 Usage: "mr show <owner/name> <n>", ReadOnly: true, Run: runMRShow})
65 register(Command{Path: []string{"mr", "diff"},
66 Summary: "show the diff",
67 Usage: "mr diff <owner/name> <n>", ReadOnly: true, Run: runMRDiff})
68 register(Command{Path: []string{"mr", "edit"},
69 Summary: "edit title or body",
70 Usage: "mr edit <owner/name> <n> [--title <t>] [--body <b> | --file -] [--format md|org]",
71 ReadsStdin: true, Run: runMREdit})
72 register(Command{Path: []string{"mr", "retarget"},
73 Summary: "retarget onto another branch",
74 Usage: "mr retarget <owner/name> <n> <branch>", Run: runMRRetarget})
75 register(Command{Path: []string{"mr", "comment"},
76 Summary: "comment",
77 Usage: "mr comment <owner/name> <n> [--message <m> | --file -] [--format md|org]",
78 ReadsStdin: true, Run: runMRComment})
79 register(Command{Path: []string{"mr", "review"},
80 Summary: "review",
81 Usage: "mr review <owner/name> <n> --approve|--request-changes|--comment|--discard", Run: runMRReview})
82 register(Command{Path: []string{"mr", "review", "request"},
83 Summary: "ask specific people for a review",
84 Usage: "mr review request <owner/name> <n> [--add <user>]... [--remove <user>]...", Run: runMRReviewRequest})
85 register(Command{Path: []string{"mr", "merge"},
86 Summary: "merge",
87 Usage: "mr merge <owner/name> <n> [--strategy ff|merge|squash|rebase]", Run: runMRMerge})
88 register(Command{Path: []string{"mr", "close"},
89 Summary: "close without merging",
90 Usage: "mr close <owner/name> <n>", Run: runMRClose})
91}
92
93// ForkOut is what `repo fork` emits: where the fork landed, and what it
94// came from. Named so the web can send a person to the new repository.
95type ForkOut struct {
96 Path string `json:"path"`
97 ForkOf string `json:"fork_of"`
98}
99
100func runRepoFork(c *Ctx, args []string) int {
101 f, err := parseFlags(args, flagSpec{Values: []string{"--name"}, MaxPos: 1, Usage: "repo fork <owner/name> [--name <n>]"})
102 if err != nil {
103 return c.fail(protocol.ExitUsage, "%v", err)
104 }
105 path, name := f.pos(0), f.Value("--name")
106 if path == "" {
107 return c.fail(protocol.ExitUsage, "usage: repo fork <owner/name> [--name <n>]")
108 }
109 src, code := resolveRepo(c, path, policy.CanRead)
110 if code >= 0 {
111 return code
112 }
113 if name == "" {
114 name = src.Name
115 }
116 if err := policy.ValidateName(name); err != nil {
117 return c.failErr(err)
118 }
119 repoCreateMu.Lock()
120 if code := checkRepoQuota(c); code >= 0 {
121 repoCreateMu.Unlock()
122 return code
123 }
124 id, err := c.Store.CreateFork("user", c.User.ID, name, src.Visibility, src.ID)
125 repoCreateMu.Unlock()
126 if err != nil {
127 return c.fail(protocol.ExitFailure, "%v", err)
128 }
129 dstDir := RepoDir(c.Cfg.Server.Root, c.User.Username, name)
130 srcDir := RepoDir(c.Cfg.Server.Root, src.OwnerName, src.Name)
131 if err := gitutil.InitBare(dstDir, "main", HooksDir(c.Cfg.Server.Root)); err != nil {
132 c.Store.DeleteRepo(id)
133 return c.fail(protocol.ExitFailure, "%v", err)
134 }
135 if desc := gitutil.ReadDescription(srcDir); desc != "" {
136 gitutil.WriteDescription(dstDir, desc)
137 }
138 if err := gitutil.FetchInto(dstDir, srcDir, "refs/heads/*", "refs/heads/*"); err != nil {
139 // Empty source repos have nothing to fetch; that is fine.
140 if _, rerr := gitutil.ResolveRef(srcDir, src.DefaultBranch); rerr == nil {
141 c.Store.DeleteRepo(id)
142 return c.fail(protocol.ExitFailure, "copying refs: %v", err)
143 }
144 }
145 forkPath := c.User.Username + "/" + name
146 return c.emit(ForkOut{Path: forkPath, ForkOf: src.Path()}, func(w io.Writer) {
147 fmt.Fprintf(w, "forked %s to %s\n", src.Path(), forkPath)
148 })
149}
150
151func runRequireApprovals(c *Ctx, args []string) int {
152 if len(args) != 2 {
153 return c.fail(protocol.ExitUsage, "usage: repo settings require-approvals <owner/name> <n>")
154 }
155 n, err := strconv.Atoi(args[1])
156 if err != nil || n < 0 || n > 20 {
157 return c.fail(protocol.ExitUsage, "approvals must be 0..20")
158 }
159 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
160 if code >= 0 {
161 return code
162 }
163 s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.RequireApprovals = n })
164 if err != nil {
165 return c.fail(protocol.ExitFailure, "%v", err)
166 }
167 return c.emit(s, func(w io.Writer) {
168 fmt.Fprintf(w, "require_approvals %d on %s\n", n, repo.Path())
169 })
170}
171
172func runRequireResolved(c *Ctx, args []string) int {
173 if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
174 return c.fail(protocol.ExitUsage, "usage: repo settings require-resolved <owner/name> on|off")
175 }
176 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
177 if code >= 0 {
178 return code
179 }
180 s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.RequireResolved = args[1] == "on" })
181 if err != nil {
182 return c.fail(protocol.ExitFailure, "%v", err)
183 }
184 return c.emit(s, func(w io.Writer) {
185 fmt.Fprintf(w, "require_resolved %s on %s\n", args[1], repo.Path())
186 })
187}
188
189func runRequireCodeowners(c *Ctx, args []string) int {
190 if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
191 return c.fail(protocol.ExitUsage, "usage: repo settings require-codeowners <owner/name> on|off")
192 }
193 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
194 if code >= 0 {
195 return code
196 }
197 s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.RequireCodeowners = args[1] == "on" })
198 if err != nil {
199 return c.fail(protocol.ExitFailure, "%v", err)
200 }
201 return c.emit(s, func(w io.Writer) {
202 fmt.Fprintf(w, "require_codeowners %s on %s\n", args[1], repo.Path())
203 })
204}
205
206func runRequireChecks(c *Ctx, args []string) int {
207 if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
208 return c.fail(protocol.ExitUsage, "usage: repo settings require-checks <owner/name> on|off")
209 }
210 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
211 if code >= 0 {
212 return code
213 }
214 s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.RequireChecks = args[1] == "on" })
215 if err != nil {
216 return c.fail(protocol.ExitFailure, "%v", err)
217 }
218 return c.emit(s, func(w io.Writer) {
219 fmt.Fprintf(w, "require_checks %s on %s\n", args[1], repo.Path())
220 })
221}
222
223func runRequireMR(c *Ctx, args []string) int {
224 if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
225 return c.fail(protocol.ExitUsage, "usage: repo settings require-mr <owner/name> on|off")
226 }
227 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
228 if code >= 0 {
229 return code
230 }
231 s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.RequireMR = args[1] == "on" })
232 if err != nil {
233 return c.fail(protocol.ExitFailure, "%v", err)
234 }
235 return c.emit(s, func(w io.Writer) {
236 fmt.Fprintf(w, "require_mr %s on %s\n", args[1], repo.Path())
237 })
238}
239
240func runRequireSigned(c *Ctx, args []string) int {
241 if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
242 return c.fail(protocol.ExitUsage, "usage: repo settings require-signed <owner/name> on|off")
243 }
244 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
245 if code >= 0 {
246 return code
247 }
248 s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.RequireSignedCommits = args[1] == "on" })
249 if err != nil {
250 return c.fail(protocol.ExitFailure, "%v", err)
251 }
252 return c.emit(s, func(w io.Writer) {
253 fmt.Fprintf(w, "require_signed_commits %s on %s\n", args[1], repo.Path())
254 })
255}
256
257// mrRef parses "<owner/name> <n>" and loads the MR.
258func mrRef(c *Ctx, args []string, perm func(store.User, store.Repo, string) bool) (store.Repo, store.MR, int) {
259 repo, n, code := refArgs(c, args, perm, "MR")
260 if code >= 0 {
261 return repo, store.MR{}, code
262 }
263 mr, err := c.Store.MRByNumber(repo.ID, n)
264 if errors.Is(err, store.ErrNotFound) {
265 return repo, mr, c.fail(protocol.ExitNotFound, "MR !%d not found in %s", n, repo.Path())
266 }
267 if err != nil {
268 return repo, mr, c.fail(protocol.ExitFailure, "%v", err)
269 }
270 return repo, mr, -1
271}
272
273func mrHeadRef(n int64) string { return fmt.Sprintf("refs/merge-requests/%d/head", n) }
274
275func runMRCreate(c *Ctx, args []string) int {
276 f, err := parseFlags(args, flagSpec{Values: []string{"--source", "--target", "--title", "--body", "--file", "--format"},
277 Bools: []string{"--draft"}, MaxPos: 1,
278 Usage: "mr create <target owner/name> --source [owner/name:]<branch> --target <branch> --title <t> [--draft]"})
279 if err != nil {
280 return c.fail(protocol.ExitUsage, "%v", err)
281 }
282 path, source, target := f.pos(0), f.Value("--source"), f.Value("--target")
283 title, body, file, format := f.Value("--title"), f.Value("--body"), f.Value("--file"), f.Value("--format")
284 if path == "" || source == "" || title == "" {
285 return c.fail(protocol.ExitUsage, "usage: mr create <target owner/name> --source [owner/name:]<branch> --target <branch> --title <t> [--draft]")
286 }
287 fmtName, err := markupFormat(format)
288 if err != nil {
289 return c.failErr(err)
290 }
291 if fmtName == "" {
292 fmtName = "md"
293 }
294 repo, code := resolveRepo(c, path, policy.CanRead)
295 if code >= 0 {
296 return code
297 }
298 if code := refuseArchived(c, repo); code >= 0 {
299 return code
300 }
301 if target == "" {
302 target = repo.DefaultBranch
303 }
304
305 // Source is "branch" (same repo) or "owner/name:branch" (a fork).
306 srcRepo := repo
307 srcBranch := source
308 if sp, br, ok := strings.Cut(source, ":"); ok {
309 srcBranch = br
310 var scode int
311 srcRepo, scode = resolveRepo(c, sp, policy.CanRead)
312 if scode >= 0 {
313 return scode
314 }
315 if srcRepo.ForkOf != repo.ID && srcRepo.ID != repo.ID {
316 return c.fail(protocol.ExitUsage, "%s is not a fork of %s", srcRepo.Path(), repo.Path())
317 }
318 }
319 srcDir := RepoDir(c.Cfg.Server.Root, srcRepo.OwnerName, srcRepo.Name)
320 headSHA, err := gitutil.ResolveRef(srcDir, "refs/heads/"+srcBranch)
321 if err != nil {
322 return c.fail(protocol.ExitNotFound, "branch %s not found in %s", srcBranch, srcRepo.Path())
323 }
324 b, err := bodyFrom(c, body, file)
325 if err != nil {
326 return c.failErr(err)
327 }
328 n, err := c.Store.CreateMR(repo.ID, c.User.ID, srcRepo.ID, srcBranch, target, title, b, headSHA, fmtName, f.Has("--draft"))
329 if err != nil {
330 return c.fail(protocol.ExitFailure, "%v", err)
331 }
332 // Fetch the head into the target so the target owns the objects.
333 dstDir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
334 if err := gitutil.FetchInto(dstDir, srcDir, headSHA, mrHeadRef(n)); err != nil {
335 return c.fail(protocol.ExitFailure, "recording MR head: %v", err)
336 }
337 if srcRepo.ID != repo.ID {
338 QueueMRBuilds(c.Store, c.Cfg.Server.Root, c.Cfg.Server.SiteURL, repo, c.User.ID, n, headSHA)
339 }
340 c.Store.RecordEvent(repo.ID, c.User.ID, "mr.created", fmt.Sprintf(`{"number":%d}`, n))
341 if targets, err := c.Store.RepoNotifyTargets(repo); err == nil {
342 notify(c, targets, notice{repo: repo, kind: "mr",
343 subject: mrSubject(repo, n, title),
344 action: fmt.Sprintf("opened merge request !%d (%s -> %s)", n, source, target),
345 excerpt: b, path: fmt.Sprintf("%s/mrs/%d", repo.Path(), n)})
346 }
347 out := MRCreated{Number: n, HeadSHA: headSHA}
348 if p, ok, err := c.Store.OpenMRBySource(repo.ID, target); err == nil && ok {
349 out.StackedOn = &stackRef{p.Number, p.Title}
350 }
351 return c.emit(out, func(w io.Writer) {
352 fmt.Fprintf(w, "created %s!%d (%s -> %s)\n", repo.Path(), n, source, target)
353 if out.StackedOn != nil {
354 fmt.Fprintf(w, "stacked on !%d %s\n", out.StackedOn.Number, out.StackedOn.Title)
355 }
356 })
357}
358
359type mrOut struct {
360 Number int64 `json:"number"`
361 Title string `json:"title"`
362 State string `json:"state"`
363 // Draft is an open merge request not asking to be merged yet.
364 Draft bool `json:"draft,omitempty"`
365 Author string `json:"author"`
366 Source string `json:"source"` // owner/name:branch, or branch, "" if gone
367 TargetRef string `json:"target_ref"`
368 HeadSHA string `json:"head_sha"`
369 Body string `json:"body,omitempty"`
370 BodyFormat string `json:"body_format,omitempty"`
371 Milestone string `json:"milestone,omitempty"`
372 // ReviewRequests is who has been asked, directly, for a review.
373 ReviewRequests []string `json:"review_requests,omitempty"`
374 // StackedOn is the open merge request whose source branch this one
375 // targets; Stacked are the open ones targeting this one's source.
376 StackedOn *stackRef `json:"stacked_on,omitempty"`
377 Stacked []stackRef `json:"stacked,omitempty"`
378 CreatedAt string `json:"created_at"`
379 MergedAt string `json:"merged_at,omitempty"`
380 MergedBy string `json:"merged_by,omitempty"`
381 ClosedAt string `json:"closed_at,omitempty"`
382 ClosedBy string `json:"closed_by,omitempty"`
383}
384
385type stackRef struct {
386 Number int64 `json:"number"`
387 Title string `json:"title"`
388}
389
390// stackOf derives the stack around m: the open merge request whose source
391// branch m targets, and the open ones targeting m's source. Both only
392// within m's repository; a fork's branch is not a target anything can
393// stack on.
394func stackOf(c *Ctx, repo store.Repo, m store.MR) (*stackRef, []stackRef) {
395 if m.State != "open" {
396 return nil, nil
397 }
398 var parent *stackRef
399 if p, ok, err := c.Store.OpenMRBySource(repo.ID, m.TargetRef); err == nil && ok && p.ID != m.ID {
400 parent = &stackRef{p.Number, p.Title}
401 }
402 var children []stackRef
403 if m.SourceRepoID == repo.ID {
404 if kids, err := c.Store.OpenMRsByTarget(repo.ID, m.SourceRef); err == nil {
405 for _, k := range kids {
406 if k.ID != m.ID {
407 children = append(children, stackRef{k.Number, k.Title})
408 }
409 }
410 }
411 }
412 return parent, children
413}
414
415func mrToOut(repo store.Repo, m store.MR, withBody bool) mrOut {
416 src := ""
417 if m.SourcePath != "" {
418 if m.SourceRepoID == repo.ID {
419 src = m.SourceRef
420 } else {
421 src = m.SourcePath + ":" + m.SourceRef
422 }
423 }
424 o := mrOut{Number: m.Number, Title: m.Title, State: m.State, Draft: m.Draft, Author: m.Author,
425 Source: src, TargetRef: m.TargetRef, HeadSHA: m.HeadSHA, Milestone: m.Milestone,
426 ReviewRequests: m.ReviewRequests,
427 CreatedAt: m.CreatedAt, MergedAt: m.MergedAt, MergedBy: m.MergedBy,
428 ClosedAt: m.ClosedAt, ClosedBy: m.ClosedBy}
429 if withBody {
430 o.Body = m.Body
431 o.BodyFormat = m.BodyFormat
432 }
433 return o
434}
435
436func runMRList(c *Ctx, args []string) int {
437 args, p, code := parsePageFlags(c, args, "mr", true)
438 if code >= 0 {
439 return code
440 }
441 const usage = "usage: mr list <owner/name> [--state open|merged|closed|source_gone|all] [--author <user>] [--milestone <title>|none] [--search <text>] [--limit <n>] [--cursor <c>]"
442 f := store.MRFilter{State: "open"}
443 fl, err := parseFlags(args, flagSpec{Values: []string{"--state", "--author", "--milestone", "--search"}, MaxPos: 1, Usage: usage})
444 if err != nil {
445 return c.fail(protocol.ExitUsage, "%v", err)
446 }
447 path := fl.pos(0)
448 if fl.Has("--state") {
449 f.State = fl.Value("--state")
450 }
451 f.Author, f.Milestone = fl.Value("--author"), fl.Value("--milestone")
452 f.Search = fl.Value("--search")
453 if fl.Has("--search") {
454 if err := validQuery(f.Search); err != nil {
455 return c.failErr(err)
456 }
457 }
458 valid := map[string]bool{"open": true, "merged": true, "closed": true, "source_gone": true, "all": true}
459 if path == "" || !valid[f.State] {
460 return c.fail(protocol.ExitUsage, usage)
461 }
462 repo, code := resolveRepo(c, path, policy.CanRead)
463 if code >= 0 {
464 return code
465 }
466 f.Limit, f.Before = p.queryLimit(), p.keyInt()
467 mrs, err := c.Store.QueryMRs(repo.ID, f)
468 if err != nil {
469 return c.fail(protocol.ExitFailure, "%v", err)
470 }
471 mrs, next := trimPage(p, mrs, "mr", func(m store.MR) string {
472 return strconv.FormatInt(m.Number, 10)
473 })
474 var ds []mrOut
475 for _, m := range mrs {
476 o := mrToOut(repo, m, false)
477 o.StackedOn, _ = stackOf(c, repo, m)
478 ds = append(ds, o)
479 }
480 return c.emitPage(p, ds, next, func(w io.Writer) {
481 for _, d := range ds {
482 stacked := ""
483 if d.StackedOn != nil {
484 stacked = fmt.Sprintf("\tstacked on !%d", d.StackedOn.Number)
485 }
486 state := d.State
487 if d.Draft {
488 state = "draft"
489 }
490 fmt.Fprintf(w, "!%d\t%s\t%s\t%s -> %s%s\n", d.Number, state, d.Title, d.Source, d.TargetRef, stacked)
491 }
492 })
493}
494
495// byWhom renders " by <user>", or nothing when the actor is unknown — an
496// imported merge request carries a time but no local account.
497func byWhom(user string) string {
498 if user == "" {
499 return ""
500 }
501 return " by " + user
502}
503
504func runMRShow(c *Ctx, args []string) int {
505 repo, mr, code := mrRef(c, args, policy.CanRead)
506 if code >= 0 {
507 return code
508 }
509 if len(args) != 2 {
510 return c.fail(protocol.ExitUsage, "usage: mr show <owner/name> <n>")
511 }
512 comments, err := c.Store.ListMRComments(mr.ID)
513 if err != nil {
514 return c.fail(protocol.ExitFailure, "%v", err)
515 }
516 reviews, err := c.Store.ListMRReviews(mr.ID)
517 if err != nil {
518 return c.fail(protocol.ExitFailure, "%v", err)
519 }
520 statuses, combined, err := c.Store.ChecksForCommit(repo.ID, mr.HeadSHA)
521 if err != nil {
522 return c.fail(protocol.ExitFailure, "%v", err)
523 }
524 unresolved, err := c.Store.UnresolvedThreadCount(mr.ID)
525 if err != nil {
526 return c.fail(protocol.ExitFailure, "%v", err)
527 }
528 var checks []CheckOut
529 for _, st := range statuses {
530 out := CheckOut{Context: st.Context, State: st.State, URL: st.TargetURL, UpdatedAt: st.UpdatedAt}
531 if st.Duration > 0 {
532 out.Duration = st.Duration.String()
533 }
534 checks = append(checks, out)
535 }
536 var cs []commentOut
537 for _, cm := range comments {
538 cs = append(cs, commentOut{cm.Author, cm.Body, cm.BodyFormat, cm.CreatedAt})
539 }
540 var rs []ReviewOut
541 counts := ReviewersWhoCount(c.Store, repo, reviews)
542 for _, r := range reviews {
543 rs = append(rs, ReviewOut{r.Reviewer, r.Verdict, r.Stale, counts[r.Reviewer], r.CreatedAt})
544 }
545 // The commits this MR carries: base..head, the diff's range.
546 var commits []CommitOut
547 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
548 base := mr.MergedBase
549 if base == "" {
550 if b, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, mrHeadRef(mr.Number)); err == nil {
551 base = b
552 }
553 }
554 if base != "" {
555 if shas, err := gitutil.RevListRange(dir, base, mrHeadRef(mr.Number)); err == nil {
556 for _, sha := range shas {
557 subject := ""
558 if raw, err := gitutil.ReadCommit(dir, sha); err == nil {
559 if parsed, err := sig.ParseCommit(raw); err == nil {
560 subject = parsed.Subject
561 }
562 }
563 commits = append(commits, CommitOut{sha, subject})
564 }
565 }
566 }
567 d := MRShow{mrOut: mrToOut(repo, mr, true), Checks: checks, Combined: combined,
568 UnresolvedThreads: unresolved, Commits: commits, Comments: cs, Reviews: rs}
569 d.StackedOn, d.Stacked = stackOf(c, repo, mr)
570 return c.emit(d, func(w io.Writer) {
571 state := d.State
572 if d.Draft {
573 state = "draft"
574 }
575 fmt.Fprintf(w, "!%d %s [%s] by %s\n%s -> %s @ %.10s\n", d.Number, d.Title, state, d.Author, d.Source, d.TargetRef, d.HeadSHA)
576 if len(d.ReviewRequests) > 0 {
577 fmt.Fprintf(w, "reviewers: %s\n", strings.Join(d.ReviewRequests, ", "))
578 }
579 if d.StackedOn != nil {
580 fmt.Fprintf(w, "stacked on !%d %s\n", d.StackedOn.Number, d.StackedOn.Title)
581 }
582 for _, k := range d.Stacked {
583 fmt.Fprintf(w, "stacked: !%d %s\n", k.Number, k.Title)
584 }
585 if d.MergedAt != "" {
586 fmt.Fprintf(w, "merged %s%s\n", d.MergedAt, byWhom(d.MergedBy))
587 }
588 if d.ClosedAt != "" {
589 fmt.Fprintf(w, "closed %s%s\n", d.ClosedAt, byWhom(d.ClosedBy))
590 }
591 if d.Body != "" {
592 fmt.Fprintf(w, "\n%s\n", d.Body)
593 }
594 for _, cm := range commits {
595 fmt.Fprintf(w, "commit: %.10s %s\n", cm.SHA, cm.Subject)
596 }
597 for _, x := range checks {
598 dur := ""
599 if x.Duration != "" {
600 dur = " in " + x.Duration
601 }
602 fmt.Fprintf(w, "check: %s %s at %s%s\n", x.Context, x.State, x.UpdatedAt, dur)
603 }
604 if d.UnresolvedThreads > 0 {
605 fmt.Fprintf(w, "unresolved threads: %d\n", d.UnresolvedThreads)
606 }
607 for _, r := range rs {
608 stale := ""
609 if r.Stale {
610 stale = " (stale)"
611 }
612 advisory := ""
613 if !r.Counts {
614 advisory = " (advisory: no write access)"
615 }
616 fmt.Fprintf(w, "review: %s %s%s%s at %s\n", r.Reviewer, r.Verdict, stale, advisory, r.CreatedAt)
617 }
618 for _, cm := range cs {
619 fmt.Fprintf(w, "\n--- %s at %s\n%s\n", cm.Author, cm.CreatedAt, cm.Body)
620 }
621 })
622}
623
624func runMRDiff(c *Ctx, args []string) int {
625 repo, mr, code := mrRef(c, args, policy.CanRead)
626 if code >= 0 {
627 return code
628 }
629 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
630 head := mrHeadRef(mr.Number)
631 // After a merge (especially fast-forward) the live merge-base equals
632 // the head and the diff would vanish; use the recorded base instead.
633 base := mr.MergedBase
634 if base == "" {
635 b, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, head)
636 if err != nil {
637 return c.fail(protocol.ExitFailure, "%v", err)
638 }
639 base = b
640 }
641 patch, truncated, err := gitutil.Diff(dir, base, head, 4<<20)
642 if err != nil {
643 return c.fail(protocol.ExitFailure, "%v", err)
644 }
645 fmt.Fprint(c.Stdout, patch)
646 if truncated {
647 fmt.Fprintln(c.Stderr, "diff truncated at 4 MiB; fetch the branch for the rest")
648 }
649 return protocol.ExitOK
650}
651
652func runMREdit(c *Ctx, args []string) int {
653 rest, title, body, format, code := editText(c, args, "mr")
654 if code >= 0 {
655 return code
656 }
657 repo, mr, code := mrRef(c, rest, policy.CanRead)
658 if code >= 0 {
659 return code
660 }
661 if code := refuseArchived(c, repo); code >= 0 {
662 return code
663 }
664 if code := authorOrWrite(c, repo, mr.Author, "edit this merge request"); code >= 0 {
665 return code
666 }
667 if err := c.Store.UpdateMRText(mr.ID, title, body, format); err != nil {
668 return c.fail(protocol.ExitFailure, "%v", err)
669 }
670 c.Store.RecordEvent(repo.ID, c.User.ID, "mr.edited", fmt.Sprintf(`{"number":%d}`, mr.Number))
671 return c.emit(map[string]any{"number": mr.Number}, func(w io.Writer) {
672 fmt.Fprintf(w, "edited %s!%d\n", repo.Path(), mr.Number)
673 })
674}
675
676// runMRRetarget moves an open merge request onto another branch of the
677// same repository.
678func runMRRetarget(c *Ctx, args []string) int {
679 if len(args) != 3 {
680 return c.fail(protocol.ExitUsage, "usage: mr retarget <owner/name> <n> <branch>")
681 }
682 repo, mr, code := mrRef(c, args[:2], policy.CanRead)
683 if code >= 0 {
684 return code
685 }
686 if code := refuseArchived(c, repo); code >= 0 {
687 return code
688 }
689 if code := authorOrWrite(c, repo, mr.Author, "retarget this merge request"); code >= 0 {
690 return code
691 }
692 if mr.State == "merged" || mr.State == "closed" {
693 return c.fail(protocol.ExitUsage, "!%d is %s; only an open merge request can be retargeted", mr.Number, mr.State)
694 }
695 target := args[2]
696 if target == mr.TargetRef {
697 return c.fail(protocol.ExitUsage, "!%d already targets %s", mr.Number, target)
698 }
699 if mr.SourceRepoID == repo.ID && target == mr.SourceRef {
700 return c.fail(protocol.ExitUsage, "%s is the source branch of !%d", target, mr.Number)
701 }
702 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
703 if _, err := gitutil.ResolveRef(dir, "refs/heads/"+target); err != nil {
704 return c.fail(protocol.ExitNotFound, "branch %s not found in %s", target, repo.Path())
705 }
706 // The diff, the commit list and the merge gates all derive their base
707 // from the target on every read, so the only thing to check here is
708 // that a base exists at all: without one there is nothing to show and
709 // nothing to merge.
710 base, err := gitutil.MergeBase(dir, "refs/heads/"+target, mrHeadRef(mr.Number))
711 if err != nil || base == "" {
712 return c.fail(protocol.ExitUsage, "%s shares no history with the head of !%d", target, mr.Number)
713 }
714 old := mr.TargetRef
715 if err := c.Store.SetMRTarget(mr.ID, target); err != nil {
716 return c.fail(protocol.ExitFailure, "%v", err)
717 }
718 c.Store.AddMRSystemComment(mr.ID, c.User.ID, fmt.Sprintf("retargeted from %s to %s", old, target))
719 c.Store.RecordEvent(repo.ID, c.User.ID, "mr.retargeted",
720 fmt.Sprintf(`{"number":%d,"from":%q,"to":%q}`, mr.Number, old, target))
721 if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
722 notify(c, parts, notice{repo: repo, kind: "mr",
723 subject: mrSubject(repo, mr.Number, mr.Title),
724 action: fmt.Sprintf("retargeted !%d from %s to %s", mr.Number, old, target),
725 path: fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
726 }
727 return c.emit(map[string]any{"number": mr.Number, "target_ref": target, "merge_base": base}, func(w io.Writer) {
728 fmt.Fprintf(w, "retargeted %s!%d from %s to %s (base %.10s)\n", repo.Path(), mr.Number, old, target, base)
729 })
730}
731
732func runMRComment(c *Ctx, args []string) int {
733 return runComment(c, args, mrThread, "mr",
734 func(rest []string) (store.Repo, int64, int64, string, int) {
735 repo, mr, code := mrRef(c, rest, policy.CanRead)
736 return repo, mr.ID, mr.Number, mr.Title, code
737 },
738 c.Store.AddMRComment, c.Store.MRParticipants)
739}
740
741func runMRReview(c *Ctx, args []string) int {
742 verdict, discard := "", false
743 var rest []string
744 for _, a := range args {
745 switch a {
746 case "--approve":
747 verdict = "approve"
748 case "--request-changes":
749 verdict = "request_changes"
750 case "--comment":
751 verdict = "comment"
752 case "--discard":
753 discard = true
754 default:
755 rest = append(rest, a)
756 }
757 }
758 const usage = "mr review <owner/name> <n> --approve|--request-changes|--comment|--discard"
759 if discard && verdict != "" {
760 return c.fail(protocol.ExitUsage, "--discard throws the batch away; it takes no verdict")
761 }
762 if verdict == "" && !discard {
763 return c.fail(protocol.ExitUsage, "usage: %s", usage)
764 }
765 repo, mr, code := mrRef(c, rest, policy.CanRead)
766 if code >= 0 {
767 return code
768 }
769 if code := refuseArchived(c, repo); code >= 0 {
770 return code
771 }
772 if mr.State != "open" {
773 return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
774 }
775 // Throwing the batch away is not a review, so it stops here: no
776 // verdict, no event, nobody told about comments nobody ever saw.
777 if discard {
778 n, err := c.Store.DiscardPendingComments(mr.ID, c.User.ID)
779 if err != nil {
780 return c.fail(protocol.ExitFailure, "%v", err)
781 }
782 return c.emit(map[string]any{"number": mr.Number, "discarded": n}, func(w io.Writer) {
783 fmt.Fprintf(w, "discarded %d pending comment(s) on %s!%d\n", n, repo.Path(), mr.Number)
784 })
785 }
786 if err := c.Store.AddMRReview(mr.ID, c.User.ID, verdict, mr.HeadSHA); err != nil {
787 return c.fail(protocol.ExitFailure, "%v", err)
788 }
789 // The batch the reviewer composed becomes visible with the verdict,
790 // which is what makes it one review rather than a trickle.
791 published, err := c.Store.PublishPendingComments(mr.ID, c.User.ID)
792 if err != nil {
793 return c.fail(protocol.ExitFailure, "%v", err)
794 }
795 c.Store.RecordEvent(repo.ID, c.User.ID, "mr.reviewed",
796 fmt.Sprintf(`{"number":%d,"verdict":%q}`, mr.Number, verdict))
797 if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
798 notify(c, parts, notice{repo: repo, kind: "mr",
799 subject: mrSubject(repo, mr.Number, mr.Title),
800 action: reviewAction(mr.Number, verdict, published),
801 path: fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
802 }
803 return c.emit(map[string]any{"number": mr.Number, "verdict": verdict, "published": published}, func(w io.Writer) {
804 fmt.Fprintf(w, "reviewed %s!%d: %s", repo.Path(), mr.Number, verdict)
805 if published > 0 {
806 fmt.Fprintf(w, " (%d comment(s))", published)
807 }
808 fmt.Fprintln(w)
809 })
810}
811
812// runMRReviewRequest is issue assign's counterpart for merge requests: it
813// pushes a merge request into a specific person's review queue and inbox
814// directly, rather than waiting for them to be otherwise involved (#145).
815func runMRReviewRequest(c *Ctx, args []string) int {
816 rest, adds, removes, err := addRemoveFlags(args)
817 if err != nil {
818 return c.failErr(err)
819 }
820 if len(adds)+len(removes) == 0 {
821 return c.fail(protocol.ExitUsage, "usage: mr review request <owner/name> <n> [--add <user>]... [--remove <user>]...")
822 }
823 repo, mr, code := mrRef(c, rest, policy.CanWrite)
824 if code >= 0 {
825 return code
826 }
827 if code := refuseArchived(c, repo); code >= 0 {
828 return code
829 }
830 resolve := func(name string) (store.User, int) {
831 u, err := c.Store.UserByUsername(name)
832 if errors.Is(err, store.ErrNotFound) {
833 return u, c.fail(protocol.ExitNotFound, "no such user %q", name)
834 }
835 if err != nil {
836 return u, c.fail(protocol.ExitFailure, "%v", err)
837 }
838 return u, -1
839 }
840 // Notified on every return, not just success: a name later in --add
841 // that fails to resolve or lacks access must not silence the people
842 // already added earlier in the same call.
843 var added []store.User
844 defer func() {
845 if len(added) == 0 {
846 return
847 }
848 ids := make([]int64, len(added))
849 for i, u := range added {
850 ids[i] = u.ID
851 }
852 notify(c, ids, notice{repo: repo, kind: "mr",
853 subject: mrSubject(repo, mr.Number, mr.Title),
854 action: fmt.Sprintf("asked for a review on !%d", mr.Number),
855 path: fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
856 }()
857 for _, name := range adds {
858 u, code := resolve(name)
859 if code >= 0 {
860 return code
861 }
862 // A review request that lands nowhere the recipient can see it is
863 // worse than useless: it looks like the ask went through.
864 grant, err := c.Store.AccessRole(repo.ID, u.ID)
865 if err != nil {
866 return c.fail(protocol.ExitFailure, "%v", err)
867 }
868 if !policy.CanRead(u, repo, grant) {
869 return c.fail(protocol.ExitDenied, "%s cannot read %s", name, repo.Path())
870 }
871 if err := c.Store.SetMRReviewRequest(mr.ID, u.ID, true); err != nil {
872 return c.fail(protocol.ExitFailure, "%v", err)
873 }
874 added = append(added, u)
875 }
876 for _, name := range removes {
877 u, code := resolve(name)
878 if code >= 0 {
879 return code
880 }
881 if err := c.Store.SetMRReviewRequest(mr.ID, u.ID, false); err != nil {
882 if errors.Is(err, store.ErrNotFound) {
883 return c.fail(protocol.ExitNotFound, "%s is not a requested reviewer", name)
884 }
885 return c.fail(protocol.ExitFailure, "%v", err)
886 }
887 }
888 updated, err := c.Store.MRByNumber(repo.ID, mr.Number)
889 if err != nil {
890 return c.fail(protocol.ExitFailure, "%v", err)
891 }
892 c.Store.RecordEvent(repo.ID, c.User.ID, "mr.review_requested",
893 fmt.Sprintf(`{"number":%d,"reviewers":%s}`, mr.Number, jsonStrings(updated.ReviewRequests)))
894 return c.emit(map[string]any{"number": mr.Number, "reviewers": updated.ReviewRequests}, func(w io.Writer) {
895 fmt.Fprintf(w, "requested reviewers on %s!%d: %s\n", repo.Path(), mr.Number, strings.Join(updated.ReviewRequests, ", "))
896 })
897}
898
899func runMRMerge(c *Ctx, args []string) int {
900 f, err := parseFlags(args, flagSpec{Values: []string{"--strategy"}, MaxPos: -1, Usage: "mr merge <owner/name> <n> [--strategy ff|merge|squash|rebase]"})
901 if err != nil {
902 return c.fail(protocol.ExitUsage, "%v", err)
903 }
904 strategy, rest := f.Value("--strategy"), f.Pos
905 valid := map[string]bool{"": true, "ff": true, "merge": true, "squash": true, "rebase": true}
906 if !valid[strategy] {
907 return c.fail(protocol.ExitUsage, "--strategy must be ff, merge, squash, or rebase")
908 }
909 repo, mr, code := mrRef(c, rest, policy.CanWrite)
910 if code >= 0 {
911 return code
912 }
913 if code := refuseArchived(c, repo); code >= 0 {
914 return code
915 }
916 if mr.State != "open" && mr.State != "source_gone" {
917 return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
918 }
919
920 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
921 targetRef := "refs/heads/" + mr.TargetRef
922 targetSHA, err := gitutil.ResolveRef(dir, targetRef)
923 if err != nil {
924 return c.fail(protocol.ExitFailure, "target branch %s: %v", mr.TargetRef, err)
925 }
926 headSHA, err := gitutil.ResolveRef(dir, mrHeadRef(mr.Number))
927 if err != nil {
928 return c.fail(protocol.ExitFailure, "MR head ref: %v", err)
929 }
930
931 // Check gate: with require_checks, the MR head must carry statuses
932 // and every one of them must be green.
933 if repo.Settings.RequireChecks {
934 statuses, err := c.Store.ListCommitStatuses(repo.ID, headSHA)
935 if err != nil {
936 return c.fail(protocol.ExitFailure, "%v", err)
937 }
938 switch store.CombinedStatus(statuses) {
939 case "success":
940 case "":
941 return c.fail(protocol.ExitDenied,
942 "%s requires green checks and none were reported on %.10s", repo.Path(), headSHA)
943 default:
944 var bad []string
945 for _, st := range statuses {
946 if st.State != "success" {
947 bad = append(bad, st.Context+"="+st.State)
948 }
949 }
950 return c.fail(protocol.ExitDenied,
951 "%s requires green checks; %.10s has %s", repo.Path(), headSHA, strings.Join(bad, ", "))
952 }
953 }
954
955 // Review gates: approvals, CODEOWNERS, resolved threads.
956 if code := c.reviewGates(repo, mr, dir, targetSHA, headSHA); code >= 0 {
957 return code
958 }
959
960 upToDate, err := gitutil.IsAncestor(dir, headSHA, targetSHA)
961 if err != nil {
962 return c.fail(protocol.ExitFailure, "%v", err)
963 }
964 if upToDate {
965 // The head is already on the target: merged by hand and pushed, or
966 // a merge whose ref update landed and whose record did not. Record
967 // it rather than refuse, so a merge request cannot be stuck open
968 // with no way to close it as merged (#108).
969 if err := c.Store.MarkMerged(mr.ID, targetSHA, c.User.ID, ""); err != nil {
970 return c.fail(protocol.ExitFailure, "%v", err)
971 }
972 c.Store.RecordEvent(repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d}`, mr.Number))
973 return c.emit(map[string]any{"number": mr.Number, "strategy": "recorded", "sha": headSHA}, func(w io.Writer) {
974 fmt.Fprintf(w, "%s already contains !%d; recorded as merged at %.10s\n", mr.TargetRef, mr.Number, headSHA)
975 })
976 }
977 ffPossible, err := gitutil.IsAncestor(dir, targetSHA, headSHA)
978 if err != nil {
979 return c.fail(protocol.ExitFailure, "%v", err)
980 }
981
982 // Signature policy matrix: with require_signed_commits, only
983 // fast-forward is allowed — squash, rebase-replay, and merge commits
984 // are all server-created and unsigned, violating the branch's own
985 // policy — and every landed commit must be verified. An explicit
986 // rebase when fast-forward is already possible IS a fast-forward
987 // (nothing is rewritten), so it stays legal.
988 if repo.Settings.RequireSignedCommits {
989 if strategy == "merge" || strategy == "squash" || !ffPossible {
990 return c.fail(protocol.ExitDenied,
991 "%s requires signed commits, so only fast-forward merges are allowed; rebase %s onto %s locally, re-push, and merge again",
992 repo.Path(), mr.SourceRef, mr.TargetRef)
993 }
994 strategy = "ff"
995 commits, err := gitutil.RevListRange(dir, targetSHA, headSHA)
996 if err != nil {
997 return c.fail(protocol.ExitFailure, "%v", err)
998 }
999 for _, sha := range commits {
1000 raw, err := gitutil.ReadCommit(dir, sha)
1001 if err != nil {
1002 return c.fail(protocol.ExitFailure, "%v", err)
1003 }
1004 parsed, err := sigParse(raw)
1005 if err != nil {
1006 return c.fail(protocol.ExitFailure, "%v", err)
1007 }
1008 res, err := VerifyCommitCached(c.Store, repo, parsed, sha)
1009 if err != nil {
1010 return c.fail(protocol.ExitFailure, "%v", err)
1011 }
1012 if res.State != "verified" {
1013 return c.fail(protocol.ExitDenied,
1014 "%s requires signed commits: %.10s is %s", repo.Path(), sha, res.State)
1015 }
1016 }
1017 }
1018 if strategy == "" {
1019 if ffPossible {
1020 strategy = "ff"
1021 } else {
1022 strategy = "merge"
1023 }
1024 }
1025 if strategy == "rebase" && ffPossible {
1026 // Nothing to rewrite: a rebase onto an ancestor is a fast-forward,
1027 // and taking it keeps the original commits and their signatures.
1028 strategy = "ff"
1029 }
1030
1031 // Every server-created commit needs the merger's verified identity.
1032 mergerEmail := ""
1033 if strategy != "ff" {
1034 email, err := c.Store.PrimaryVerifiedEmail(c.User.ID)
1035 if err != nil {
1036 return c.fail(protocol.ExitFailure, "%v", err)
1037 }
1038 if email == "" {
1039 return c.fail(protocol.ExitDenied,
1040 "%s merges create commits carrying your identity: verify a primary email first (or use a fast-forward merge)", strategy)
1041 }
1042 mergerEmail = email
1043 }
1044
1045 var newSHA string
1046 switch strategy {
1047 case "ff":
1048 if !ffPossible {
1049 return c.fail(protocol.ExitUsage,
1050 "fast-forward not possible: %s has diverged from the MR head; use --strategy merge or rebase and re-push", mr.TargetRef)
1051 }
1052 newSHA = headSHA
1053
1054 case "merge":
1055 tree, conflict, err := gitutil.MergeTree(dir, targetSHA, headSHA)
1056 if err != nil {
1057 return c.fail(protocol.ExitFailure, "%v", err)
1058 }
1059 if conflict {
1060 return c.fail(protocol.ExitUsage,
1061 "merge conflicts between %s and the MR head; resolve locally and re-push", mr.TargetRef)
1062 }
1063 msg := fmt.Sprintf("Merge request !%d: %s\n\nMerged %s into %s", mr.Number, mr.Title, mr.SourceRef, mr.TargetRef)
1064 newSHA, err = gitutil.CommitTree(dir, tree, []string{targetSHA, headSHA}, c.User.Username, mergerEmail, msg)
1065 if err != nil {
1066 return c.fail(protocol.ExitFailure, "%v", err)
1067 }
1068
1069 case "squash":
1070 // One new commit with the merged tree. Authorship credit goes to
1071 // the MR author (their verified identity when they have one); the
1072 // committer is the merger.
1073 tree := ""
1074 if ffPossible {
1075 t, err := gitutil.ResolveTree(dir, headSHA)
1076 if err != nil {
1077 return c.fail(protocol.ExitFailure, "%v", err)
1078 }
1079 tree = t
1080 } else {
1081 t, conflict, err := gitutil.MergeTree(dir, targetSHA, headSHA)
1082 if err != nil {
1083 return c.fail(protocol.ExitFailure, "%v", err)
1084 }
1085 if conflict {
1086 return c.fail(protocol.ExitUsage,
1087 "merge conflicts between %s and the MR head; resolve locally and re-push", mr.TargetRef)
1088 }
1089 tree = t
1090 }
1091 authorName, authorEmail := c.User.Username, mergerEmail
1092 if author, err := c.Store.UserByUsername(mr.Author); err == nil {
1093 if ae, err := c.Store.PrimaryVerifiedEmail(author.ID); err == nil && ae != "" {
1094 authorName, authorEmail = author.Username, ae
1095 }
1096 }
1097 msg := fmt.Sprintf("%s (!%d)", mr.Title, mr.Number)
1098 if mr.Body != "" {
1099 msg += "\n\n" + mr.Body
1100 }
1101 var err error
1102 newSHA, err = gitutil.CommitTreeIdent(dir, tree, []string{targetSHA},
1103 authorName, authorEmail, "", c.User.Username, mergerEmail, msg)
1104 if err != nil {
1105 return c.fail(protocol.ExitFailure, "%v", err)
1106 }
1107
1108 case "rebase":
1109 commits, err := gitutil.RevListRange(dir, targetSHA, headSHA)
1110 if err != nil {
1111 return c.fail(protocol.ExitFailure, "%v", err)
1112 }
1113 // Oldest first.
1114 for i, j := 0, len(commits)-1; i < j; i, j = i+1, j-1 {
1115 commits[i], commits[j] = commits[j], commits[i]
1116 }
1117 onto := targetSHA
1118 for _, sha := range commits {
1119 parents, err := gitutil.CommitParents(dir, sha)
1120 if err != nil {
1121 return c.fail(protocol.ExitFailure, "%v", err)
1122 }
1123 if len(parents) > 1 {
1124 return c.fail(protocol.ExitUsage,
1125 "the MR contains merge commit %.10s; a rebase merge needs linear history — use --strategy merge or squash", sha)
1126 }
1127 base := onto // root commit: replay against the new tip itself
1128 if len(parents) == 1 {
1129 base = parents[0]
1130 }
1131 tree, conflict, err := gitutil.MergeTreeOnto(dir, base, onto, sha)
1132 if err != nil {
1133 return c.fail(protocol.ExitFailure, "%v", err)
1134 }
1135 if conflict {
1136 return c.fail(protocol.ExitUsage,
1137 "commit %.10s does not apply cleanly onto %s; rebase locally and re-push", sha, mr.TargetRef)
1138 }
1139 aName, aEmail, aDate, err := gitutil.AuthorIdent(dir, sha)
1140 if err != nil {
1141 return c.fail(protocol.ExitFailure, "%v", err)
1142 }
1143 msg, err := gitutil.CommitMessage(dir, sha)
1144 if err != nil {
1145 return c.fail(protocol.ExitFailure, "%v", err)
1146 }
1147 onto, err = gitutil.CommitTreeIdent(dir, tree, []string{onto},
1148 aName, aEmail, aDate, c.User.Username, mergerEmail, msg)
1149 if err != nil {
1150 return c.fail(protocol.ExitFailure, "%v", err)
1151 }
1152 }
1153 newSHA = onto
1154 }
1155
1156 // A stacked merge request's diff is against this branch. After a
1157 // fast-forward or merge commit the same commits are on the target and
1158 // its diff is unchanged there; after a squash or rebase they are not,
1159 // and the stack would carry this merge request's changes a second
1160 // time. Refuse rather than leave the stack wrong.
1161 var stack []store.MR
1162 if mr.SourceRepoID == repo.ID {
1163 stack, _ = c.Store.OpenMRsByTarget(repo.ID, mr.SourceRef)
1164 }
1165 if len(stack) > 0 && (strategy == "squash" || strategy == "rebase") {
1166 var nums []string
1167 for _, k := range stack {
1168 nums = append(nums, fmt.Sprintf("!%d", k.Number))
1169 }
1170 return c.fail(protocol.ExitUsage,
1171 "%s is stacked on by %s; a %s merge rewrites the commits they build on. Merge with --strategy ff or merge, or merge the stack into %s first",
1172 fmt.Sprintf("!%d", mr.Number), strings.Join(nums, ", "), strategy, mr.SourceRef)
1173 }
1174
1175 // CAS so a concurrent push between our read and this write fails the
1176 // merge instead of silently discarding the push.
1177 if err := gitutil.UpdateRefCAS(dir, targetRef, newSHA, targetSHA); err != nil {
1178 return c.fail(protocol.ExitFailure, "target branch moved during merge; retry: %v", err)
1179 }
1180 if err := c.Store.MarkMerged(mr.ID, targetSHA, c.User.ID, ""); err != nil {
1181 return c.fail(protocol.ExitFailure, "%v", err)
1182 }
1183 c.Store.RecordEvent(repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d,"sha":%q}`, mr.Number, newSHA))
1184 // The stack moves up: whatever targeted this branch now targets what
1185 // it merged into, reviews intact, since that diff is the one they
1186 // were of.
1187 for _, k := range stack {
1188 if err := c.Store.RetargetKeepingReviews(k.ID, mr.TargetRef); err != nil {
1189 continue
1190 }
1191 c.Store.AddMRSystemComment(k.ID, c.User.ID, fmt.Sprintf("retargeted from %s to %s: !%d merged", mr.SourceRef, mr.TargetRef, mr.Number))
1192 if parts, err := c.Store.MRParticipants(k.ID); err == nil {
1193 notify(c, parts, notice{repo: repo, kind: "mr",
1194 subject: mrSubject(repo, k.Number, k.Title),
1195 action: fmt.Sprintf("retargeted !%d from %s to %s: !%d merged", k.Number, mr.SourceRef, mr.TargetRef, mr.Number),
1196 path: fmt.Sprintf("%s/mrs/%d", repo.Path(), k.Number)})
1197 }
1198 }
1199 // Merges bypass receive-pack, so the commit-message issue actions
1200 // (closes #N, references) run here for the newly landed commits. The
1201 // description is scanned after them, so a commit wins the attribution
1202 // when both name the same issue.
1203 if mr.TargetRef == repo.DefaultBranch {
1204 ProcessCommitMessages(c.Store, dir, repo, c.User.ID, targetSHA, newSHA)
1205 ProcessMRDescription(c.Store, repo, mr, c.User.ID)
1206 RecordLandedCommits(c.Store, dir, repo, targetSHA, newSHA)
1207 }
1208 // A merge moves the ref directly, so it never reaches post-receive and
1209 // none of the ref-update work fires on its own. The event webhooks
1210 // subscribe to, and the branch's CI jobs, happen here instead.
1211 c.Store.RecordEvent(repo.ID, c.User.ID, "push", fmt.Sprintf(
1212 `{"ref":%q,"old":%q,"new":%q,"forced":false,"deleted":false}`,
1213 targetRef, targetSHA, newSHA))
1214 QueueBranchBuilds(c.Store, c.Cfg.Server.Root, c.Cfg.Server.SiteURL,
1215 repo, c.User.ID, mr.TargetRef, targetSHA, newSHA, time.Now())
1216 c.Store.MarkMirrorsDirty(repo.ID, "push")
1217 if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
1218 notify(c, parts, notice{repo: repo, kind: "mr",
1219 subject: mrSubject(repo, mr.Number, mr.Title),
1220 action: fmt.Sprintf("merged !%d into %s (%s)", mr.Number, mr.TargetRef, strategy),
1221 path: fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
1222 }
1223 return c.emit(map[string]any{"number": mr.Number, "strategy": strategy, "sha": newSHA}, func(w io.Writer) {
1224 fmt.Fprintf(w, "merged %s!%d into %s (%s) at %.10s\n", repo.Path(), mr.Number, mr.TargetRef, strategy, newSHA)
1225 })
1226}
1227
1228// reviewGates enforces require_approvals (fresh, non-author, latest review
1229// per reviewer; a fresh request-changes blocks), require_codeowners, and
1230// require_resolved. Returns -1 to proceed.
1231func (c *Ctx) reviewGates(repo store.Repo, mr store.MR, dir, targetSHA, headSHA string) int {
1232 // A draft is open but not asking. This gate is unconditional — no
1233 // setting turns it off — because the author said so themselves.
1234 if mr.Draft {
1235 return c.fail(protocol.ExitDenied,
1236 "!%d is a draft; `gitbay mr ready %s %d` first", mr.Number, repo.Path(), mr.Number)
1237 }
1238 set := repo.Settings
1239 reviews, err := c.Store.ListMRReviews(mr.ID)
1240 if err != nil {
1241 return c.fail(protocol.ExitFailure, "%v", err)
1242 }
1243 // Latest fresh review per reviewer decides their stance — but only
1244 // from someone the repository trusts to write to it. Reviewing is
1245 // open to any reader, which is what makes an outside opinion on a
1246 // public change possible; deciding a merge gate is not the same
1247 // thing, and counting every verdict let anyone with an account
1248 // satisfy require_approvals or block a merge indefinitely (#147).
1249 counts := ReviewersWhoCount(c.Store, repo, reviews)
1250 latest := map[string]string{}
1251 for _, r := range reviews {
1252 if r.Stale || r.Reviewer == mr.Author || !counts[r.Reviewer] {
1253 continue
1254 }
1255 latest[r.Reviewer] = r.Verdict
1256 }
1257 var approvers []string
1258 var blockers []string
1259 for who, verdict := range latest {
1260 switch verdict {
1261 case "approve":
1262 approvers = append(approvers, who)
1263 case "request_changes":
1264 blockers = append(blockers, who)
1265 }
1266 }
1267
1268 if set.RequireApprovals > 0 {
1269 if len(blockers) > 0 {
1270 slices.Sort(blockers)
1271 return c.fail(protocol.ExitDenied,
1272 "%s requested changes on !%d; resolve their review before merging", strings.Join(blockers, ", "), mr.Number)
1273 }
1274 if len(approvers) < set.RequireApprovals {
1275 return c.fail(protocol.ExitDenied,
1276 "%s requires %d fresh approval(s); !%d has %d", repo.Path(), set.RequireApprovals, mr.Number, len(approvers))
1277 }
1278 }
1279
1280 // CODEOWNERS: every owned changed file needs an approval from one of
1281 // its owners. require_codeowners is the opt-in — a repository can
1282 // carry the file as documentation of who to ask without it gating
1283 // merges — and it does not wait on require_approvals (#99).
1284 if set.RequireCodeowners {
1285 content, err := gitutil.ReadBlob(dir, "refs/heads/"+mr.TargetRef, "CODEOWNERS", 1<<20)
1286 if err != nil {
1287 content, err = gitutil.ReadBlob(dir, "refs/heads/"+mr.TargetRef, ".gitbay/CODEOWNERS", 1<<20)
1288 }
1289 if err != nil || len(content) == 0 {
1290 return c.fail(protocol.ExitDenied,
1291 "%s requires CODEOWNERS approval but %s carries no CODEOWNERS file",
1292 repo.Path(), mr.TargetRef)
1293 }
1294 rules := policy.ParseCodeowners(string(content))
1295 base, err := gitutil.MergeBase(dir, targetSHA, headSHA)
1296 if err != nil {
1297 return c.fail(protocol.ExitFailure, "%v", err)
1298 }
1299 files, err := gitutil.DiffFiles(dir, base, headSHA)
1300 if err != nil {
1301 return c.fail(protocol.ExitFailure, "%v", err)
1302 }
1303 approved := map[string]bool{}
1304 for _, a := range approvers {
1305 approved[a] = true
1306 }
1307 missing := map[string][]string{} // owner-set key -> example paths
1308 for _, f := range files {
1309 owners := policy.OwnersFor(rules, f)
1310 if owners == nil {
1311 continue
1312 }
1313 ok := false
1314 for _, o := range owners {
1315 if approved[o] {
1316 ok = true
1317 break
1318 }
1319 }
1320 if !ok {
1321 key := strings.Join(owners, ",")
1322 if len(missing[key]) < 3 {
1323 missing[key] = append(missing[key], f)
1324 }
1325 }
1326 }
1327 if len(missing) > 0 {
1328 var parts []string
1329 for owners, paths := range missing {
1330 parts = append(parts, fmt.Sprintf("%s (owned by %s)", strings.Join(paths, ", "), owners))
1331 }
1332 slices.Sort(parts)
1333 return c.fail(protocol.ExitDenied,
1334 "CODEOWNERS approval missing for: %s", strings.Join(parts, "; "))
1335 }
1336 }
1337
1338 if set.RequireResolved {
1339 n, err := c.Store.UnresolvedThreadCount(mr.ID)
1340 if err != nil {
1341 return c.fail(protocol.ExitFailure, "%v", err)
1342 }
1343 if n > 0 {
1344 return c.fail(protocol.ExitDenied,
1345 "%s requires review threads resolved; !%d has %d open (mr threads %s %d)", repo.Path(), mr.Number, n, repo.Path(), mr.Number)
1346 }
1347 }
1348 return -1
1349}
1350
1351func runMRDraft(c *Ctx, args []string) int { return setMRDraft(c, args, true) }
1352func runMRReady(c *Ctx, args []string) int { return setMRDraft(c, args, false) }
1353
1354func setMRDraft(c *Ctx, args []string, draft bool) int {
1355 verb := "ready"
1356 if draft {
1357 verb = "draft"
1358 }
1359 repo, mr, code := mrRef(c, args, policy.CanRead)
1360 if code >= 0 {
1361 return code
1362 }
1363 if code := refuseArchived(c, repo); code >= 0 {
1364 return code
1365 }
1366 if len(args) != 2 {
1367 return c.fail(protocol.ExitUsage, "usage: mr %s <owner/name> <n>", verb)
1368 }
1369 if code := authorOrWrite(c, repo, mr.Author, "change this merge request"); code >= 0 {
1370 return code
1371 }
1372 if mr.State != "open" && mr.State != "source_gone" {
1373 return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
1374 }
1375 if mr.Draft == draft {
1376 state := "already ready"
1377 if draft {
1378 state = "already a draft"
1379 }
1380 return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, state)
1381 }
1382 if err := c.Store.SetMRDraft(mr.ID, draft); err != nil {
1383 return c.fail(protocol.ExitFailure, "%v", err)
1384 }
1385 c.Store.RecordEvent(repo.ID, c.User.ID, "mr.draft",
1386 fmt.Sprintf(`{"number":%d,"draft":%t}`, mr.Number, draft))
1387 // Marking ready is the request for review; going back to draft
1388 // withdraws it and is not worth anyone's inbox.
1389 //
1390 // The targets are the repository's, not the thread's participants.
1391 // Until someone comments or reviews, the only participant is the
1392 // author, who is the actor and excluded — so notifying participants
1393 // here reaches nobody, which is exactly what opening it as a draft
1394 // and then marking it ready would do. Opening a merge request tells
1395 // the repository; so does saying it is finally asking. A review
1396 // request made before ready — or on an earlier revision — reaches its
1397 // target here too: they are exactly who else is being asked.
1398 if !draft {
1399 if targets, err := c.Store.RepoNotifyTargets(repo); err == nil {
1400 parts, _ := c.Store.MRParticipants(mr.ID)
1401 reviewers, _ := c.Store.MRReviewRequestIDs(mr.ID)
1402 notify(c, append(append(targets, parts...), reviewers...), notice{repo: repo, kind: "mr",
1403 subject: mrSubject(repo, mr.Number, mr.Title),
1404 action: fmt.Sprintf("marked !%d ready for review", mr.Number),
1405 path: fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
1406 }
1407 }
1408 return c.emit(map[string]any{"number": mr.Number, "draft": draft}, func(w io.Writer) {
1409 fmt.Fprintf(w, "%s!%d is %s\n", repo.Path(), mr.Number, map[bool]string{true: "a draft", false: "ready"}[draft])
1410 })
1411}
1412
1413func runMRClose(c *Ctx, args []string) int {
1414 repo, mr, code := mrRef(c, args, policy.CanRead)
1415 if code >= 0 {
1416 return code
1417 }
1418 if code := refuseArchived(c, repo); code >= 0 {
1419 return code
1420 }
1421 if len(args) != 2 {
1422 return c.fail(protocol.ExitUsage, "usage: mr close <owner/name> <n>")
1423 }
1424 if code := authorOrWrite(c, repo, mr.Author, "close this merge request"); code >= 0 {
1425 return code
1426 }
1427 if mr.State == "merged" || mr.State == "closed" {
1428 return c.fail(protocol.ExitUsage, "MR !%d is already %s", mr.Number, mr.State)
1429 }
1430 if err := c.Store.MarkClosed(mr.ID, c.User.ID, ""); err != nil {
1431 return c.fail(protocol.ExitFailure, "%v", err)
1432 }
1433 c.Store.RecordEvent(repo.ID, c.User.ID, "mr.closed", fmt.Sprintf(`{"number":%d}`, mr.Number))
1434 if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
1435 notify(c, parts, notice{repo: repo, kind: "mr",
1436 subject: mrSubject(repo, mr.Number, mr.Title),
1437 action: fmt.Sprintf("closed !%d", mr.Number),
1438 path: fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
1439 }
1440 return c.emit(map[string]any{"number": mr.Number, "state": "closed"}, func(w io.Writer) {
1441 fmt.Fprintf(w, "closed %s!%d\n", repo.Path(), mr.Number)
1442 })
1443}
1444
1445// reviewAction is what a review notification says it was. A verdict with
1446// a batch behind it is a different thing from a bare verdict, and the
1447// person reading the mail is deciding whether to open it.
1448func reviewAction(number int64, verdict string, published int64) string {
1449 if published > 0 {
1450 return fmt.Sprintf("reviewed !%d: %s, with %d comment(s)", number, verdict, published)
1451 }
1452 return fmt.Sprintf("reviewed !%d: %s", number, verdict)
1453}
1454
1455// RevisionOut is one head a merge request has had.
1456type RevisionOut struct {
1457 N int `json:"n"` // 1 is the first push
1458 SHA string `json:"sha"`
1459 BaseSHA string `json:"base_sha,omitempty"`
1460 CreatedAt string `json:"created_at"`
1461 Current bool `json:"current,omitempty"`
1462}
1463
1464func mrRevisions(c *Ctx, mr store.MR) ([]RevisionOut, error) {
1465 heads, err := c.Store.MRHeads(mr.ID)
1466 if err != nil {
1467 return nil, err
1468 }
1469 out := make([]RevisionOut, 0, len(heads))
1470 for i, h := range heads {
1471 out = append(out, RevisionOut{N: i + 1, SHA: h.SHA, BaseSHA: h.BaseSHA,
1472 CreatedAt: h.CreatedAt, Current: h.SHA == mr.HeadSHA})
1473 }
1474 return out, nil
1475}
1476
1477func runMRRevisions(c *Ctx, args []string) int {
1478 repo, mr, code := mrRef(c, args, policy.CanRead)
1479 if code >= 0 {
1480 return code
1481 }
1482 if len(args) != 2 {
1483 return c.fail(protocol.ExitUsage, "usage: mr revisions <owner/name> <n>")
1484 }
1485 revs, err := mrRevisions(c, mr)
1486 if err != nil {
1487 return c.fail(protocol.ExitFailure, "%v", err)
1488 }
1489 return c.emit(revs, func(w io.Writer) {
1490 for _, r := range revs {
1491 mark := " "
1492 if r.Current {
1493 mark = "*"
1494 }
1495 fmt.Fprintf(w, "%s v%d\t%.10s\t%s\n", mark, r.N, r.SHA, r.CreatedAt)
1496 }
1497 if len(revs) < 2 {
1498 fmt.Fprintf(w, "\nonly one revision; %s!%d has not been pushed to since it was opened\n",
1499 repo.Path(), mr.Number)
1500 }
1501 })
1502}
1503
1504func runMRRangeDiff(c *Ctx, args []string) int {
1505 const usage = "mr range-diff <owner/name> <n> [--from <sha>] [--to <sha>]"
1506 f, err := parseFlags(args, flagSpec{Values: []string{"--from", "--to"}, MaxPos: 2, Usage: usage})
1507 if err != nil {
1508 return c.fail(protocol.ExitUsage, "%v", err)
1509 }
1510 repo, mr, code := mrRef(c, f.Pos, policy.CanRead)
1511 if code >= 0 {
1512 return code
1513 }
1514 if len(f.Pos) != 2 {
1515 return c.fail(protocol.ExitUsage, "usage: %s", usage)
1516 }
1517 revs, err := mrRevisions(c, mr)
1518 if err != nil {
1519 return c.fail(protocol.ExitFailure, "%v", err)
1520 }
1521 // One revision is a merge request nobody has pushed to since it was
1522 // opened. The argv was fine and the answer is "nothing changed", so
1523 // this succeeds with an empty patch rather than failing.
1524 if len(revs) < 2 {
1525 fmt.Fprintf(c.Stderr, "%s!%d has one revision; nothing to compare it against\n",
1526 repo.Path(), mr.Number)
1527 return protocol.ExitOK
1528 }
1529 // Default to the two most recent, which is "what changed since the
1530 // last push" — the question a stale review asks.
1531 from, to := revs[len(revs)-2], revs[len(revs)-1]
1532 pick := func(sha string) (RevisionOut, bool) {
1533 for _, r := range revs {
1534 if strings.HasPrefix(r.SHA, sha) {
1535 return r, true
1536 }
1537 }
1538 return RevisionOut{}, false
1539 }
1540 if v := f.Value("--from"); v != "" {
1541 r, ok := pick(v)
1542 if !ok {
1543 return c.fail(protocol.ExitNotFound, "%.12s is not a revision of !%d; see `mr revisions`", v, mr.Number)
1544 }
1545 from = r
1546 }
1547 if v := f.Value("--to"); v != "" {
1548 r, ok := pick(v)
1549 if !ok {
1550 return c.fail(protocol.ExitNotFound, "%.12s is not a revision of !%d; see `mr revisions`", v, mr.Number)
1551 }
1552 to = r
1553 }
1554 if from.SHA == to.SHA {
1555 return c.fail(protocol.ExitUsage, "--from and --to are the same revision")
1556 }
1557
1558 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
1559 // A revision recorded before its base could be worked out, or by a
1560 // migration backfill, falls back to the target's merge base.
1561 baseOf := func(r RevisionOut) string {
1562 if r.BaseSHA != "" {
1563 return r.BaseSHA
1564 }
1565 b, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, r.SHA)
1566 if err != nil {
1567 return r.SHA + "^"
1568 }
1569 return b
1570 }
1571 patch, truncated, err := gitutil.RangeDiff(dir, baseOf(from), from.SHA, baseOf(to), to.SHA, 4<<20)
1572 if err != nil {
1573 return c.fail(protocol.ExitFailure,
1574 "%v (the objects for an older revision may have been garbage-collected)", err)
1575 }
1576 fmt.Fprint(c.Stdout, patch)
1577 if truncated {
1578 fmt.Fprintln(c.Stderr, "range-diff truncated at 4 MiB")
1579 }
1580 return protocol.ExitOK
1581}
1582
1583// reviewersWhoCount is the set of reviewers whose verdict decides a merge
1584// gate: those with write access to the repository.
1585//
1586// Write, rather than a separate reviewer role, because it is the same
1587// question the gates already answer — a person who could push this change
1588// themselves is the person whose approval means the repository accepts
1589// it. Someone named in CODEOWNERS without write is a misconfiguration the
1590// owner should fix rather than a case to special-case here: they could
1591// not merge what they approved.
1592// Exported because the web renders the same distinction: a page that
1593// showed an approval the gate ignores would differ from the gate, and the
1594// difference would only surface when a merge was refused.
1595func ReviewersWhoCount(st *store.Store, repo store.Repo, reviews []store.MRReview) map[string]bool {
1596 counts := map[string]bool{}
1597 for _, r := range reviews {
1598 if _, done := counts[r.Reviewer]; done {
1599 continue
1600 }
1601 counts[r.Reviewer] = false
1602 u, err := st.UserByUsername(r.Reviewer)
1603 if err != nil {
1604 continue
1605 }
1606 grant, err := st.AccessRole(repo.ID, u.ID)
1607 if err != nil {
1608 continue
1609 }
1610 counts[r.Reviewer] = policy.CanWrite(u, repo, grant)
1611 }
1612 return counts
1613}