internal/control/mr.go

26b59e4e1845ca161d394403e2ef262040feebab
gitbay/internal/control/mr.go history · blame · raw

948 lines · 31723 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 target == "" {
245		target = repo.DefaultBranch
246	}
247
248	// Source is "branch" (same repo) or "owner/name:branch" (a fork).
249	srcRepo := repo
250	srcBranch := source
251	if sp, br, ok := strings.Cut(source, ":"); ok {
252		srcBranch = br
253		var scode int
254		srcRepo, scode = resolveRepo(c, sp, policy.CanRead)
255		if scode >= 0 {
256			return scode
257		}
258		if srcRepo.ForkOf != repo.ID && srcRepo.ID != repo.ID {
259			return c.fail(protocol.ExitUsage, "%s is not a fork of %s", srcRepo.Path(), repo.Path())
260		}
261	}
262	srcDir := RepoDir(c.Cfg.Server.Root, srcRepo.OwnerName, srcRepo.Name)
263	headSHA, err := gitutil.ResolveRef(srcDir, "refs/heads/"+srcBranch)
264	if err != nil {
265		return c.fail(protocol.ExitNotFound, "branch %s not found in %s", srcBranch, srcRepo.Path())
266	}
267	b, err := bodyFrom(c, body, file)
268	if err != nil {
269		return c.fail(protocol.ExitUsage, "%v", err)
270	}
271	n, err := c.Store.CreateMR(repo.ID, c.User.ID, srcRepo.ID, srcBranch, target, title, b, headSHA)
272	if err != nil {
273		return c.fail(protocol.ExitFailure, "%v", err)
274	}
275	// Fetch the head into the target so the target owns the objects.
276	dstDir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
277	if err := gitutil.FetchInto(dstDir, srcDir, headSHA, mrHeadRef(n)); err != nil {
278		return c.fail(protocol.ExitFailure, "recording MR head: %v", err)
279	}
280	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.created", fmt.Sprintf(`{"number":%d}`, n))
281	if targets, err := c.Store.RepoNotifyTargets(repo); err == nil {
282		notifyUsers(c, targets, mrSubject(repo, n, title),
283			notifyBody(c, fmt.Sprintf("opened merge request !%d (%s -> %s)", n, source, target), b, fmt.Sprintf("%s/mrs/%d", repo.Path(), n)))
284	}
285	return c.emit(map[string]any{"number": n, "head_sha": headSHA}, func(w io.Writer) {
286		fmt.Fprintf(w, "created %s!%d (%s -> %s)\n", repo.Path(), n, source, target)
287	})
288}
289
290type mrOut struct {
291	Number    int64  `json:"number"`
292	Title     string `json:"title"`
293	State     string `json:"state"`
294	Author    string `json:"author"`
295	Source    string `json:"source"` // owner/name:branch, or branch, "" if gone
296	TargetRef string `json:"target_ref"`
297	HeadSHA   string `json:"head_sha"`
298	Body      string `json:"body,omitempty"`
299	CreatedAt string `json:"created_at"`
300}
301
302func mrToOut(repo store.Repo, m store.MR, withBody bool) mrOut {
303	src := ""
304	if m.SourcePath != "" {
305		if m.SourceRepoID == repo.ID {
306			src = m.SourceRef
307		} else {
308			src = m.SourcePath + ":" + m.SourceRef
309		}
310	}
311	o := mrOut{Number: m.Number, Title: m.Title, State: m.State, Author: m.Author,
312		Source: src, TargetRef: m.TargetRef, HeadSHA: m.HeadSHA, CreatedAt: m.CreatedAt}
313	if withBody {
314		o.Body = m.Body
315	}
316	return o
317}
318
319func runMRList(c *Ctx, args []string) int {
320	state := "open"
321	var path string
322	for i := 0; i < len(args); i++ {
323		switch args[i] {
324		case "--state":
325			if i+1 >= len(args) {
326				return c.fail(protocol.ExitUsage, "--state requires a value")
327			}
328			state = args[i+1]
329			i++
330		default:
331			if path != "" {
332				return c.fail(protocol.ExitUsage, "unexpected argument %q", args[i])
333			}
334			path = args[i]
335		}
336	}
337	valid := map[string]bool{"open": true, "merged": true, "closed": true, "source_gone": true, "all": true}
338	if path == "" || !valid[state] {
339		return c.fail(protocol.ExitUsage, "usage: mr list <owner/name> [--state open|merged|closed|source_gone|all]")
340	}
341	repo, code := resolveRepo(c, path, policy.CanRead)
342	if code >= 0 {
343		return code
344	}
345	mrs, err := c.Store.ListMRs(repo.ID, state)
346	if err != nil {
347		return c.fail(protocol.ExitFailure, "%v", err)
348	}
349	var ds []mrOut
350	for _, m := range mrs {
351		ds = append(ds, mrToOut(repo, m, false))
352	}
353	return c.emit(ds, func(w io.Writer) {
354		for _, d := range ds {
355			fmt.Fprintf(w, "!%d\t%s\t%s\t%s -> %s\n", d.Number, d.State, d.Title, d.Source, d.TargetRef)
356		}
357	})
358}
359
360func runMRShow(c *Ctx, args []string) int {
361	repo, mr, code := mrRef(c, args, policy.CanRead)
362	if code >= 0 {
363		return code
364	}
365	if len(args) != 2 {
366		return c.fail(protocol.ExitUsage, "usage: mr show <owner/name> <n>")
367	}
368	comments, err := c.Store.ListMRComments(mr.ID)
369	if err != nil {
370		return c.fail(protocol.ExitFailure, "%v", err)
371	}
372	reviews, err := c.Store.ListMRReviews(mr.ID)
373	if err != nil {
374		return c.fail(protocol.ExitFailure, "%v", err)
375	}
376	statuses, err := c.Store.ListCommitStatuses(repo.ID, mr.HeadSHA)
377	if err != nil {
378		return c.fail(protocol.ExitFailure, "%v", err)
379	}
380	unresolved, err := c.Store.UnresolvedThreadCount(mr.ID)
381	if err != nil {
382		return c.fail(protocol.ExitFailure, "%v", err)
383	}
384	type commentOut struct {
385		Author    string `json:"author"`
386		Body      string `json:"body"`
387		CreatedAt string `json:"created_at"`
388	}
389	type reviewOut struct {
390		Reviewer string `json:"reviewer"`
391		Verdict  string `json:"verdict"`
392		Stale    bool   `json:"stale"`
393	}
394	type checkOut struct {
395		Context string `json:"context"`
396		State   string `json:"state"`
397		URL     string `json:"url,omitempty"`
398	}
399	var checks []checkOut
400	for _, st := range statuses {
401		checks = append(checks, checkOut{st.Context, st.State, st.TargetURL})
402	}
403	var cs []commentOut
404	for _, cm := range comments {
405		cs = append(cs, commentOut{cm.Author, cm.Body, cm.CreatedAt})
406	}
407	var rs []reviewOut
408	for _, r := range reviews {
409		rs = append(rs, reviewOut{r.Reviewer, r.Verdict, r.Stale})
410	}
411	d := struct {
412		mrOut
413		Checks            []checkOut   `json:"checks,omitempty"`
414		Combined          string       `json:"checks_combined,omitempty"`
415		UnresolvedThreads int          `json:"unresolved_threads,omitempty"`
416		Comments          []commentOut `json:"comments,omitempty"`
417		Reviews           []reviewOut  `json:"reviews,omitempty"`
418	}{mrToOut(repo, mr, true), checks, store.CombinedStatus(statuses), unresolved, cs, rs}
419	return c.emit(d, func(w io.Writer) {
420		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)
421		if d.Body != "" {
422			fmt.Fprintf(w, "\n%s\n", d.Body)
423		}
424		for _, x := range checks {
425			fmt.Fprintf(w, "check: %s %s\n", x.Context, x.State)
426		}
427		if d.UnresolvedThreads > 0 {
428			fmt.Fprintf(w, "unresolved threads: %d\n", d.UnresolvedThreads)
429		}
430		for _, r := range rs {
431			stale := ""
432			if r.Stale {
433				stale = " (stale)"
434			}
435			fmt.Fprintf(w, "review: %s %s%s\n", r.Reviewer, r.Verdict, stale)
436		}
437		for _, cm := range cs {
438			fmt.Fprintf(w, "\n--- %s at %s\n%s\n", cm.Author, cm.CreatedAt, cm.Body)
439		}
440	})
441}
442
443func runMRDiff(c *Ctx, args []string) int {
444	repo, mr, code := mrRef(c, args, policy.CanRead)
445	if code >= 0 {
446		return code
447	}
448	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
449	head := mrHeadRef(mr.Number)
450	// After a merge (especially fast-forward) the live merge-base equals
451	// the head and the diff would vanish; use the recorded base instead.
452	base := mr.MergedBase
453	if base == "" {
454		b, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, head)
455		if err != nil {
456			return c.fail(protocol.ExitFailure, "%v", err)
457		}
458		base = b
459	}
460	patch, err := gitutil.Diff(dir, base, head, 4<<20)
461	if err != nil {
462		return c.fail(protocol.ExitFailure, "%v", err)
463	}
464	fmt.Fprint(c.Stdout, patch)
465	return protocol.ExitOK
466}
467
468func runMRComment(c *Ctx, args []string) int {
469	var rest []string
470	var message, file string
471	for i := 0; i < len(args); i++ {
472		switch args[i] {
473		case "--message", "--file":
474			if i+1 >= len(args) {
475				return c.fail(protocol.ExitUsage, "%s requires a value", args[i])
476			}
477			if args[i] == "--message" {
478				message = args[i+1]
479			} else {
480				file = args[i+1]
481			}
482			i++
483		default:
484			rest = append(rest, args[i])
485		}
486	}
487	repo, mr, code := mrRef(c, rest, policy.CanRead)
488	if code >= 0 {
489		return code
490	}
491	body, err := bodyFrom(c, message, file)
492	if err != nil {
493		return c.fail(protocol.ExitUsage, "%v", err)
494	}
495	if strings.TrimSpace(body) == "" {
496		return c.fail(protocol.ExitUsage, "empty comment; use --message or --file -")
497	}
498	if err := c.Store.AddMRComment(mr.ID, c.User.ID, body); err != nil {
499		return c.fail(protocol.ExitFailure, "%v", err)
500	}
501	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
502		notifyUsers(c, parts, mrSubject(repo, mr.Number, mr.Title),
503			notifyBody(c, fmt.Sprintf("commented on !%d", mr.Number), body, fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)))
504	}
505	return c.emit(map[string]any{"number": mr.Number}, func(w io.Writer) {
506		fmt.Fprintf(w, "commented on %s!%d\n", repo.Path(), mr.Number)
507	})
508}
509
510func runMRReview(c *Ctx, args []string) int {
511	verdict := ""
512	var rest []string
513	for _, a := range args {
514		switch a {
515		case "--approve":
516			verdict = "approve"
517		case "--request-changes":
518			verdict = "request_changes"
519		case "--comment":
520			verdict = "comment"
521		default:
522			rest = append(rest, a)
523		}
524	}
525	if verdict == "" {
526		return c.fail(protocol.ExitUsage, "usage: mr review <owner/name> <n> --approve|--request-changes|--comment")
527	}
528	repo, mr, code := mrRef(c, rest, policy.CanRead)
529	if code >= 0 {
530		return code
531	}
532	if mr.State != "open" {
533		return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
534	}
535	if err := c.Store.AddMRReview(mr.ID, c.User.ID, verdict, mr.HeadSHA); err != nil {
536		return c.fail(protocol.ExitFailure, "%v", err)
537	}
538	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
539		notifyUsers(c, parts, mrSubject(repo, mr.Number, mr.Title),
540			notifyBody(c, fmt.Sprintf("reviewed !%d: %s", mr.Number, verdict), "", fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)))
541	}
542	return c.emit(map[string]any{"number": mr.Number, "verdict": verdict}, func(w io.Writer) {
543		fmt.Fprintf(w, "reviewed %s!%d: %s\n", repo.Path(), mr.Number, verdict)
544	})
545}
546
547func runMRMerge(c *Ctx, args []string) int {
548	strategy := ""
549	var rest []string
550	for i := 0; i < len(args); i++ {
551		if args[i] == "--strategy" {
552			if i+1 >= len(args) {
553				return c.fail(protocol.ExitUsage, "--strategy requires ff|merge|squash|rebase")
554			}
555			strategy = args[i+1]
556			i++
557			continue
558		}
559		rest = append(rest, args[i])
560	}
561	valid := map[string]bool{"": true, "ff": true, "merge": true, "squash": true, "rebase": true}
562	if !valid[strategy] {
563		return c.fail(protocol.ExitUsage, "--strategy must be ff, merge, squash, or rebase")
564	}
565	repo, mr, code := mrRef(c, rest, policy.CanWrite)
566	if code >= 0 {
567		return code
568	}
569	if mr.State != "open" && mr.State != "source_gone" {
570		return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
571	}
572
573	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
574	targetRef := "refs/heads/" + mr.TargetRef
575	targetSHA, err := gitutil.ResolveRef(dir, targetRef)
576	if err != nil {
577		return c.fail(protocol.ExitFailure, "target branch %s: %v", mr.TargetRef, err)
578	}
579	headSHA, err := gitutil.ResolveRef(dir, mrHeadRef(mr.Number))
580	if err != nil {
581		return c.fail(protocol.ExitFailure, "MR head ref: %v", err)
582	}
583
584	// Check gate: with require_checks, the MR head must carry statuses
585	// and every one of them must be green.
586	if repo.Settings.RequireChecks {
587		statuses, err := c.Store.ListCommitStatuses(repo.ID, headSHA)
588		if err != nil {
589			return c.fail(protocol.ExitFailure, "%v", err)
590		}
591		switch store.CombinedStatus(statuses) {
592		case "success":
593		case "":
594			return c.fail(protocol.ExitDenied,
595				"%s requires green checks and none were reported on %.10s", repo.Path(), headSHA)
596		default:
597			var bad []string
598			for _, st := range statuses {
599				if st.State != "success" {
600					bad = append(bad, st.Context+"="+st.State)
601				}
602			}
603			return c.fail(protocol.ExitDenied,
604				"%s requires green checks; %.10s has %s", repo.Path(), headSHA, strings.Join(bad, ", "))
605		}
606	}
607
608	// Review gates: approvals, CODEOWNERS, resolved threads.
609	if code := c.reviewGates(repo, mr, dir, targetSHA, headSHA); code >= 0 {
610		return code
611	}
612
613	upToDate, err := gitutil.IsAncestor(dir, headSHA, targetSHA)
614	if err != nil {
615		return c.fail(protocol.ExitFailure, "%v", err)
616	}
617	if upToDate {
618		return c.fail(protocol.ExitUsage, "target already contains the MR head")
619	}
620	ffPossible, err := gitutil.IsAncestor(dir, targetSHA, headSHA)
621	if err != nil {
622		return c.fail(protocol.ExitFailure, "%v", err)
623	}
624
625	// Signature policy matrix: with require_signed_commits, only
626	// fast-forward is allowed — squash, rebase-replay, and merge commits
627	// are all server-created and unsigned, violating the branch's own
628	// policy — and every landed commit must be verified. An explicit
629	// rebase when fast-forward is already possible IS a fast-forward
630	// (nothing is rewritten), so it stays legal.
631	if repo.Settings.RequireSignedCommits {
632		if strategy == "merge" || strategy == "squash" || !ffPossible {
633			return c.fail(protocol.ExitDenied,
634				"%s requires signed commits, so only fast-forward merges are allowed; rebase %s onto %s locally, re-push, and merge again",
635				repo.Path(), mr.SourceRef, mr.TargetRef)
636		}
637		strategy = "ff"
638		commits, err := gitutil.RevListRange(dir, targetSHA, headSHA)
639		if err != nil {
640			return c.fail(protocol.ExitFailure, "%v", err)
641		}
642		for _, sha := range commits {
643			raw, err := gitutil.ReadCommit(dir, sha)
644			if err != nil {
645				return c.fail(protocol.ExitFailure, "%v", err)
646			}
647			parsed, err := sigParse(raw)
648			if err != nil {
649				return c.fail(protocol.ExitFailure, "%v", err)
650			}
651			res, err := VerifyCommitCached(c.Store, repo, parsed, sha)
652			if err != nil {
653				return c.fail(protocol.ExitFailure, "%v", err)
654			}
655			if res.State != "verified" {
656				return c.fail(protocol.ExitDenied,
657					"%s requires signed commits: %.10s is %s", repo.Path(), sha, res.State)
658			}
659		}
660	}
661	if strategy == "" {
662		if ffPossible {
663			strategy = "ff"
664		} else {
665			strategy = "merge"
666		}
667	}
668	if strategy == "rebase" && ffPossible {
669		// Nothing to rewrite: a rebase onto an ancestor is a fast-forward,
670		// and taking it keeps the original commits and their signatures.
671		strategy = "ff"
672	}
673
674	// Every server-created commit needs the merger's verified identity.
675	mergerEmail := ""
676	if strategy != "ff" {
677		email, err := c.Store.PrimaryVerifiedEmail(c.User.ID)
678		if err != nil {
679			return c.fail(protocol.ExitFailure, "%v", err)
680		}
681		if email == "" {
682			return c.fail(protocol.ExitDenied,
683				"%s merges create commits carrying your identity: verify a primary email first (or use a fast-forward merge)", strategy)
684		}
685		mergerEmail = email
686	}
687
688	var newSHA string
689	switch strategy {
690	case "ff":
691		if !ffPossible {
692			return c.fail(protocol.ExitUsage,
693				"fast-forward not possible: %s has diverged from the MR head; use --strategy merge or rebase and re-push", mr.TargetRef)
694		}
695		newSHA = headSHA
696
697	case "merge":
698		tree, conflict, err := gitutil.MergeTree(dir, targetSHA, headSHA)
699		if err != nil {
700			return c.fail(protocol.ExitFailure, "%v", err)
701		}
702		if conflict {
703			return c.fail(protocol.ExitUsage,
704				"merge conflicts between %s and the MR head; resolve locally and re-push", mr.TargetRef)
705		}
706		msg := fmt.Sprintf("Merge request !%d: %s\n\nMerged %s into %s", mr.Number, mr.Title, mr.SourceRef, mr.TargetRef)
707		newSHA, err = gitutil.CommitTree(dir, tree, []string{targetSHA, headSHA}, c.User.Username, mergerEmail, msg)
708		if err != nil {
709			return c.fail(protocol.ExitFailure, "%v", err)
710		}
711
712	case "squash":
713		// One new commit with the merged tree. Authorship credit goes to
714		// the MR author (their verified identity when they have one); the
715		// committer is the merger.
716		tree := ""
717		if ffPossible {
718			t, err := gitutil.ResolveTree(dir, headSHA)
719			if err != nil {
720				return c.fail(protocol.ExitFailure, "%v", err)
721			}
722			tree = t
723		} else {
724			t, conflict, err := gitutil.MergeTree(dir, targetSHA, headSHA)
725			if err != nil {
726				return c.fail(protocol.ExitFailure, "%v", err)
727			}
728			if conflict {
729				return c.fail(protocol.ExitUsage,
730					"merge conflicts between %s and the MR head; resolve locally and re-push", mr.TargetRef)
731			}
732			tree = t
733		}
734		authorName, authorEmail := c.User.Username, mergerEmail
735		if author, err := c.Store.UserByUsername(mr.Author); err == nil {
736			if ae, err := c.Store.PrimaryVerifiedEmail(author.ID); err == nil && ae != "" {
737				authorName, authorEmail = author.Username, ae
738			}
739		}
740		msg := fmt.Sprintf("%s (!%d)", mr.Title, mr.Number)
741		if mr.Body != "" {
742			msg += "\n\n" + mr.Body
743		}
744		var err error
745		newSHA, err = gitutil.CommitTreeIdent(dir, tree, []string{targetSHA},
746			authorName, authorEmail, "", c.User.Username, mergerEmail, msg)
747		if err != nil {
748			return c.fail(protocol.ExitFailure, "%v", err)
749		}
750
751	case "rebase":
752		commits, err := gitutil.RevListRange(dir, targetSHA, headSHA)
753		if err != nil {
754			return c.fail(protocol.ExitFailure, "%v", err)
755		}
756		// Oldest first.
757		for i, j := 0, len(commits)-1; i < j; i, j = i+1, j-1 {
758			commits[i], commits[j] = commits[j], commits[i]
759		}
760		onto := targetSHA
761		for _, sha := range commits {
762			parents, err := gitutil.CommitParents(dir, sha)
763			if err != nil {
764				return c.fail(protocol.ExitFailure, "%v", err)
765			}
766			if len(parents) > 1 {
767				return c.fail(protocol.ExitUsage,
768					"the MR contains merge commit %.10s; a rebase merge needs linear history — use --strategy merge or squash", sha)
769			}
770			base := onto // root commit: replay against the new tip itself
771			if len(parents) == 1 {
772				base = parents[0]
773			}
774			tree, conflict, err := gitutil.MergeTreeOnto(dir, base, onto, sha)
775			if err != nil {
776				return c.fail(protocol.ExitFailure, "%v", err)
777			}
778			if conflict {
779				return c.fail(protocol.ExitUsage,
780					"commit %.10s does not apply cleanly onto %s; rebase locally and re-push", sha, mr.TargetRef)
781			}
782			aName, aEmail, aDate, err := gitutil.AuthorIdent(dir, sha)
783			if err != nil {
784				return c.fail(protocol.ExitFailure, "%v", err)
785			}
786			msg, err := gitutil.CommitMessage(dir, sha)
787			if err != nil {
788				return c.fail(protocol.ExitFailure, "%v", err)
789			}
790			onto, err = gitutil.CommitTreeIdent(dir, tree, []string{onto},
791				aName, aEmail, aDate, c.User.Username, mergerEmail, msg)
792			if err != nil {
793				return c.fail(protocol.ExitFailure, "%v", err)
794			}
795		}
796		newSHA = onto
797	}
798
799	// CAS so a concurrent push between our read and this write fails the
800	// merge instead of silently discarding the push.
801	if err := gitutil.UpdateRefCAS(dir, targetRef, newSHA, targetSHA); err != nil {
802		return c.fail(protocol.ExitFailure, "target branch moved during merge; retry: %v", err)
803	}
804	if err := c.Store.MarkMerged(mr.ID, targetSHA); err != nil {
805		return c.fail(protocol.ExitFailure, "%v", err)
806	}
807	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d,"sha":%q}`, mr.Number, newSHA))
808	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
809		notifyUsers(c, parts, mrSubject(repo, mr.Number, mr.Title),
810			notifyBody(c, fmt.Sprintf("merged !%d into %s (%s)", mr.Number, mr.TargetRef, strategy), "", fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)))
811	}
812	return c.emit(map[string]any{"number": mr.Number, "strategy": strategy, "sha": newSHA}, func(w io.Writer) {
813		fmt.Fprintf(w, "merged %s!%d into %s (%s) at %.10s\n", repo.Path(), mr.Number, mr.TargetRef, strategy, newSHA)
814	})
815}
816
817// reviewGates enforces require_approvals (fresh, non-author, latest review
818// per reviewer; a fresh request-changes blocks), CODEOWNERS coverage, and
819// require_resolved. Returns -1 to proceed.
820func (c *Ctx) reviewGates(repo store.Repo, mr store.MR, dir, targetSHA, headSHA string) int {
821	set := repo.Settings
822	if set.RequireApprovals == 0 && !set.RequireResolved {
823		return -1
824	}
825
826	if set.RequireApprovals > 0 {
827		reviews, err := c.Store.ListMRReviews(mr.ID)
828		if err != nil {
829			return c.fail(protocol.ExitFailure, "%v", err)
830		}
831		// Latest fresh review per reviewer decides their stance.
832		latest := map[string]string{}
833		for _, r := range reviews {
834			if r.Stale || r.Reviewer == mr.Author {
835				continue
836			}
837			latest[r.Reviewer] = r.Verdict
838		}
839		var approvers []string
840		var blockers []string
841		for who, verdict := range latest {
842			switch verdict {
843			case "approve":
844				approvers = append(approvers, who)
845			case "request_changes":
846				blockers = append(blockers, who)
847			}
848		}
849		if len(blockers) > 0 {
850			slices.Sort(blockers)
851			return c.fail(protocol.ExitDenied,
852				"%s requested changes on !%d; resolve their review before merging", strings.Join(blockers, ", "), mr.Number)
853		}
854		if len(approvers) < set.RequireApprovals {
855			return c.fail(protocol.ExitDenied,
856				"%s requires %d fresh approval(s); !%d has %d", repo.Path(), set.RequireApprovals, mr.Number, len(approvers))
857		}
858
859		// CODEOWNERS: every owned changed file needs an approval from one
860		// of its owners.
861		content, err := gitutil.ReadBlob(dir, "refs/heads/"+mr.TargetRef, "CODEOWNERS", 1<<20)
862		if err != nil {
863			content, err = gitutil.ReadBlob(dir, "refs/heads/"+mr.TargetRef, ".gitbay/CODEOWNERS", 1<<20)
864		}
865		if err == nil && len(content) > 0 {
866			rules := policy.ParseCodeowners(string(content))
867			base, err := gitutil.MergeBase(dir, targetSHA, headSHA)
868			if err != nil {
869				return c.fail(protocol.ExitFailure, "%v", err)
870			}
871			files, err := gitutil.DiffFiles(dir, base, headSHA)
872			if err != nil {
873				return c.fail(protocol.ExitFailure, "%v", err)
874			}
875			approved := map[string]bool{}
876			for _, a := range approvers {
877				approved[a] = true
878			}
879			missing := map[string][]string{} // owner-set key -> example paths
880			for _, f := range files {
881				owners := policy.OwnersFor(rules, f)
882				if owners == nil {
883					continue
884				}
885				ok := false
886				for _, o := range owners {
887					if approved[o] {
888						ok = true
889						break
890					}
891				}
892				if !ok {
893					key := strings.Join(owners, ",")
894					if len(missing[key]) < 3 {
895						missing[key] = append(missing[key], f)
896					}
897				}
898			}
899			if len(missing) > 0 {
900				var parts []string
901				for owners, paths := range missing {
902					parts = append(parts, fmt.Sprintf("%s (owned by %s)", strings.Join(paths, ", "), owners))
903				}
904				slices.Sort(parts)
905				return c.fail(protocol.ExitDenied,
906					"CODEOWNERS approval missing for: %s", strings.Join(parts, "; "))
907			}
908		}
909	}
910
911	if set.RequireResolved {
912		n, err := c.Store.UnresolvedThreadCount(mr.ID)
913		if err != nil {
914			return c.fail(protocol.ExitFailure, "%v", err)
915		}
916		if n > 0 {
917			return c.fail(protocol.ExitDenied,
918				"%s requires review threads resolved; !%d has %d open (mr threads %s %d)", repo.Path(), mr.Number, n, repo.Path(), mr.Number)
919		}
920	}
921	return -1
922}
923
924func runMRClose(c *Ctx, args []string) int {
925	repo, mr, code := mrRef(c, args, policy.CanRead)
926	if code >= 0 {
927		return code
928	}
929	if len(args) != 2 {
930		return c.fail(protocol.ExitUsage, "usage: mr close <owner/name> <n>")
931	}
932	grant, err := c.Store.AccessRole(repo.ID, c.User.ID)
933	if err != nil {
934		return c.fail(protocol.ExitFailure, "%v", err)
935	}
936	if mr.Author != c.User.Username && !policy.CanWrite(c.User, repo, grant) {
937		return c.fail(protocol.ExitDenied, "only the author or users with write access can close this MR")
938	}
939	if mr.State == "merged" || mr.State == "closed" {
940		return c.fail(protocol.ExitUsage, "MR !%d is already %s", mr.Number, mr.State)
941	}
942	if err := c.Store.SetMRState(mr.ID, "closed"); err != nil {
943		return c.fail(protocol.ExitFailure, "%v", err)
944	}
945	return c.emit(map[string]any{"number": mr.Number, "state": "closed"}, func(w io.Writer) {
946		fmt.Fprintf(w, "closed %s!%d\n", repo.Path(), mr.Number)
947	})
948}