internal/control/mr.go

251a71053c93d2621ad97fa7d1ce8efacb119406
gitbay/internal/control/mr.go history · blame · raw

1150 lines · 41331 bytes

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