internal/control/mr.go
1665 lines · 61268 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.failInput(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.failInput(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.failInput(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 if created, err := c.Store.MRByNumber(repo.ID, n); err == nil {
348 notifyMentions(c, repo, mrThread, created.ID, n, title, b)
349 }
350 out := MRCreated{Number: n, HeadSHA: headSHA}
351 if p, ok, err := c.Store.OpenMRBySource(repo.ID, target); err == nil && ok {
352 out.StackedOn = &stackRef{p.Number, p.Title}
353 }
354 return c.emit(out, func(w io.Writer) {
355 fmt.Fprintf(w, "created %s!%d (%s -> %s)\n", repo.Path(), n, source, target)
356 if out.StackedOn != nil {
357 fmt.Fprintf(w, "stacked on !%d %s\n", out.StackedOn.Number, out.StackedOn.Title)
358 }
359 })
360}
361
362type mrOut struct {
363 Number int64 `json:"number"`
364 Title string `json:"title"`
365 State string `json:"state"`
366 // Draft is an open merge request not asking to be merged yet.
367 Draft bool `json:"draft,omitempty"`
368 Author string `json:"author"`
369 Source string `json:"source"` // owner/name:branch, or branch, "" if gone
370 TargetRef string `json:"target_ref"`
371 HeadSHA string `json:"head_sha"`
372 Body string `json:"body,omitempty"`
373 BodyFormat string `json:"body_format,omitempty"`
374 Milestone string `json:"milestone,omitempty"`
375 // ReviewRequests is who has been asked, directly, for a review.
376 ReviewRequests []string `json:"review_requests,omitempty"`
377 // StackedOn is the open merge request whose source branch this one
378 // targets; Stacked are the open ones targeting this one's source.
379 StackedOn *stackRef `json:"stacked_on,omitempty"`
380 Stacked []stackRef `json:"stacked,omitempty"`
381 CreatedAt string `json:"created_at"`
382 MergedAt string `json:"merged_at,omitempty"`
383 MergedBy string `json:"merged_by,omitempty"`
384 ClosedAt string `json:"closed_at,omitempty"`
385 ClosedBy string `json:"closed_by,omitempty"`
386}
387
388type stackRef struct {
389 Number int64 `json:"number"`
390 Title string `json:"title"`
391}
392
393// stackOf derives the stack around m: the open merge request whose source
394// branch m targets, and the open ones targeting m's source. Both only
395// within m's repository; a fork's branch is not a target anything can
396// stack on.
397func stackOf(c *Ctx, repo store.Repo, m store.MR) (*stackRef, []stackRef) {
398 if m.State != "open" {
399 return nil, nil
400 }
401 var parent *stackRef
402 if p, ok, err := c.Store.OpenMRBySource(repo.ID, m.TargetRef); err == nil && ok && p.ID != m.ID {
403 parent = &stackRef{p.Number, p.Title}
404 }
405 var children []stackRef
406 if m.SourceRepoID == repo.ID {
407 if kids, err := c.Store.OpenMRsByTarget(repo.ID, m.SourceRef); err == nil {
408 for _, k := range kids {
409 if k.ID != m.ID {
410 children = append(children, stackRef{k.Number, k.Title})
411 }
412 }
413 }
414 }
415 return parent, children
416}
417
418func mrToOut(repo store.Repo, m store.MR, withBody bool) mrOut {
419 src := ""
420 if m.SourcePath != "" {
421 if m.SourceRepoID == repo.ID {
422 src = m.SourceRef
423 } else {
424 src = m.SourcePath + ":" + m.SourceRef
425 }
426 }
427 o := mrOut{Number: m.Number, Title: m.Title, State: m.State, Draft: m.Draft, Author: m.Author,
428 Source: src, TargetRef: m.TargetRef, HeadSHA: m.HeadSHA, Milestone: m.Milestone,
429 ReviewRequests: m.ReviewRequests,
430 CreatedAt: m.CreatedAt, MergedAt: m.MergedAt, MergedBy: m.MergedBy,
431 ClosedAt: m.ClosedAt, ClosedBy: m.ClosedBy}
432 if withBody {
433 o.Body = m.Body
434 o.BodyFormat = m.BodyFormat
435 }
436 return o
437}
438
439func runMRList(c *Ctx, args []string) int {
440 args, p, code := parsePageFlags(c, args, "mr", true)
441 if code >= 0 {
442 return code
443 }
444 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>]"
445 f := store.MRFilter{State: "open"}
446 fl, err := parseFlags(args, flagSpec{Values: []string{"--state", "--author", "--milestone", "--search"}, MaxPos: 1, Usage: 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.fail(protocol.ExitUsage, 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.fail(protocol.ExitUsage, "usage: mr show <owner/name> <n>")
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.fail(protocol.ExitUsage, "usage: mr retarget <owner/name> <n> <branch>")
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 const usage = "mr review <owner/name> <n> --approve|--request-changes|--comment|--discard"
783 if discard && verdict != "" {
784 return c.fail(protocol.ExitUsage, "--discard throws the batch away; it takes no verdict")
785 }
786 if verdict == "" && !discard {
787 return c.fail(protocol.ExitUsage, "usage: %s", usage)
788 }
789 repo, mr, code := mrRef(c, rest, policy.CanRead)
790 if code >= 0 {
791 return code
792 }
793 if code := refuseArchived(c, repo); code >= 0 {
794 return code
795 }
796 if mr.State != "open" {
797 return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
798 }
799 // Throwing the batch away is not a review, so it stops here: no
800 // verdict, no event, nobody told about comments nobody ever saw.
801 if discard {
802 n, err := c.Store.DiscardPendingComments(mr.ID, c.User.ID)
803 if err != nil {
804 return c.fail(protocol.ExitFailure, "%v", err)
805 }
806 return c.emit(map[string]any{"number": mr.Number, "discarded": n}, func(w io.Writer) {
807 fmt.Fprintf(w, "discarded %d pending comment(s) on %s!%d\n", n, repo.Path(), mr.Number)
808 })
809 }
810 if err := c.Store.AddMRReview(mr.ID, c.User.ID, verdict, mr.HeadSHA); err != nil {
811 return c.fail(protocol.ExitFailure, "%v", err)
812 }
813 // The batch the reviewer composed becomes visible with the verdict,
814 // which is what makes it one review rather than a trickle.
815 published, err := c.Store.PublishPendingComments(mr.ID, c.User.ID)
816 if err != nil {
817 return c.fail(protocol.ExitFailure, "%v", err)
818 }
819 c.Store.RecordEvent(repo.ID, c.User.ID, "mr.reviewed",
820 fmt.Sprintf(`{"number":%d,"verdict":%q}`, mr.Number, verdict))
821 if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
822 notify(c, parts, notice{repo: repo, kind: "mr",
823 subject: mrSubject(repo, mr.Number, mr.Title),
824 action: reviewAction(mr.Number, verdict, published),
825 path: fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
826 }
827 // Whether the merge gates will count this verdict, said now rather
828 // than at the refusal (#199).
829 counts := ReviewersWhoCount(c.Store, repo, []store.MRReview{{Reviewer: c.User.Username}})[c.User.Username]
830 return c.emit(map[string]any{"number": mr.Number, "verdict": verdict, "published": published, "counts": counts}, func(w io.Writer) {
831 fmt.Fprintf(w, "reviewed %s!%d: %s", repo.Path(), mr.Number, verdict)
832 if published > 0 {
833 fmt.Fprintf(w, " (%d comment(s))", published)
834 }
835 if !counts {
836 fmt.Fprintf(w, " (advisory: no write access on %s, so the merge gates do not count it)", repo.Path())
837 }
838 fmt.Fprintln(w)
839 })
840}
841
842// runMRReviewRequest is issue assign's counterpart for merge requests: it
843// pushes a merge request into a specific person's review queue and inbox
844// directly, rather than waiting for them to be otherwise involved (#145).
845func runMRReviewRequest(c *Ctx, args []string) int {
846 rest, adds, removes, err := addRemoveFlags(args)
847 if err != nil {
848 return c.failInput(err)
849 }
850 if len(adds)+len(removes) == 0 {
851 return c.fail(protocol.ExitUsage, "usage: mr review request <owner/name> <n> [--add <user>]... [--remove <user>]...")
852 }
853 repo, mr, code := mrRef(c, rest, policy.CanWrite)
854 if code >= 0 {
855 return code
856 }
857 if code := refuseArchived(c, repo); code >= 0 {
858 return code
859 }
860 resolve := func(name string) (store.User, int) {
861 u, err := c.Store.UserByUsername(name)
862 if errors.Is(err, store.ErrNotFound) {
863 return u, c.fail(protocol.ExitNotFound, "no such user %q", name)
864 }
865 if err != nil {
866 return u, c.fail(protocol.ExitFailure, "%v", err)
867 }
868 return u, -1
869 }
870 // Notified on every return, not just success: a name later in --add
871 // that fails to resolve or lacks access must not silence the people
872 // already added earlier in the same call.
873 var added []store.User
874 defer func() {
875 if len(added) == 0 {
876 return
877 }
878 ids := make([]int64, len(added))
879 for i, u := range added {
880 ids[i] = u.ID
881 }
882 notify(c, ids, notice{repo: repo, kind: "mr",
883 subject: mrSubject(repo, mr.Number, mr.Title),
884 action: fmt.Sprintf("asked for a review on !%d", mr.Number),
885 path: fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
886 }()
887 for _, name := range adds {
888 u, code := resolve(name)
889 if code >= 0 {
890 return code
891 }
892 // A review request that lands nowhere the recipient can see it is
893 // worse than useless: it looks like the ask went through.
894 grant, err := c.Store.AccessRole(repo.ID, u.ID)
895 if err != nil {
896 return c.fail(protocol.ExitFailure, "%v", err)
897 }
898 if !policy.CanRead(u, repo, grant) {
899 return c.fail(protocol.ExitDenied, "%s cannot read %s", name, repo.Path())
900 }
901 if err := c.Store.SetMRReviewRequest(mr.ID, u.ID, true); err != nil {
902 return c.fail(protocol.ExitFailure, "%v", err)
903 }
904 added = append(added, u)
905 }
906 for _, name := range removes {
907 u, code := resolve(name)
908 if code >= 0 {
909 return code
910 }
911 if err := c.Store.SetMRReviewRequest(mr.ID, u.ID, false); err != nil {
912 if errors.Is(err, store.ErrNotFound) {
913 return c.fail(protocol.ExitNotFound, "%s is not a requested reviewer", name)
914 }
915 return c.fail(protocol.ExitFailure, "%v", err)
916 }
917 }
918 updated, err := c.Store.MRByNumber(repo.ID, mr.Number)
919 if err != nil {
920 return c.fail(protocol.ExitFailure, "%v", err)
921 }
922 c.Store.RecordEvent(repo.ID, c.User.ID, "mr.review_requested",
923 fmt.Sprintf(`{"number":%d,"reviewers":%s}`, mr.Number, jsonStrings(updated.ReviewRequests)))
924 return c.emit(map[string]any{"number": mr.Number, "reviewers": updated.ReviewRequests}, func(w io.Writer) {
925 fmt.Fprintf(w, "requested reviewers on %s!%d: %s\n", repo.Path(), mr.Number, strings.Join(updated.ReviewRequests, ", "))
926 })
927}
928
929func runMRMerge(c *Ctx, args []string) int {
930 f, err := parseFlags(args, flagSpec{Values: []string{"--strategy"}, MaxPos: -1, Usage: "mr merge <owner/name> <n> [--strategy ff|merge|squash|rebase]"})
931 if err != nil {
932 return c.fail(protocol.ExitUsage, "%v", err)
933 }
934 strategy, rest := f.Value("--strategy"), f.Pos
935 valid := map[string]bool{"": true, "ff": true, "merge": true, "squash": true, "rebase": true}
936 if !valid[strategy] {
937 return c.fail(protocol.ExitUsage, "--strategy must be ff, merge, squash, or rebase")
938 }
939 repo, mr, code := mrRef(c, rest, policy.CanWrite)
940 if code >= 0 {
941 return code
942 }
943 if code := refuseArchived(c, repo); code >= 0 {
944 return code
945 }
946 if mr.State != "open" && mr.State != "source_gone" {
947 return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
948 }
949
950 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
951 targetRef := "refs/heads/" + mr.TargetRef
952 targetSHA, err := gitutil.ResolveRef(dir, targetRef)
953 if err != nil {
954 return c.fail(protocol.ExitFailure, "target branch %s: %v", mr.TargetRef, err)
955 }
956 headSHA, err := gitutil.ResolveRef(dir, mrHeadRef(mr.Number))
957 if err != nil {
958 return c.fail(protocol.ExitFailure, "MR head ref: %v", err)
959 }
960
961 // Merge gates: draft, checks, approvals, CODEOWNERS, resolved threads,
962 // all reported at once.
963 if code := c.reviewGates(repo, mr, dir, targetSHA, headSHA); code >= 0 {
964 return code
965 }
966
967 upToDate, err := gitutil.IsAncestor(dir, headSHA, targetSHA)
968 if err != nil {
969 return c.fail(protocol.ExitFailure, "%v", err)
970 }
971 if upToDate {
972 // The head is already on the target: merged by hand and pushed, or
973 // a merge whose ref update landed and whose record did not. Record
974 // it rather than refuse, so a merge request cannot be stuck open
975 // with no way to close it as merged (#108).
976 if err := c.Store.MarkMerged(mr.ID, targetSHA, c.User.ID, ""); err != nil {
977 return c.fail(protocol.ExitFailure, "%v", err)
978 }
979 c.Store.RecordEvent(repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d}`, mr.Number))
980 return c.emit(map[string]any{"number": mr.Number, "strategy": "recorded", "sha": headSHA}, func(w io.Writer) {
981 fmt.Fprintf(w, "%s already contains !%d; recorded as merged at %.10s\n", mr.TargetRef, mr.Number, headSHA)
982 })
983 }
984 ffPossible, err := gitutil.IsAncestor(dir, targetSHA, headSHA)
985 if err != nil {
986 return c.fail(protocol.ExitFailure, "%v", err)
987 }
988
989 // Signature policy matrix: with require_signed_commits, only
990 // fast-forward is allowed — squash, rebase-replay, and merge commits
991 // are all server-created and unsigned, violating the branch's own
992 // policy — and every landed commit must be verified. An explicit
993 // rebase when fast-forward is already possible IS a fast-forward
994 // (nothing is rewritten), so it stays legal.
995 if repo.Settings.RequireSignedCommits {
996 if strategy == "merge" || strategy == "squash" || !ffPossible {
997 return c.fail(protocol.ExitDenied,
998 "%s requires signed commits, so only fast-forward merges are allowed; rebase %s onto %s locally, re-push, and merge again",
999 repo.Path(), mr.SourceRef, mr.TargetRef)
1000 }
1001 strategy = "ff"
1002 commits, err := gitutil.RevListRange(dir, targetSHA, headSHA)
1003 if err != nil {
1004 return c.fail(protocol.ExitFailure, "%v", err)
1005 }
1006 for _, sha := range commits {
1007 raw, err := gitutil.ReadCommit(dir, sha)
1008 if err != nil {
1009 return c.fail(protocol.ExitFailure, "%v", err)
1010 }
1011 parsed, err := sigParse(raw)
1012 if err != nil {
1013 return c.fail(protocol.ExitFailure, "%v", err)
1014 }
1015 res, err := VerifyCommitCached(c.Store, repo, parsed, sha)
1016 if err != nil {
1017 return c.fail(protocol.ExitFailure, "%v", err)
1018 }
1019 if res.State != "verified" {
1020 return c.fail(protocol.ExitDenied,
1021 "%s requires signed commits: %.10s is %s", repo.Path(), sha, res.State)
1022 }
1023 }
1024 }
1025 if strategy == "" {
1026 if ffPossible {
1027 strategy = "ff"
1028 } else {
1029 strategy = "merge"
1030 }
1031 }
1032 if strategy == "rebase" && ffPossible {
1033 // Nothing to rewrite: a rebase onto an ancestor is a fast-forward,
1034 // and taking it keeps the original commits and their signatures.
1035 strategy = "ff"
1036 }
1037
1038 // Every server-created commit needs the merger's verified identity.
1039 mergerEmail := ""
1040 if strategy != "ff" {
1041 email, err := c.Store.PrimaryVerifiedEmail(c.User.ID)
1042 if err != nil {
1043 return c.fail(protocol.ExitFailure, "%v", err)
1044 }
1045 if email == "" {
1046 return c.fail(protocol.ExitDenied,
1047 "%s merges create commits carrying your identity: verify a primary email first (or use a fast-forward merge)", strategy)
1048 }
1049 mergerEmail = email
1050 }
1051
1052 var newSHA string
1053 switch strategy {
1054 case "ff":
1055 if !ffPossible {
1056 return c.fail(protocol.ExitUsage,
1057 "fast-forward not possible: %s has diverged from the MR head; use --strategy merge or rebase and re-push", mr.TargetRef)
1058 }
1059 newSHA = headSHA
1060
1061 case "merge":
1062 tree, conflict, err := gitutil.MergeTree(dir, targetSHA, headSHA)
1063 if err != nil {
1064 return c.fail(protocol.ExitFailure, "%v", err)
1065 }
1066 if conflict {
1067 return c.fail(protocol.ExitUsage,
1068 "merge conflicts between %s and the MR head; resolve locally and re-push", mr.TargetRef)
1069 }
1070 msg := fmt.Sprintf("Merge request !%d: %s\n\nMerged %s into %s", mr.Number, mr.Title, mr.SourceRef, mr.TargetRef)
1071 newSHA, err = gitutil.CommitTree(dir, tree, []string{targetSHA, headSHA}, c.User.Username, mergerEmail, msg)
1072 if err != nil {
1073 return c.fail(protocol.ExitFailure, "%v", err)
1074 }
1075
1076 case "squash":
1077 // One new commit with the merged tree. Authorship credit goes to
1078 // the MR author (their verified identity when they have one); the
1079 // committer is the merger.
1080 tree := ""
1081 if ffPossible {
1082 t, err := gitutil.ResolveTree(dir, headSHA)
1083 if err != nil {
1084 return c.fail(protocol.ExitFailure, "%v", err)
1085 }
1086 tree = t
1087 } else {
1088 t, conflict, err := gitutil.MergeTree(dir, targetSHA, headSHA)
1089 if err != nil {
1090 return c.fail(protocol.ExitFailure, "%v", err)
1091 }
1092 if conflict {
1093 return c.fail(protocol.ExitUsage,
1094 "merge conflicts between %s and the MR head; resolve locally and re-push", mr.TargetRef)
1095 }
1096 tree = t
1097 }
1098 authorName, authorEmail := c.User.Username, mergerEmail
1099 if author, err := c.Store.UserByUsername(mr.Author); err == nil {
1100 if ae, err := c.Store.PrimaryVerifiedEmail(author.ID); err == nil && ae != "" {
1101 authorName, authorEmail = author.Username, ae
1102 }
1103 }
1104 msg := fmt.Sprintf("%s (!%d)", mr.Title, mr.Number)
1105 if mr.Body != "" {
1106 msg += "\n\n" + mr.Body
1107 }
1108 var err error
1109 newSHA, err = gitutil.CommitTreeIdent(dir, tree, []string{targetSHA},
1110 authorName, authorEmail, "", c.User.Username, mergerEmail, msg)
1111 if err != nil {
1112 return c.fail(protocol.ExitFailure, "%v", err)
1113 }
1114
1115 case "rebase":
1116 commits, err := gitutil.RevListRange(dir, targetSHA, headSHA)
1117 if err != nil {
1118 return c.fail(protocol.ExitFailure, "%v", err)
1119 }
1120 // Oldest first.
1121 for i, j := 0, len(commits)-1; i < j; i, j = i+1, j-1 {
1122 commits[i], commits[j] = commits[j], commits[i]
1123 }
1124 onto := targetSHA
1125 for _, sha := range commits {
1126 parents, err := gitutil.CommitParents(dir, sha)
1127 if err != nil {
1128 return c.fail(protocol.ExitFailure, "%v", err)
1129 }
1130 if len(parents) > 1 {
1131 return c.fail(protocol.ExitUsage,
1132 "the MR contains merge commit %.10s; a rebase merge needs linear history — use --strategy merge or squash", sha)
1133 }
1134 base := onto // root commit: replay against the new tip itself
1135 if len(parents) == 1 {
1136 base = parents[0]
1137 }
1138 tree, conflict, err := gitutil.MergeTreeOnto(dir, base, onto, sha)
1139 if err != nil {
1140 return c.fail(protocol.ExitFailure, "%v", err)
1141 }
1142 if conflict {
1143 return c.fail(protocol.ExitUsage,
1144 "commit %.10s does not apply cleanly onto %s; rebase locally and re-push", sha, mr.TargetRef)
1145 }
1146 aName, aEmail, aDate, err := gitutil.AuthorIdent(dir, sha)
1147 if err != nil {
1148 return c.fail(protocol.ExitFailure, "%v", err)
1149 }
1150 msg, err := gitutil.CommitMessage(dir, sha)
1151 if err != nil {
1152 return c.fail(protocol.ExitFailure, "%v", err)
1153 }
1154 onto, err = gitutil.CommitTreeIdent(dir, tree, []string{onto},
1155 aName, aEmail, aDate, c.User.Username, mergerEmail, msg)
1156 if err != nil {
1157 return c.fail(protocol.ExitFailure, "%v", err)
1158 }
1159 }
1160 newSHA = onto
1161 }
1162
1163 // A stacked merge request's diff is against this branch. After a
1164 // fast-forward or merge commit the same commits are on the target and
1165 // its diff is unchanged there; after a squash or rebase they are not,
1166 // and the stack would carry this merge request's changes a second
1167 // time. Refuse rather than leave the stack wrong.
1168 var stack []store.MR
1169 if mr.SourceRepoID == repo.ID {
1170 stack, _ = c.Store.OpenMRsByTarget(repo.ID, mr.SourceRef)
1171 }
1172 if len(stack) > 0 && (strategy == "squash" || strategy == "rebase") {
1173 var nums []string
1174 for _, k := range stack {
1175 nums = append(nums, fmt.Sprintf("!%d", k.Number))
1176 }
1177 return c.fail(protocol.ExitUsage,
1178 "%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",
1179 fmt.Sprintf("!%d", mr.Number), strings.Join(nums, ", "), strategy, mr.SourceRef)
1180 }
1181
1182 // CAS so a concurrent push between our read and this write fails the
1183 // merge instead of silently discarding the push.
1184 if err := gitutil.UpdateRefCAS(dir, targetRef, newSHA, targetSHA); err != nil {
1185 return c.fail(protocol.ExitFailure, "target branch moved during merge; retry: %v", err)
1186 }
1187 if err := c.Store.MarkMerged(mr.ID, targetSHA, c.User.ID, ""); err != nil {
1188 return c.fail(protocol.ExitFailure, "%v", err)
1189 }
1190 c.Store.RecordEvent(repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d,"sha":%q}`, mr.Number, newSHA))
1191 // The stack moves up: whatever targeted this branch now targets what
1192 // it merged into, reviews intact, since that diff is the one they
1193 // were of.
1194 for _, k := range stack {
1195 if err := c.Store.RetargetKeepingReviews(k.ID, mr.TargetRef); err != nil {
1196 continue
1197 }
1198 c.Store.AddMRSystemComment(k.ID, c.User.ID, fmt.Sprintf("retargeted from %s to %s: !%d merged", mr.SourceRef, mr.TargetRef, mr.Number))
1199 if parts, err := c.Store.MRParticipants(k.ID); err == nil {
1200 notify(c, parts, notice{repo: repo, kind: "mr",
1201 subject: mrSubject(repo, k.Number, k.Title),
1202 action: fmt.Sprintf("retargeted !%d from %s to %s: !%d merged", k.Number, mr.SourceRef, mr.TargetRef, mr.Number),
1203 path: fmt.Sprintf("%s/mrs/%d", repo.Path(), k.Number)})
1204 }
1205 }
1206 // Merges bypass receive-pack, so the commit-message issue actions
1207 // (closes #N, references) run here for the newly landed commits. The
1208 // description is scanned after them, so a commit wins the attribution
1209 // when both name the same issue.
1210 if mr.TargetRef == repo.DefaultBranch {
1211 ProcessCommitMessages(c.Store, dir, repo, c.User.ID, c.Scope, targetSHA, newSHA)
1212 ProcessMRDescription(c.Store, repo, mr, c.User.ID, c.Scope)
1213 RecordLandedCommits(c.Store, dir, repo, targetSHA, newSHA)
1214 }
1215 // A merge moves the ref directly, so it never reaches post-receive and
1216 // none of the ref-update work fires on its own. The event webhooks
1217 // subscribe to, and the branch's CI jobs, happen here instead.
1218 c.Store.RecordEvent(repo.ID, c.User.ID, "push", fmt.Sprintf(
1219 `{"ref":%q,"old":%q,"new":%q,"forced":false,"deleted":false}`,
1220 targetRef, targetSHA, newSHA))
1221 QueueBranchBuilds(c.Store, c.Cfg.Server.Root, c.Cfg.Server.SiteURL,
1222 repo, c.User.ID, mr.TargetRef, targetSHA, newSHA, time.Now())
1223 c.Store.MarkMirrorsDirty(repo.ID, "push")
1224 if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
1225 notify(c, parts, notice{repo: repo, kind: "mr",
1226 subject: mrSubject(repo, mr.Number, mr.Title),
1227 action: fmt.Sprintf("merged !%d into %s (%s)", mr.Number, mr.TargetRef, strategy),
1228 path: fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
1229 }
1230 return c.emit(map[string]any{"number": mr.Number, "strategy": strategy, "sha": newSHA}, func(w io.Writer) {
1231 fmt.Fprintf(w, "merged %s!%d into %s (%s) at %.10s\n", repo.Path(), mr.Number, mr.TargetRef, strategy, newSHA)
1232 })
1233}
1234
1235// reviewGates refuses a merge whose gates are not all met, naming every
1236// unmet one. Returns -1 to proceed.
1237func (c *Ctx) reviewGates(repo store.Repo, mr store.MR, dir, targetSHA, headSHA string) int {
1238 g, err := MergeGates(c.Store, repo, mr, dir, targetSHA, headSHA)
1239 if err != nil {
1240 return c.fail(protocol.ExitFailure, "%v", err)
1241 }
1242 if len(g.Unmet) > 0 {
1243 return c.fail(protocol.ExitDenied, "%s", strings.Join(g.Unmet, "; "))
1244 }
1245 return -1
1246}
1247
1248// MergeGates computes where a merge request stands against its
1249// repository's gates: draft, require_checks, require_approvals (fresh,
1250// non-author, latest review per reviewer from someone who can write; a
1251// fresh request-changes blocks), require_codeowners and require_resolved.
1252// Unmet carries one sentence per gate not passed. Fast-forward is
1253// reported, not gated: whether it matters depends on the strategy.
1254func MergeGates(st *store.Store, repo store.Repo, mr store.MR, dir, targetSHA, headSHA string) (GatesOut, error) {
1255 set := repo.Settings
1256 g := GatesOut{Draft: mr.Draft, ApprovalsRequired: set.RequireApprovals,
1257 CodeownersRequired: set.RequireCodeowners, ResolvedRequired: set.RequireResolved,
1258 ChecksRequired: set.RequireChecks}
1259 // A draft is open but not asking. This gate is unconditional — no
1260 // setting turns it off — because the author said so themselves.
1261 if mr.Draft {
1262 g.Unmet = append(g.Unmet, fmt.Sprintf("!%d is a draft; `gitbay mr ready %s %d` first", mr.Number, repo.Path(), mr.Number))
1263 }
1264
1265 // Checks: with require_checks, the head must carry statuses and every
1266 // one of them must be green.
1267 statuses, err := st.ListCommitStatuses(repo.ID, headSHA)
1268 if err != nil {
1269 return g, err
1270 }
1271 g.Checks = store.CombinedStatus(statuses)
1272 if set.RequireChecks {
1273 switch g.Checks {
1274 case "success":
1275 case "":
1276 g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires green checks and none were reported on %.10s", repo.Path(), headSHA))
1277 default:
1278 var bad []string
1279 for _, st := range statuses {
1280 if st.State != "success" {
1281 bad = append(bad, st.Context+"="+st.State)
1282 }
1283 }
1284 g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires green checks; %.10s has %s", repo.Path(), headSHA, strings.Join(bad, ", ")))
1285 }
1286 }
1287
1288 reviews, err := st.ListMRReviews(mr.ID)
1289 if err != nil {
1290 return g, err
1291 }
1292 // Latest fresh review per reviewer decides their stance — but only
1293 // from someone the repository trusts to write to it. Reviewing is
1294 // open to any reader, which is what makes an outside opinion on a
1295 // public change possible; deciding a merge gate is not the same
1296 // thing, and counting every verdict let anyone with an account
1297 // satisfy require_approvals or block a merge indefinitely (#147).
1298 counts := ReviewersWhoCount(st, repo, reviews)
1299 latest := map[string]string{}
1300 for _, r := range reviews {
1301 if r.Stale || r.Reviewer == mr.Author || !counts[r.Reviewer] {
1302 continue
1303 }
1304 latest[r.Reviewer] = r.Verdict
1305 }
1306 for who, verdict := range latest {
1307 switch verdict {
1308 case "approve":
1309 g.Approvals = append(g.Approvals, who)
1310 case "request_changes":
1311 g.ChangesRequested = append(g.ChangesRequested, who)
1312 }
1313 }
1314 slices.Sort(g.Approvals)
1315 slices.Sort(g.ChangesRequested)
1316 if set.RequireApprovals > 0 {
1317 if len(g.ChangesRequested) > 0 {
1318 g.Unmet = append(g.Unmet, fmt.Sprintf("%s requested changes on !%d; resolve their review before merging", strings.Join(g.ChangesRequested, ", "), mr.Number))
1319 }
1320 if len(g.Approvals) < set.RequireApprovals {
1321 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)))
1322 }
1323 }
1324
1325 // CODEOWNERS: every owned changed file needs an approval from one of
1326 // its owners. require_codeowners is the opt-in — a repository can
1327 // carry the file as documentation of who to ask without it gating
1328 // merges — and it does not wait on require_approvals (#99).
1329 if set.RequireCodeowners {
1330 content, err := gitutil.ReadBlob(dir, "refs/heads/"+mr.TargetRef, "CODEOWNERS", 1<<20)
1331 if err != nil {
1332 content, err = gitutil.ReadBlob(dir, "refs/heads/"+mr.TargetRef, ".gitbay/CODEOWNERS", 1<<20)
1333 }
1334 if err != nil || len(content) == 0 {
1335 g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires CODEOWNERS approval but %s carries no CODEOWNERS file", repo.Path(), mr.TargetRef))
1336 } else {
1337 rules := policy.ParseCodeowners(string(content))
1338 base, err := gitutil.MergeBase(dir, targetSHA, headSHA)
1339 if err != nil {
1340 return g, err
1341 }
1342 files, err := gitutil.DiffFiles(dir, base, headSHA)
1343 if err != nil {
1344 return g, err
1345 }
1346 approved := map[string]bool{}
1347 for _, a := range g.Approvals {
1348 approved[a] = true
1349 }
1350 missing := map[string][]string{} // owner-set key -> paths
1351 var keys []string
1352 for _, f := range files {
1353 owners := policy.OwnersFor(rules, f)
1354 if owners == nil {
1355 continue
1356 }
1357 ok := false
1358 for _, o := range owners {
1359 if approved[o] {
1360 ok = true
1361 break
1362 }
1363 }
1364 if !ok {
1365 key := strings.Join(owners, ",")
1366 if _, seen := missing[key]; !seen {
1367 keys = append(keys, key)
1368 }
1369 missing[key] = append(missing[key], f)
1370 }
1371 }
1372 if len(missing) > 0 {
1373 slices.Sort(keys)
1374 var parts []string
1375 for _, key := range keys {
1376 paths := missing[key]
1377 g.OwnersOutstanding = append(g.OwnersOutstanding, OwnersOut{Files: paths, Owners: strings.Split(key, ",")})
1378 if len(paths) > 3 {
1379 paths = paths[:3]
1380 }
1381 parts = append(parts, fmt.Sprintf("%s (owned by %s)", strings.Join(paths, ", "), key))
1382 }
1383 g.Unmet = append(g.Unmet, "CODEOWNERS approval missing for: "+strings.Join(parts, "; "))
1384 }
1385 }
1386 }
1387
1388 n, err := st.UnresolvedThreadCount(mr.ID)
1389 if err != nil {
1390 return g, err
1391 }
1392 g.OpenThreads = n
1393 if set.RequireResolved && n > 0 {
1394 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))
1395 }
1396
1397 if ff, err := gitutil.IsAncestor(dir, targetSHA, headSHA); err == nil {
1398 g.FastForward = ff
1399 }
1400 return g, nil
1401}
1402
1403func runMRDraft(c *Ctx, args []string) int { return setMRDraft(c, args, true) }
1404func runMRReady(c *Ctx, args []string) int { return setMRDraft(c, args, false) }
1405
1406func setMRDraft(c *Ctx, args []string, draft bool) int {
1407 verb := "ready"
1408 if draft {
1409 verb = "draft"
1410 }
1411 repo, mr, code := mrRef(c, args, policy.CanRead)
1412 if code >= 0 {
1413 return code
1414 }
1415 if code := refuseArchived(c, repo); code >= 0 {
1416 return code
1417 }
1418 if len(args) != 2 {
1419 return c.fail(protocol.ExitUsage, "usage: mr %s <owner/name> <n>", verb)
1420 }
1421 if code := authorOrWrite(c, repo, mr.Author, "change this merge request"); code >= 0 {
1422 return code
1423 }
1424 if mr.State != "open" && mr.State != "source_gone" {
1425 return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
1426 }
1427 if mr.Draft == draft {
1428 state := "already ready"
1429 if draft {
1430 state = "already a draft"
1431 }
1432 return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, state)
1433 }
1434 if err := c.Store.SetMRDraft(mr.ID, draft); err != nil {
1435 return c.fail(protocol.ExitFailure, "%v", err)
1436 }
1437 c.Store.RecordEvent(repo.ID, c.User.ID, "mr.draft",
1438 fmt.Sprintf(`{"number":%d,"draft":%t}`, mr.Number, draft))
1439 // Marking ready is the request for review; going back to draft
1440 // withdraws it and is not worth anyone's inbox.
1441 //
1442 // The targets are the repository's, not the thread's participants.
1443 // Until someone comments or reviews, the only participant is the
1444 // author, who is the actor and excluded — so notifying participants
1445 // here reaches nobody, which is exactly what opening it as a draft
1446 // and then marking it ready would do. Opening a merge request tells
1447 // the repository; so does saying it is finally asking. A review
1448 // request made before ready — or on an earlier revision — reaches its
1449 // target here too: they are exactly who else is being asked.
1450 if !draft {
1451 if targets, err := c.Store.RepoNotifyTargets(repo); err == nil {
1452 parts, _ := c.Store.MRParticipants(mr.ID)
1453 reviewers, _ := c.Store.MRReviewRequestIDs(mr.ID)
1454 notify(c, append(append(targets, parts...), reviewers...), notice{repo: repo, kind: "mr",
1455 subject: mrSubject(repo, mr.Number, mr.Title),
1456 action: fmt.Sprintf("marked !%d ready for review", mr.Number),
1457 path: fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
1458 }
1459 }
1460 return c.emit(map[string]any{"number": mr.Number, "draft": draft}, func(w io.Writer) {
1461 fmt.Fprintf(w, "%s!%d is %s\n", repo.Path(), mr.Number, map[bool]string{true: "a draft", false: "ready"}[draft])
1462 })
1463}
1464
1465func runMRClose(c *Ctx, args []string) int {
1466 repo, mr, code := mrRef(c, args, policy.CanRead)
1467 if code >= 0 {
1468 return code
1469 }
1470 if code := refuseArchived(c, repo); code >= 0 {
1471 return code
1472 }
1473 if len(args) != 2 {
1474 return c.fail(protocol.ExitUsage, "usage: mr close <owner/name> <n>")
1475 }
1476 if code := authorOrWrite(c, repo, mr.Author, "close this merge request"); code >= 0 {
1477 return code
1478 }
1479 if mr.State == "merged" || mr.State == "closed" {
1480 return c.fail(protocol.ExitUsage, "MR !%d is already %s", mr.Number, mr.State)
1481 }
1482 if err := c.Store.MarkClosed(mr.ID, c.User.ID, ""); err != nil {
1483 return c.fail(protocol.ExitFailure, "%v", err)
1484 }
1485 c.Store.RecordEvent(repo.ID, c.User.ID, "mr.closed", fmt.Sprintf(`{"number":%d}`, mr.Number))
1486 if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
1487 notify(c, parts, notice{repo: repo, kind: "mr",
1488 subject: mrSubject(repo, mr.Number, mr.Title),
1489 action: fmt.Sprintf("closed !%d", mr.Number),
1490 path: fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
1491 }
1492 return c.emit(map[string]any{"number": mr.Number, "state": "closed"}, func(w io.Writer) {
1493 fmt.Fprintf(w, "closed %s!%d\n", repo.Path(), mr.Number)
1494 })
1495}
1496
1497// reviewAction is what a review notification says it was. A verdict with
1498// a batch behind it is a different thing from a bare verdict, and the
1499// person reading the mail is deciding whether to open it.
1500func reviewAction(number int64, verdict string, published int64) string {
1501 if published > 0 {
1502 return fmt.Sprintf("reviewed !%d: %s, with %d comment(s)", number, verdict, published)
1503 }
1504 return fmt.Sprintf("reviewed !%d: %s", number, verdict)
1505}
1506
1507// RevisionOut is one head a merge request has had.
1508type RevisionOut struct {
1509 N int `json:"n"` // 1 is the first push
1510 SHA string `json:"sha"`
1511 BaseSHA string `json:"base_sha,omitempty"`
1512 CreatedAt string `json:"created_at"`
1513 Current bool `json:"current,omitempty"`
1514}
1515
1516func mrRevisions(c *Ctx, mr store.MR) ([]RevisionOut, error) {
1517 heads, err := c.Store.MRHeads(mr.ID)
1518 if err != nil {
1519 return nil, err
1520 }
1521 out := make([]RevisionOut, 0, len(heads))
1522 for i, h := range heads {
1523 out = append(out, RevisionOut{N: i + 1, SHA: h.SHA, BaseSHA: h.BaseSHA,
1524 CreatedAt: h.CreatedAt, Current: h.SHA == mr.HeadSHA})
1525 }
1526 return out, nil
1527}
1528
1529func runMRRevisions(c *Ctx, args []string) int {
1530 repo, mr, code := mrRef(c, args, policy.CanRead)
1531 if code >= 0 {
1532 return code
1533 }
1534 if len(args) != 2 {
1535 return c.fail(protocol.ExitUsage, "usage: mr revisions <owner/name> <n>")
1536 }
1537 revs, err := mrRevisions(c, mr)
1538 if err != nil {
1539 return c.fail(protocol.ExitFailure, "%v", err)
1540 }
1541 return c.emit(revs, func(w io.Writer) {
1542 for _, r := range revs {
1543 mark := " "
1544 if r.Current {
1545 mark = "*"
1546 }
1547 fmt.Fprintf(w, "%s v%d\t%.10s\t%s\n", mark, r.N, r.SHA, r.CreatedAt)
1548 }
1549 if len(revs) < 2 {
1550 fmt.Fprintf(w, "\nonly one revision; %s!%d has not been pushed to since it was opened\n",
1551 repo.Path(), mr.Number)
1552 }
1553 })
1554}
1555
1556func runMRRangeDiff(c *Ctx, args []string) int {
1557 const usage = "mr range-diff <owner/name> <n> [--from <sha>] [--to <sha>]"
1558 f, err := parseFlags(args, flagSpec{Values: []string{"--from", "--to"}, MaxPos: 2, Usage: usage})
1559 if err != nil {
1560 return c.fail(protocol.ExitUsage, "%v", err)
1561 }
1562 repo, mr, code := mrRef(c, f.Pos, policy.CanRead)
1563 if code >= 0 {
1564 return code
1565 }
1566 if len(f.Pos) != 2 {
1567 return c.fail(protocol.ExitUsage, "usage: %s", usage)
1568 }
1569 revs, err := mrRevisions(c, mr)
1570 if err != nil {
1571 return c.fail(protocol.ExitFailure, "%v", err)
1572 }
1573 // One revision is a merge request nobody has pushed to since it was
1574 // opened. The argv was fine and the answer is "nothing changed", so
1575 // this succeeds with an empty patch rather than failing.
1576 if len(revs) < 2 {
1577 fmt.Fprintf(c.Stderr, "%s!%d has one revision; nothing to compare it against\n",
1578 repo.Path(), mr.Number)
1579 return protocol.ExitOK
1580 }
1581 // Default to the two most recent, which is "what changed since the
1582 // last push" — the question a stale review asks.
1583 from, to := revs[len(revs)-2], revs[len(revs)-1]
1584 pick := func(sha string) (RevisionOut, bool) {
1585 for _, r := range revs {
1586 if strings.HasPrefix(r.SHA, sha) {
1587 return r, true
1588 }
1589 }
1590 return RevisionOut{}, false
1591 }
1592 if v := f.Value("--from"); v != "" {
1593 r, ok := pick(v)
1594 if !ok {
1595 return c.fail(protocol.ExitNotFound, "%.12s is not a revision of !%d; see `mr revisions`", v, mr.Number)
1596 }
1597 from = r
1598 }
1599 if v := f.Value("--to"); v != "" {
1600 r, ok := pick(v)
1601 if !ok {
1602 return c.fail(protocol.ExitNotFound, "%.12s is not a revision of !%d; see `mr revisions`", v, mr.Number)
1603 }
1604 to = r
1605 }
1606 if from.SHA == to.SHA {
1607 return c.fail(protocol.ExitUsage, "--from and --to are the same revision")
1608 }
1609
1610 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
1611 // A revision recorded before its base could be worked out, or by a
1612 // migration backfill, falls back to the target's merge base.
1613 baseOf := func(r RevisionOut) string {
1614 if r.BaseSHA != "" {
1615 return r.BaseSHA
1616 }
1617 b, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, r.SHA)
1618 if err != nil {
1619 return r.SHA + "^"
1620 }
1621 return b
1622 }
1623 patch, truncated, err := gitutil.RangeDiff(dir, baseOf(from), from.SHA, baseOf(to), to.SHA, 4<<20)
1624 if err != nil {
1625 return c.fail(protocol.ExitFailure,
1626 "%v (the objects for an older revision may have been garbage-collected)", err)
1627 }
1628 fmt.Fprint(c.Stdout, patch)
1629 if truncated {
1630 fmt.Fprintln(c.Stderr, "range-diff truncated at 4 MiB")
1631 }
1632 return protocol.ExitOK
1633}
1634
1635// reviewersWhoCount is the set of reviewers whose verdict decides a merge
1636// gate: those with write access to the repository.
1637//
1638// Write, rather than a separate reviewer role, because it is the same
1639// question the gates already answer — a person who could push this change
1640// themselves is the person whose approval means the repository accepts
1641// it. Someone named in CODEOWNERS without write is a misconfiguration the
1642// owner should fix rather than a case to special-case here: they could
1643// not merge what they approved.
1644// Exported because the web renders the same distinction: a page that
1645// showed an approval the gate ignores would differ from the gate, and the
1646// difference would only surface when a merge was refused.
1647func ReviewersWhoCount(st *store.Store, repo store.Repo, reviews []store.MRReview) map[string]bool {
1648 counts := map[string]bool{}
1649 for _, r := range reviews {
1650 if _, done := counts[r.Reviewer]; done {
1651 continue
1652 }
1653 counts[r.Reviewer] = false
1654 u, err := st.UserByUsername(r.Reviewer)
1655 if err != nil {
1656 continue
1657 }
1658 grant, err := st.AccessRole(repo.ID, u.ID)
1659 if err != nil {
1660 continue
1661 }
1662 counts[r.Reviewer] = policy.CanWrite(u, repo, grant)
1663 }
1664 return counts
1665}