internal/control/mr.go

e7b249b38d2d85e868196130ce690fc43088d9d2
gitbay/internal/control/mr.go history · blame · raw

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