internal/control/mr.go

160fc0ec2bbbb4367ce5db1814c1a7404b656048
gitbay/internal/control/mr.go history · blame · raw

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