internal/control/mr.go

33f4fa3490944ada57c2a5c57e6650020c1afeab
gitbay/internal/control/mr.go history · blame · raw

969 lines · 32349 bytes

  1package control
  2
  3import (
  4	"errors"
  5	"fmt"
  6	"io"
  7	"slices"
  8	"strconv"
  9	"strings"
 10
 11	"gitbay.org/gitbay/internal/gitutil"
 12	"gitbay.org/gitbay/internal/policy"
 13	"gitbay.org/gitbay/internal/protocol"
 14	"gitbay.org/gitbay/internal/store"
 15)
 16
 17func init() {
 18	register(Command{Path: []string{"repo", "fork"},
 19		Summary: "fork a repository under your account: repo fork <owner/name> [--name <n>]", Run: runRepoFork})
 20	register(Command{Path: []string{"repo", "settings", "require-approvals"},
 21		Summary: "require N fresh approvals to merge: repo settings require-approvals <owner/name> <n> (0 = off)", Run: runRequireApprovals})
 22	register(Command{Path: []string{"repo", "settings", "require-resolved"},
 23		Summary: "require all review threads resolved to merge: repo settings require-resolved <owner/name> on|off", Run: runRequireResolved})
 24	register(Command{Path: []string{"repo", "settings", "require-checks"},
 25		Summary: "gate merges on green statuses: repo settings require-checks <owner/name> on|off", Run: runRequireChecks})
 26	register(Command{Path: []string{"repo", "settings", "require-signed"},
 27		Summary: "require verified commit signatures: repo settings require-signed <owner/name> on|off", Run: runRequireSigned})
 28	register(Command{Path: []string{"mr", "create"},
 29		Summary:    "open a merge request: mr create <target owner/name> --source [owner/name:]<branch> --target <branch> --title <t> [--body <b> | --file -]",
 30		ReadsStdin: true, Run: runMRCreate})
 31	register(Command{Path: []string{"mr", "list"},
 32		Summary: "list merge requests: mr list <owner/name> [--state open|merged|closed|source_gone|all]", ReadOnly: true, Run: runMRList})
 33	register(Command{Path: []string{"mr", "show"},
 34		Summary: "show a merge request: mr show <owner/name> <n>", ReadOnly: true, Run: runMRShow})
 35	register(Command{Path: []string{"mr", "diff"},
 36		Summary: "show the diff: mr diff <owner/name> <n>", ReadOnly: true, Run: runMRDiff})
 37	register(Command{Path: []string{"mr", "comment"},
 38		Summary:    "comment: mr comment <owner/name> <n> [--message <m> | --file -]",
 39		ReadsStdin: true, Run: runMRComment})
 40	register(Command{Path: []string{"mr", "review"},
 41		Summary: "review: mr review <owner/name> <n> --approve|--request-changes|--comment", Run: runMRReview})
 42	register(Command{Path: []string{"mr", "merge"},
 43		Summary: "merge: mr merge <owner/name> <n> [--strategy ff|merge|squash|rebase]", Run: runMRMerge})
 44	register(Command{Path: []string{"mr", "close"},
 45		Summary: "close without merging: mr close <owner/name> <n>", Run: runMRClose})
 46}
 47
 48func runRepoFork(c *Ctx, args []string) int {
 49	var path, name string
 50	for i := 0; i < len(args); i++ {
 51		switch args[i] {
 52		case "--name":
 53			if i+1 >= len(args) {
 54				return c.fail(protocol.ExitUsage, "--name requires a value")
 55			}
 56			name = args[i+1]
 57			i++
 58		default:
 59			if path != "" {
 60				return c.fail(protocol.ExitUsage, "usage: repo fork <owner/name> [--name <n>]")
 61			}
 62			path = args[i]
 63		}
 64	}
 65	if path == "" {
 66		return c.fail(protocol.ExitUsage, "usage: repo fork <owner/name> [--name <n>]")
 67	}
 68	src, code := resolveRepo(c, path, policy.CanRead)
 69	if code >= 0 {
 70		return code
 71	}
 72	if name == "" {
 73		name = src.Name
 74	}
 75	if err := policy.ValidateName(name); err != nil {
 76		return c.fail(protocol.ExitUsage, "%v", err)
 77	}
 78	id, err := c.Store.CreateRepo("user", c.User.ID, name, src.Visibility)
 79	if err != nil {
 80		return c.fail(protocol.ExitFailure, "%v", err)
 81	}
 82	if err := c.Store.SetForkOf(id, src.ID); err != nil {
 83		return c.fail(protocol.ExitFailure, "%v", err)
 84	}
 85	dstDir := RepoDir(c.Cfg.Server.Root, c.User.Username, name)
 86	srcDir := RepoDir(c.Cfg.Server.Root, src.OwnerName, src.Name)
 87	if err := gitutil.InitBare(dstDir, "main", HooksDir(c.Cfg.Server.Root)); err != nil {
 88		c.Store.DeleteRepo(id)
 89		return c.fail(protocol.ExitFailure, "%v", err)
 90	}
 91	if desc := gitutil.ReadDescription(srcDir); desc != "" {
 92		gitutil.WriteDescription(dstDir, desc)
 93	}
 94	if err := gitutil.FetchInto(dstDir, srcDir, "refs/heads/*", "refs/heads/*"); err != nil {
 95		// Empty source repos have nothing to fetch; that is fine.
 96		if _, rerr := gitutil.ResolveRef(srcDir, src.DefaultBranch); rerr == nil {
 97			c.Store.DeleteRepo(id)
 98			return c.fail(protocol.ExitFailure, "copying refs: %v", err)
 99		}
100	}
101	forkPath := c.User.Username + "/" + name
102	return c.emit(map[string]string{"path": forkPath, "fork_of": src.Path()}, func(w io.Writer) {
103		fmt.Fprintf(w, "forked %s to %s\n", src.Path(), forkPath)
104	})
105}
106
107func runRequireApprovals(c *Ctx, args []string) int {
108	if len(args) != 2 {
109		return c.fail(protocol.ExitUsage, "usage: repo settings require-approvals <owner/name> <n>")
110	}
111	n, err := strconv.Atoi(args[1])
112	if err != nil || n < 0 || n > 20 {
113		return c.fail(protocol.ExitUsage, "approvals must be 0..20")
114	}
115	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
116	if code >= 0 {
117		return code
118	}
119	s := repo.Settings
120	s.RequireApprovals = n
121	if err := c.Store.SetRepoSettings(repo.ID, s); err != nil {
122		return c.fail(protocol.ExitFailure, "%v", err)
123	}
124	return c.emit(s, func(w io.Writer) {
125		fmt.Fprintf(w, "require_approvals %d on %s\n", n, repo.Path())
126	})
127}
128
129func runRequireResolved(c *Ctx, args []string) int {
130	if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
131		return c.fail(protocol.ExitUsage, "usage: repo settings require-resolved <owner/name> on|off")
132	}
133	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
134	if code >= 0 {
135		return code
136	}
137	s := repo.Settings
138	s.RequireResolved = args[1] == "on"
139	if err := c.Store.SetRepoSettings(repo.ID, s); err != nil {
140		return c.fail(protocol.ExitFailure, "%v", err)
141	}
142	return c.emit(s, func(w io.Writer) {
143		fmt.Fprintf(w, "require_resolved %s on %s\n", args[1], repo.Path())
144	})
145}
146
147func runRequireChecks(c *Ctx, args []string) int {
148	if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
149		return c.fail(protocol.ExitUsage, "usage: repo settings require-checks <owner/name> on|off")
150	}
151	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
152	if code >= 0 {
153		return code
154	}
155	s := repo.Settings
156	s.RequireChecks = args[1] == "on"
157	if err := c.Store.SetRepoSettings(repo.ID, s); err != nil {
158		return c.fail(protocol.ExitFailure, "%v", err)
159	}
160	return c.emit(s, func(w io.Writer) {
161		fmt.Fprintf(w, "require_checks %s on %s\n", args[1], repo.Path())
162	})
163}
164
165func runRequireSigned(c *Ctx, args []string) int {
166	if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
167		return c.fail(protocol.ExitUsage, "usage: repo settings require-signed <owner/name> on|off")
168	}
169	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
170	if code >= 0 {
171		return code
172	}
173	s := repo.Settings
174	s.RequireSignedCommits = args[1] == "on"
175	if err := c.Store.SetRepoSettings(repo.ID, s); err != nil {
176		return c.fail(protocol.ExitFailure, "%v", err)
177	}
178	return c.emit(s, func(w io.Writer) {
179		fmt.Fprintf(w, "require_signed_commits %s on %s\n", args[1], repo.Path())
180	})
181}
182
183// mrRef parses "<owner/name> <n>" and loads the MR.
184func mrRef(c *Ctx, args []string, perm func(store.User, store.Repo, string) bool) (store.Repo, store.MR, int) {
185	if len(args) < 2 {
186		return store.Repo{}, store.MR{}, c.fail(protocol.ExitUsage, "expected <owner/name> <number>")
187	}
188	repo, code := resolveRepo(c, args[0], perm)
189	if code >= 0 {
190		return repo, store.MR{}, code
191	}
192	n, err := strconv.ParseInt(args[1], 10, 64)
193	if err != nil {
194		return repo, store.MR{}, c.fail(protocol.ExitUsage, "bad MR number %q", args[1])
195	}
196	mr, err := c.Store.MRByNumber(repo.ID, n)
197	if errors.Is(err, store.ErrNotFound) {
198		return repo, mr, c.fail(protocol.ExitNotFound, "MR !%d not found in %s", n, repo.Path())
199	}
200	if err != nil {
201		return repo, mr, c.fail(protocol.ExitFailure, "%v", err)
202	}
203	return repo, mr, -1
204}
205
206func mrHeadRef(n int64) string { return fmt.Sprintf("refs/merge-requests/%d/head", n) }
207
208func runMRCreate(c *Ctx, args []string) int {
209	var path, source, target, title, body, file string
210	for i := 0; i < len(args); i++ {
211		switch args[i] {
212		case "--source", "--target", "--title", "--body", "--file":
213			if i+1 >= len(args) {
214				return c.fail(protocol.ExitUsage, "%s requires a value", args[i])
215			}
216			v := args[i+1]
217			switch args[i] {
218			case "--source":
219				source = v
220			case "--target":
221				target = v
222			case "--title":
223				title = v
224			case "--body":
225				body = v
226			case "--file":
227				file = v
228			}
229			i++
230		default:
231			if path != "" {
232				return c.fail(protocol.ExitUsage, "unexpected argument %q", args[i])
233			}
234			path = args[i]
235		}
236	}
237	if path == "" || source == "" || title == "" {
238		return c.fail(protocol.ExitUsage, "usage: mr create <target owner/name> --source [owner/name:]<branch> --target <branch> --title <t>")
239	}
240	repo, code := resolveRepo(c, path, policy.CanRead)
241	if code >= 0 {
242		return code
243	}
244	if code := refuseArchived(c, repo); code >= 0 {
245		return code
246	}
247	if target == "" {
248		target = repo.DefaultBranch
249	}
250
251	// Source is "branch" (same repo) or "owner/name:branch" (a fork).
252	srcRepo := repo
253	srcBranch := source
254	if sp, br, ok := strings.Cut(source, ":"); ok {
255		srcBranch = br
256		var scode int
257		srcRepo, scode = resolveRepo(c, sp, policy.CanRead)
258		if scode >= 0 {
259			return scode
260		}
261		if srcRepo.ForkOf != repo.ID && srcRepo.ID != repo.ID {
262			return c.fail(protocol.ExitUsage, "%s is not a fork of %s", srcRepo.Path(), repo.Path())
263		}
264	}
265	srcDir := RepoDir(c.Cfg.Server.Root, srcRepo.OwnerName, srcRepo.Name)
266	headSHA, err := gitutil.ResolveRef(srcDir, "refs/heads/"+srcBranch)
267	if err != nil {
268		return c.fail(protocol.ExitNotFound, "branch %s not found in %s", srcBranch, srcRepo.Path())
269	}
270	b, err := bodyFrom(c, body, file)
271	if err != nil {
272		return c.fail(protocol.ExitUsage, "%v", err)
273	}
274	n, err := c.Store.CreateMR(repo.ID, c.User.ID, srcRepo.ID, srcBranch, target, title, b, headSHA)
275	if err != nil {
276		return c.fail(protocol.ExitFailure, "%v", err)
277	}
278	// Fetch the head into the target so the target owns the objects.
279	dstDir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
280	if err := gitutil.FetchInto(dstDir, srcDir, headSHA, mrHeadRef(n)); err != nil {
281		return c.fail(protocol.ExitFailure, "recording MR head: %v", err)
282	}
283	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.created", fmt.Sprintf(`{"number":%d}`, n))
284	if targets, err := c.Store.RepoNotifyTargets(repo); err == nil {
285		notifyUsers(c, targets, mrSubject(repo, n, title),
286			notifyBody(c, fmt.Sprintf("opened merge request !%d (%s -> %s)", n, source, target), b, fmt.Sprintf("%s/mrs/%d", repo.Path(), n)))
287	}
288	return c.emit(map[string]any{"number": n, "head_sha": headSHA}, func(w io.Writer) {
289		fmt.Fprintf(w, "created %s!%d (%s -> %s)\n", repo.Path(), n, source, target)
290	})
291}
292
293type mrOut struct {
294	Number    int64  `json:"number"`
295	Title     string `json:"title"`
296	State     string `json:"state"`
297	Author    string `json:"author"`
298	Source    string `json:"source"` // owner/name:branch, or branch, "" if gone
299	TargetRef string `json:"target_ref"`
300	HeadSHA   string `json:"head_sha"`
301	Body      string `json:"body,omitempty"`
302	CreatedAt string `json:"created_at"`
303}
304
305func mrToOut(repo store.Repo, m store.MR, withBody bool) mrOut {
306	src := ""
307	if m.SourcePath != "" {
308		if m.SourceRepoID == repo.ID {
309			src = m.SourceRef
310		} else {
311			src = m.SourcePath + ":" + m.SourceRef
312		}
313	}
314	o := mrOut{Number: m.Number, Title: m.Title, State: m.State, Author: m.Author,
315		Source: src, TargetRef: m.TargetRef, HeadSHA: m.HeadSHA, CreatedAt: m.CreatedAt}
316	if withBody {
317		o.Body = m.Body
318	}
319	return o
320}
321
322func runMRList(c *Ctx, args []string) int {
323	state := "open"
324	var path string
325	for i := 0; i < len(args); i++ {
326		switch args[i] {
327		case "--state":
328			if i+1 >= len(args) {
329				return c.fail(protocol.ExitUsage, "--state requires a value")
330			}
331			state = args[i+1]
332			i++
333		default:
334			if path != "" {
335				return c.fail(protocol.ExitUsage, "unexpected argument %q", args[i])
336			}
337			path = args[i]
338		}
339	}
340	valid := map[string]bool{"open": true, "merged": true, "closed": true, "source_gone": true, "all": true}
341	if path == "" || !valid[state] {
342		return c.fail(protocol.ExitUsage, "usage: mr list <owner/name> [--state open|merged|closed|source_gone|all]")
343	}
344	repo, code := resolveRepo(c, path, policy.CanRead)
345	if code >= 0 {
346		return code
347	}
348	mrs, err := c.Store.ListMRs(repo.ID, state)
349	if err != nil {
350		return c.fail(protocol.ExitFailure, "%v", err)
351	}
352	var ds []mrOut
353	for _, m := range mrs {
354		ds = append(ds, mrToOut(repo, m, false))
355	}
356	return c.emit(ds, func(w io.Writer) {
357		for _, d := range ds {
358			fmt.Fprintf(w, "!%d\t%s\t%s\t%s -> %s\n", d.Number, d.State, d.Title, d.Source, d.TargetRef)
359		}
360	})
361}
362
363func runMRShow(c *Ctx, args []string) int {
364	repo, mr, code := mrRef(c, args, policy.CanRead)
365	if code >= 0 {
366		return code
367	}
368	if len(args) != 2 {
369		return c.fail(protocol.ExitUsage, "usage: mr show <owner/name> <n>")
370	}
371	comments, err := c.Store.ListMRComments(mr.ID)
372	if err != nil {
373		return c.fail(protocol.ExitFailure, "%v", err)
374	}
375	reviews, err := c.Store.ListMRReviews(mr.ID)
376	if err != nil {
377		return c.fail(protocol.ExitFailure, "%v", err)
378	}
379	statuses, err := c.Store.ListCommitStatuses(repo.ID, mr.HeadSHA)
380	if err != nil {
381		return c.fail(protocol.ExitFailure, "%v", err)
382	}
383	unresolved, err := c.Store.UnresolvedThreadCount(mr.ID)
384	if err != nil {
385		return c.fail(protocol.ExitFailure, "%v", err)
386	}
387	type commentOut struct {
388		Author    string `json:"author"`
389		Body      string `json:"body"`
390		CreatedAt string `json:"created_at"`
391	}
392	type reviewOut struct {
393		Reviewer string `json:"reviewer"`
394		Verdict  string `json:"verdict"`
395		Stale    bool   `json:"stale"`
396	}
397	type checkOut struct {
398		Context string `json:"context"`
399		State   string `json:"state"`
400		URL     string `json:"url,omitempty"`
401	}
402	var checks []checkOut
403	for _, st := range statuses {
404		checks = append(checks, checkOut{st.Context, st.State, st.TargetURL})
405	}
406	var cs []commentOut
407	for _, cm := range comments {
408		cs = append(cs, commentOut{cm.Author, cm.Body, cm.CreatedAt})
409	}
410	var rs []reviewOut
411	for _, r := range reviews {
412		rs = append(rs, reviewOut{r.Reviewer, r.Verdict, r.Stale})
413	}
414	d := struct {
415		mrOut
416		Checks            []checkOut   `json:"checks,omitempty"`
417		Combined          string       `json:"checks_combined,omitempty"`
418		UnresolvedThreads int          `json:"unresolved_threads,omitempty"`
419		Comments          []commentOut `json:"comments,omitempty"`
420		Reviews           []reviewOut  `json:"reviews,omitempty"`
421	}{mrToOut(repo, mr, true), checks, store.CombinedStatus(statuses), unresolved, cs, rs}
422	return c.emit(d, func(w io.Writer) {
423		fmt.Fprintf(w, "!%d %s [%s] by %s\n%s -> %s @ %.10s\n", d.Number, d.Title, d.State, d.Author, d.Source, d.TargetRef, d.HeadSHA)
424		if d.Body != "" {
425			fmt.Fprintf(w, "\n%s\n", d.Body)
426		}
427		for _, x := range checks {
428			fmt.Fprintf(w, "check: %s %s\n", x.Context, x.State)
429		}
430		if d.UnresolvedThreads > 0 {
431			fmt.Fprintf(w, "unresolved threads: %d\n", d.UnresolvedThreads)
432		}
433		for _, r := range rs {
434			stale := ""
435			if r.Stale {
436				stale = " (stale)"
437			}
438			fmt.Fprintf(w, "review: %s %s%s\n", r.Reviewer, r.Verdict, stale)
439		}
440		for _, cm := range cs {
441			fmt.Fprintf(w, "\n--- %s at %s\n%s\n", cm.Author, cm.CreatedAt, cm.Body)
442		}
443	})
444}
445
446func runMRDiff(c *Ctx, args []string) int {
447	repo, mr, code := mrRef(c, args, policy.CanRead)
448	if code >= 0 {
449		return code
450	}
451	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
452	head := mrHeadRef(mr.Number)
453	// After a merge (especially fast-forward) the live merge-base equals
454	// the head and the diff would vanish; use the recorded base instead.
455	base := mr.MergedBase
456	if base == "" {
457		b, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, head)
458		if err != nil {
459			return c.fail(protocol.ExitFailure, "%v", err)
460		}
461		base = b
462	}
463	patch, err := gitutil.Diff(dir, base, head, 4<<20)
464	if err != nil {
465		return c.fail(protocol.ExitFailure, "%v", err)
466	}
467	fmt.Fprint(c.Stdout, patch)
468	return protocol.ExitOK
469}
470
471func runMRComment(c *Ctx, args []string) int {
472	var rest []string
473	var message, file string
474	for i := 0; i < len(args); i++ {
475		switch args[i] {
476		case "--message", "--file":
477			if i+1 >= len(args) {
478				return c.fail(protocol.ExitUsage, "%s requires a value", args[i])
479			}
480			if args[i] == "--message" {
481				message = args[i+1]
482			} else {
483				file = args[i+1]
484			}
485			i++
486		default:
487			rest = append(rest, args[i])
488		}
489	}
490	repo, mr, code := mrRef(c, rest, policy.CanRead)
491	if code >= 0 {
492		return code
493	}
494	if code := refuseArchived(c, repo); code >= 0 {
495		return code
496	}
497	body, err := bodyFrom(c, message, file)
498	if err != nil {
499		return c.fail(protocol.ExitUsage, "%v", err)
500	}
501	if strings.TrimSpace(body) == "" {
502		return c.fail(protocol.ExitUsage, "empty comment; use --message or --file -")
503	}
504	if err := c.Store.AddMRComment(mr.ID, c.User.ID, body); err != nil {
505		return c.fail(protocol.ExitFailure, "%v", err)
506	}
507	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
508		notifyUsers(c, parts, mrSubject(repo, mr.Number, mr.Title),
509			notifyBody(c, fmt.Sprintf("commented on !%d", mr.Number), body, fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)))
510	}
511	return c.emit(map[string]any{"number": mr.Number}, func(w io.Writer) {
512		fmt.Fprintf(w, "commented on %s!%d\n", repo.Path(), mr.Number)
513	})
514}
515
516func runMRReview(c *Ctx, args []string) int {
517	verdict := ""
518	var rest []string
519	for _, a := range args {
520		switch a {
521		case "--approve":
522			verdict = "approve"
523		case "--request-changes":
524			verdict = "request_changes"
525		case "--comment":
526			verdict = "comment"
527		default:
528			rest = append(rest, a)
529		}
530	}
531	if verdict == "" {
532		return c.fail(protocol.ExitUsage, "usage: mr review <owner/name> <n> --approve|--request-changes|--comment")
533	}
534	repo, mr, code := mrRef(c, rest, policy.CanRead)
535	if code >= 0 {
536		return code
537	}
538	if code := refuseArchived(c, repo); code >= 0 {
539		return code
540	}
541	if mr.State != "open" {
542		return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
543	}
544	if err := c.Store.AddMRReview(mr.ID, c.User.ID, verdict, mr.HeadSHA); err != nil {
545		return c.fail(protocol.ExitFailure, "%v", err)
546	}
547	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
548		notifyUsers(c, parts, mrSubject(repo, mr.Number, mr.Title),
549			notifyBody(c, fmt.Sprintf("reviewed !%d: %s", mr.Number, verdict), "", fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)))
550	}
551	return c.emit(map[string]any{"number": mr.Number, "verdict": verdict}, func(w io.Writer) {
552		fmt.Fprintf(w, "reviewed %s!%d: %s\n", repo.Path(), mr.Number, verdict)
553	})
554}
555
556func runMRMerge(c *Ctx, args []string) int {
557	strategy := ""
558	var rest []string
559	for i := 0; i < len(args); i++ {
560		if args[i] == "--strategy" {
561			if i+1 >= len(args) {
562				return c.fail(protocol.ExitUsage, "--strategy requires ff|merge|squash|rebase")
563			}
564			strategy = args[i+1]
565			i++
566			continue
567		}
568		rest = append(rest, args[i])
569	}
570	valid := map[string]bool{"": true, "ff": true, "merge": true, "squash": true, "rebase": true}
571	if !valid[strategy] {
572		return c.fail(protocol.ExitUsage, "--strategy must be ff, merge, squash, or rebase")
573	}
574	repo, mr, code := mrRef(c, rest, policy.CanWrite)
575	if code >= 0 {
576		return code
577	}
578	if code := refuseArchived(c, repo); code >= 0 {
579		return code
580	}
581	if mr.State != "open" && mr.State != "source_gone" {
582		return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
583	}
584
585	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
586	targetRef := "refs/heads/" + mr.TargetRef
587	targetSHA, err := gitutil.ResolveRef(dir, targetRef)
588	if err != nil {
589		return c.fail(protocol.ExitFailure, "target branch %s: %v", mr.TargetRef, err)
590	}
591	headSHA, err := gitutil.ResolveRef(dir, mrHeadRef(mr.Number))
592	if err != nil {
593		return c.fail(protocol.ExitFailure, "MR head ref: %v", err)
594	}
595
596	// Check gate: with require_checks, the MR head must carry statuses
597	// and every one of them must be green.
598	if repo.Settings.RequireChecks {
599		statuses, err := c.Store.ListCommitStatuses(repo.ID, headSHA)
600		if err != nil {
601			return c.fail(protocol.ExitFailure, "%v", err)
602		}
603		switch store.CombinedStatus(statuses) {
604		case "success":
605		case "":
606			return c.fail(protocol.ExitDenied,
607				"%s requires green checks and none were reported on %.10s", repo.Path(), headSHA)
608		default:
609			var bad []string
610			for _, st := range statuses {
611				if st.State != "success" {
612					bad = append(bad, st.Context+"="+st.State)
613				}
614			}
615			return c.fail(protocol.ExitDenied,
616				"%s requires green checks; %.10s has %s", repo.Path(), headSHA, strings.Join(bad, ", "))
617		}
618	}
619
620	// Review gates: approvals, CODEOWNERS, resolved threads.
621	if code := c.reviewGates(repo, mr, dir, targetSHA, headSHA); code >= 0 {
622		return code
623	}
624
625	upToDate, err := gitutil.IsAncestor(dir, headSHA, targetSHA)
626	if err != nil {
627		return c.fail(protocol.ExitFailure, "%v", err)
628	}
629	if upToDate {
630		return c.fail(protocol.ExitUsage, "target already contains the MR head")
631	}
632	ffPossible, err := gitutil.IsAncestor(dir, targetSHA, headSHA)
633	if err != nil {
634		return c.fail(protocol.ExitFailure, "%v", err)
635	}
636
637	// Signature policy matrix: with require_signed_commits, only
638	// fast-forward is allowed — squash, rebase-replay, and merge commits
639	// are all server-created and unsigned, violating the branch's own
640	// policy — and every landed commit must be verified. An explicit
641	// rebase when fast-forward is already possible IS a fast-forward
642	// (nothing is rewritten), so it stays legal.
643	if repo.Settings.RequireSignedCommits {
644		if strategy == "merge" || strategy == "squash" || !ffPossible {
645			return c.fail(protocol.ExitDenied,
646				"%s requires signed commits, so only fast-forward merges are allowed; rebase %s onto %s locally, re-push, and merge again",
647				repo.Path(), mr.SourceRef, mr.TargetRef)
648		}
649		strategy = "ff"
650		commits, err := gitutil.RevListRange(dir, targetSHA, headSHA)
651		if err != nil {
652			return c.fail(protocol.ExitFailure, "%v", err)
653		}
654		for _, sha := range commits {
655			raw, err := gitutil.ReadCommit(dir, sha)
656			if err != nil {
657				return c.fail(protocol.ExitFailure, "%v", err)
658			}
659			parsed, err := sigParse(raw)
660			if err != nil {
661				return c.fail(protocol.ExitFailure, "%v", err)
662			}
663			res, err := VerifyCommitCached(c.Store, repo, parsed, sha)
664			if err != nil {
665				return c.fail(protocol.ExitFailure, "%v", err)
666			}
667			if res.State != "verified" {
668				return c.fail(protocol.ExitDenied,
669					"%s requires signed commits: %.10s is %s", repo.Path(), sha, res.State)
670			}
671		}
672	}
673	if strategy == "" {
674		if ffPossible {
675			strategy = "ff"
676		} else {
677			strategy = "merge"
678		}
679	}
680	if strategy == "rebase" && ffPossible {
681		// Nothing to rewrite: a rebase onto an ancestor is a fast-forward,
682		// and taking it keeps the original commits and their signatures.
683		strategy = "ff"
684	}
685
686	// Every server-created commit needs the merger's verified identity.
687	mergerEmail := ""
688	if strategy != "ff" {
689		email, err := c.Store.PrimaryVerifiedEmail(c.User.ID)
690		if err != nil {
691			return c.fail(protocol.ExitFailure, "%v", err)
692		}
693		if email == "" {
694			return c.fail(protocol.ExitDenied,
695				"%s merges create commits carrying your identity: verify a primary email first (or use a fast-forward merge)", strategy)
696		}
697		mergerEmail = email
698	}
699
700	var newSHA string
701	switch strategy {
702	case "ff":
703		if !ffPossible {
704			return c.fail(protocol.ExitUsage,
705				"fast-forward not possible: %s has diverged from the MR head; use --strategy merge or rebase and re-push", mr.TargetRef)
706		}
707		newSHA = headSHA
708
709	case "merge":
710		tree, conflict, err := gitutil.MergeTree(dir, targetSHA, headSHA)
711		if err != nil {
712			return c.fail(protocol.ExitFailure, "%v", err)
713		}
714		if conflict {
715			return c.fail(protocol.ExitUsage,
716				"merge conflicts between %s and the MR head; resolve locally and re-push", mr.TargetRef)
717		}
718		msg := fmt.Sprintf("Merge request !%d: %s\n\nMerged %s into %s", mr.Number, mr.Title, mr.SourceRef, mr.TargetRef)
719		newSHA, err = gitutil.CommitTree(dir, tree, []string{targetSHA, headSHA}, c.User.Username, mergerEmail, msg)
720		if err != nil {
721			return c.fail(protocol.ExitFailure, "%v", err)
722		}
723
724	case "squash":
725		// One new commit with the merged tree. Authorship credit goes to
726		// the MR author (their verified identity when they have one); the
727		// committer is the merger.
728		tree := ""
729		if ffPossible {
730			t, err := gitutil.ResolveTree(dir, headSHA)
731			if err != nil {
732				return c.fail(protocol.ExitFailure, "%v", err)
733			}
734			tree = t
735		} else {
736			t, conflict, err := gitutil.MergeTree(dir, targetSHA, headSHA)
737			if err != nil {
738				return c.fail(protocol.ExitFailure, "%v", err)
739			}
740			if conflict {
741				return c.fail(protocol.ExitUsage,
742					"merge conflicts between %s and the MR head; resolve locally and re-push", mr.TargetRef)
743			}
744			tree = t
745		}
746		authorName, authorEmail := c.User.Username, mergerEmail
747		if author, err := c.Store.UserByUsername(mr.Author); err == nil {
748			if ae, err := c.Store.PrimaryVerifiedEmail(author.ID); err == nil && ae != "" {
749				authorName, authorEmail = author.Username, ae
750			}
751		}
752		msg := fmt.Sprintf("%s (!%d)", mr.Title, mr.Number)
753		if mr.Body != "" {
754			msg += "\n\n" + mr.Body
755		}
756		var err error
757		newSHA, err = gitutil.CommitTreeIdent(dir, tree, []string{targetSHA},
758			authorName, authorEmail, "", c.User.Username, mergerEmail, msg)
759		if err != nil {
760			return c.fail(protocol.ExitFailure, "%v", err)
761		}
762
763	case "rebase":
764		commits, err := gitutil.RevListRange(dir, targetSHA, headSHA)
765		if err != nil {
766			return c.fail(protocol.ExitFailure, "%v", err)
767		}
768		// Oldest first.
769		for i, j := 0, len(commits)-1; i < j; i, j = i+1, j-1 {
770			commits[i], commits[j] = commits[j], commits[i]
771		}
772		onto := targetSHA
773		for _, sha := range commits {
774			parents, err := gitutil.CommitParents(dir, sha)
775			if err != nil {
776				return c.fail(protocol.ExitFailure, "%v", err)
777			}
778			if len(parents) > 1 {
779				return c.fail(protocol.ExitUsage,
780					"the MR contains merge commit %.10s; a rebase merge needs linear history — use --strategy merge or squash", sha)
781			}
782			base := onto // root commit: replay against the new tip itself
783			if len(parents) == 1 {
784				base = parents[0]
785			}
786			tree, conflict, err := gitutil.MergeTreeOnto(dir, base, onto, sha)
787			if err != nil {
788				return c.fail(protocol.ExitFailure, "%v", err)
789			}
790			if conflict {
791				return c.fail(protocol.ExitUsage,
792					"commit %.10s does not apply cleanly onto %s; rebase locally and re-push", sha, mr.TargetRef)
793			}
794			aName, aEmail, aDate, err := gitutil.AuthorIdent(dir, sha)
795			if err != nil {
796				return c.fail(protocol.ExitFailure, "%v", err)
797			}
798			msg, err := gitutil.CommitMessage(dir, sha)
799			if err != nil {
800				return c.fail(protocol.ExitFailure, "%v", err)
801			}
802			onto, err = gitutil.CommitTreeIdent(dir, tree, []string{onto},
803				aName, aEmail, aDate, c.User.Username, mergerEmail, msg)
804			if err != nil {
805				return c.fail(protocol.ExitFailure, "%v", err)
806			}
807		}
808		newSHA = onto
809	}
810
811	// CAS so a concurrent push between our read and this write fails the
812	// merge instead of silently discarding the push.
813	if err := gitutil.UpdateRefCAS(dir, targetRef, newSHA, targetSHA); err != nil {
814		return c.fail(protocol.ExitFailure, "target branch moved during merge; retry: %v", err)
815	}
816	if err := c.Store.MarkMerged(mr.ID, targetSHA); err != nil {
817		return c.fail(protocol.ExitFailure, "%v", err)
818	}
819	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d,"sha":%q}`, mr.Number, newSHA))
820	// Merges bypass receive-pack, so the commit-message issue actions
821	// (closes #N, references) run here for the newly landed commits.
822	if mr.TargetRef == repo.DefaultBranch {
823		ProcessCommitMessages(c.Store, dir, repo, c.User.ID, targetSHA, newSHA)
824	}
825	c.Store.MarkMirrorsDirty(repo.ID, "push")
826	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
827		notifyUsers(c, parts, mrSubject(repo, mr.Number, mr.Title),
828			notifyBody(c, fmt.Sprintf("merged !%d into %s (%s)", mr.Number, mr.TargetRef, strategy), "", fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)))
829	}
830	return c.emit(map[string]any{"number": mr.Number, "strategy": strategy, "sha": newSHA}, func(w io.Writer) {
831		fmt.Fprintf(w, "merged %s!%d into %s (%s) at %.10s\n", repo.Path(), mr.Number, mr.TargetRef, strategy, newSHA)
832	})
833}
834
835// reviewGates enforces require_approvals (fresh, non-author, latest review
836// per reviewer; a fresh request-changes blocks), CODEOWNERS coverage, and
837// require_resolved. Returns -1 to proceed.
838func (c *Ctx) reviewGates(repo store.Repo, mr store.MR, dir, targetSHA, headSHA string) int {
839	set := repo.Settings
840	if set.RequireApprovals == 0 && !set.RequireResolved {
841		return -1
842	}
843
844	if set.RequireApprovals > 0 {
845		reviews, err := c.Store.ListMRReviews(mr.ID)
846		if err != nil {
847			return c.fail(protocol.ExitFailure, "%v", err)
848		}
849		// Latest fresh review per reviewer decides their stance.
850		latest := map[string]string{}
851		for _, r := range reviews {
852			if r.Stale || r.Reviewer == mr.Author {
853				continue
854			}
855			latest[r.Reviewer] = r.Verdict
856		}
857		var approvers []string
858		var blockers []string
859		for who, verdict := range latest {
860			switch verdict {
861			case "approve":
862				approvers = append(approvers, who)
863			case "request_changes":
864				blockers = append(blockers, who)
865			}
866		}
867		if len(blockers) > 0 {
868			slices.Sort(blockers)
869			return c.fail(protocol.ExitDenied,
870				"%s requested changes on !%d; resolve their review before merging", strings.Join(blockers, ", "), mr.Number)
871		}
872		if len(approvers) < set.RequireApprovals {
873			return c.fail(protocol.ExitDenied,
874				"%s requires %d fresh approval(s); !%d has %d", repo.Path(), set.RequireApprovals, mr.Number, len(approvers))
875		}
876
877		// CODEOWNERS: every owned changed file needs an approval from one
878		// of its owners.
879		content, err := gitutil.ReadBlob(dir, "refs/heads/"+mr.TargetRef, "CODEOWNERS", 1<<20)
880		if err != nil {
881			content, err = gitutil.ReadBlob(dir, "refs/heads/"+mr.TargetRef, ".gitbay/CODEOWNERS", 1<<20)
882		}
883		if err == nil && len(content) > 0 {
884			rules := policy.ParseCodeowners(string(content))
885			base, err := gitutil.MergeBase(dir, targetSHA, headSHA)
886			if err != nil {
887				return c.fail(protocol.ExitFailure, "%v", err)
888			}
889			files, err := gitutil.DiffFiles(dir, base, headSHA)
890			if err != nil {
891				return c.fail(protocol.ExitFailure, "%v", err)
892			}
893			approved := map[string]bool{}
894			for _, a := range approvers {
895				approved[a] = true
896			}
897			missing := map[string][]string{} // owner-set key -> example paths
898			for _, f := range files {
899				owners := policy.OwnersFor(rules, f)
900				if owners == nil {
901					continue
902				}
903				ok := false
904				for _, o := range owners {
905					if approved[o] {
906						ok = true
907						break
908					}
909				}
910				if !ok {
911					key := strings.Join(owners, ",")
912					if len(missing[key]) < 3 {
913						missing[key] = append(missing[key], f)
914					}
915				}
916			}
917			if len(missing) > 0 {
918				var parts []string
919				for owners, paths := range missing {
920					parts = append(parts, fmt.Sprintf("%s (owned by %s)", strings.Join(paths, ", "), owners))
921				}
922				slices.Sort(parts)
923				return c.fail(protocol.ExitDenied,
924					"CODEOWNERS approval missing for: %s", strings.Join(parts, "; "))
925			}
926		}
927	}
928
929	if set.RequireResolved {
930		n, err := c.Store.UnresolvedThreadCount(mr.ID)
931		if err != nil {
932			return c.fail(protocol.ExitFailure, "%v", err)
933		}
934		if n > 0 {
935			return c.fail(protocol.ExitDenied,
936				"%s requires review threads resolved; !%d has %d open (mr threads %s %d)", repo.Path(), mr.Number, n, repo.Path(), mr.Number)
937		}
938	}
939	return -1
940}
941
942func runMRClose(c *Ctx, args []string) int {
943	repo, mr, code := mrRef(c, args, policy.CanRead)
944	if code >= 0 {
945		return code
946	}
947	if code := refuseArchived(c, repo); code >= 0 {
948		return code
949	}
950	if len(args) != 2 {
951		return c.fail(protocol.ExitUsage, "usage: mr close <owner/name> <n>")
952	}
953	grant, err := c.Store.AccessRole(repo.ID, c.User.ID)
954	if err != nil {
955		return c.fail(protocol.ExitFailure, "%v", err)
956	}
957	if mr.Author != c.User.Username && !policy.CanWrite(c.User, repo, grant) {
958		return c.fail(protocol.ExitDenied, "only the author or users with write access can close this MR")
959	}
960	if mr.State == "merged" || mr.State == "closed" {
961		return c.fail(protocol.ExitUsage, "MR !%d is already %s", mr.Number, mr.State)
962	}
963	if err := c.Store.SetMRState(mr.ID, "closed"); err != nil {
964		return c.fail(protocol.ExitFailure, "%v", err)
965	}
966	return c.emit(map[string]any{"number": mr.Number, "state": "closed"}, func(w io.Writer) {
967		fmt.Fprintf(w, "closed %s!%d\n", repo.Path(), mr.Number)
968	})
969}