internal/control/mr.go

3af6fd1aaf69413d258a4131a627d048d2f1d290
gitbay/internal/control/mr.go history · blame · raw

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