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