internal/control/mr.go

7cc95d1fc1115f22008751a05e9e07156d49d6b0
gitbay/internal/control/mr.go history · blame · raw

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