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