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