internal/control/mr.go

5e9732fb1d5142142fdae2985f07125cf852647c
gitbay/internal/control/mr.go history · blame · raw

1171 lines · 42474 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] [--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] [--limit <n>] [--cursor <c>]"
 392	f := store.MRFilter{State: "open"}
 393	fl, err := parseFlags(args, flagSpec{Values: []string{"--state", "--author", "--milestone"}, 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	valid := map[string]bool{"open": true, "merged": true, "closed": true, "source_gone": true, "all": true}
 403	if path == "" || !valid[f.State] {
 404		return c.fail(protocol.ExitUsage, usage)
 405	}
 406	repo, code := resolveRepo(c, path, policy.CanRead)
 407	if code >= 0 {
 408		return code
 409	}
 410	f.Limit, f.Before = p.queryLimit(), p.keyInt()
 411	mrs, err := c.Store.QueryMRs(repo.ID, f)
 412	if err != nil {
 413		return c.fail(protocol.ExitFailure, "%v", err)
 414	}
 415	mrs, next := trimPage(p, mrs, "mr", func(m store.MR) string {
 416		return strconv.FormatInt(m.Number, 10)
 417	})
 418	var ds []mrOut
 419	for _, m := range mrs {
 420		o := mrToOut(repo, m, false)
 421		o.StackedOn, _ = stackOf(c, repo, m)
 422		ds = append(ds, o)
 423	}
 424	return c.emitPage(p, ds, next, func(w io.Writer) {
 425		for _, d := range ds {
 426			stacked := ""
 427			if d.StackedOn != nil {
 428				stacked = fmt.Sprintf("\tstacked on !%d", d.StackedOn.Number)
 429			}
 430			fmt.Fprintf(w, "!%d\t%s\t%s\t%s -> %s%s\n", d.Number, d.State, d.Title, d.Source, d.TargetRef, stacked)
 431		}
 432	})
 433}
 434
 435// byWhom renders " by <user>", or nothing when the actor is unknown — an
 436// imported merge request carries a time but no local account.
 437func byWhom(user string) string {
 438	if user == "" {
 439		return ""
 440	}
 441	return " by " + user
 442}
 443
 444func runMRShow(c *Ctx, args []string) int {
 445	repo, mr, code := mrRef(c, args, policy.CanRead)
 446	if code >= 0 {
 447		return code
 448	}
 449	if len(args) != 2 {
 450		return c.fail(protocol.ExitUsage, "usage: mr show <owner/name> <n>")
 451	}
 452	comments, err := c.Store.ListMRComments(mr.ID)
 453	if err != nil {
 454		return c.fail(protocol.ExitFailure, "%v", err)
 455	}
 456	reviews, err := c.Store.ListMRReviews(mr.ID)
 457	if err != nil {
 458		return c.fail(protocol.ExitFailure, "%v", err)
 459	}
 460	statuses, combined, err := c.Store.ChecksForCommit(repo.ID, mr.HeadSHA)
 461	if err != nil {
 462		return c.fail(protocol.ExitFailure, "%v", err)
 463	}
 464	unresolved, err := c.Store.UnresolvedThreadCount(mr.ID)
 465	if err != nil {
 466		return c.fail(protocol.ExitFailure, "%v", err)
 467	}
 468	var checks []CheckOut
 469	for _, st := range statuses {
 470		out := CheckOut{Context: st.Context, State: st.State, URL: st.TargetURL, UpdatedAt: st.UpdatedAt}
 471		if st.Duration > 0 {
 472			out.Duration = st.Duration.String()
 473		}
 474		checks = append(checks, out)
 475	}
 476	var cs []commentOut
 477	for _, cm := range comments {
 478		cs = append(cs, commentOut{cm.Author, cm.Body, cm.BodyFormat, cm.CreatedAt})
 479	}
 480	var rs []ReviewOut
 481	for _, r := range reviews {
 482		rs = append(rs, ReviewOut{r.Reviewer, r.Verdict, r.Stale, r.CreatedAt})
 483	}
 484	// The commits this MR carries: base..head, the diff's range.
 485	var commits []CommitOut
 486	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
 487	base := mr.MergedBase
 488	if base == "" {
 489		if b, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, mrHeadRef(mr.Number)); err == nil {
 490			base = b
 491		}
 492	}
 493	if base != "" {
 494		if shas, err := gitutil.RevListRange(dir, base, mrHeadRef(mr.Number)); err == nil {
 495			for _, sha := range shas {
 496				subject := ""
 497				if raw, err := gitutil.ReadCommit(dir, sha); err == nil {
 498					if parsed, err := sig.ParseCommit(raw); err == nil {
 499						subject = parsed.Subject
 500					}
 501				}
 502				commits = append(commits, CommitOut{sha, subject})
 503			}
 504		}
 505	}
 506	d := MRShow{mrOut: mrToOut(repo, mr, true), Checks: checks, Combined: combined,
 507		UnresolvedThreads: unresolved, Commits: commits, Comments: cs, Reviews: rs}
 508	d.StackedOn, d.Stacked = stackOf(c, repo, mr)
 509	return c.emit(d, func(w io.Writer) {
 510		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)
 511		if d.StackedOn != nil {
 512			fmt.Fprintf(w, "stacked on !%d %s\n", d.StackedOn.Number, d.StackedOn.Title)
 513		}
 514		for _, k := range d.Stacked {
 515			fmt.Fprintf(w, "stacked: !%d %s\n", k.Number, k.Title)
 516		}
 517		if d.MergedAt != "" {
 518			fmt.Fprintf(w, "merged %s%s\n", d.MergedAt, byWhom(d.MergedBy))
 519		}
 520		if d.ClosedAt != "" {
 521			fmt.Fprintf(w, "closed %s%s\n", d.ClosedAt, byWhom(d.ClosedBy))
 522		}
 523		if d.Body != "" {
 524			fmt.Fprintf(w, "\n%s\n", d.Body)
 525		}
 526		for _, cm := range commits {
 527			fmt.Fprintf(w, "commit: %.10s %s\n", cm.SHA, cm.Subject)
 528		}
 529		for _, x := range checks {
 530			dur := ""
 531			if x.Duration != "" {
 532				dur = " in " + x.Duration
 533			}
 534			fmt.Fprintf(w, "check: %s %s at %s%s\n", x.Context, x.State, x.UpdatedAt, dur)
 535		}
 536		if d.UnresolvedThreads > 0 {
 537			fmt.Fprintf(w, "unresolved threads: %d\n", d.UnresolvedThreads)
 538		}
 539		for _, r := range rs {
 540			stale := ""
 541			if r.Stale {
 542				stale = " (stale)"
 543			}
 544			fmt.Fprintf(w, "review: %s %s%s at %s\n", r.Reviewer, r.Verdict, stale, r.CreatedAt)
 545		}
 546		for _, cm := range cs {
 547			fmt.Fprintf(w, "\n--- %s at %s\n%s\n", cm.Author, cm.CreatedAt, cm.Body)
 548		}
 549	})
 550}
 551
 552func runMRDiff(c *Ctx, args []string) int {
 553	repo, mr, code := mrRef(c, args, policy.CanRead)
 554	if code >= 0 {
 555		return code
 556	}
 557	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
 558	head := mrHeadRef(mr.Number)
 559	// After a merge (especially fast-forward) the live merge-base equals
 560	// the head and the diff would vanish; use the recorded base instead.
 561	base := mr.MergedBase
 562	if base == "" {
 563		b, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, head)
 564		if err != nil {
 565			return c.fail(protocol.ExitFailure, "%v", err)
 566		}
 567		base = b
 568	}
 569	patch, truncated, err := gitutil.Diff(dir, base, head, 4<<20)
 570	if err != nil {
 571		return c.fail(protocol.ExitFailure, "%v", err)
 572	}
 573	fmt.Fprint(c.Stdout, patch)
 574	if truncated {
 575		fmt.Fprintln(c.Stderr, "diff truncated at 4 MiB; fetch the branch for the rest")
 576	}
 577	return protocol.ExitOK
 578}
 579
 580func runMREdit(c *Ctx, args []string) int {
 581	rest, title, body, format, code := editText(c, args, "mr")
 582	if code >= 0 {
 583		return code
 584	}
 585	repo, mr, code := mrRef(c, rest, policy.CanRead)
 586	if code >= 0 {
 587		return code
 588	}
 589	if code := refuseArchived(c, repo); code >= 0 {
 590		return code
 591	}
 592	if code := authorOrWrite(c, repo, mr.Author, "edit this merge request"); code >= 0 {
 593		return code
 594	}
 595	if err := c.Store.UpdateMRText(mr.ID, title, body, format); err != nil {
 596		return c.fail(protocol.ExitFailure, "%v", err)
 597	}
 598	return c.emit(map[string]any{"number": mr.Number}, func(w io.Writer) {
 599		fmt.Fprintf(w, "edited %s!%d\n", repo.Path(), mr.Number)
 600	})
 601}
 602
 603// runMRRetarget moves an open merge request onto another branch of the
 604// same repository.
 605func runMRRetarget(c *Ctx, args []string) int {
 606	if len(args) != 3 {
 607		return c.fail(protocol.ExitUsage, "usage: mr retarget <owner/name> <n> <branch>")
 608	}
 609	repo, mr, code := mrRef(c, args[:2], policy.CanRead)
 610	if code >= 0 {
 611		return code
 612	}
 613	if code := refuseArchived(c, repo); code >= 0 {
 614		return code
 615	}
 616	if code := authorOrWrite(c, repo, mr.Author, "retarget this merge request"); code >= 0 {
 617		return code
 618	}
 619	if mr.State == "merged" || mr.State == "closed" {
 620		return c.fail(protocol.ExitUsage, "!%d is %s; only an open merge request can be retargeted", mr.Number, mr.State)
 621	}
 622	target := args[2]
 623	if target == mr.TargetRef {
 624		return c.fail(protocol.ExitUsage, "!%d already targets %s", mr.Number, target)
 625	}
 626	if mr.SourceRepoID == repo.ID && target == mr.SourceRef {
 627		return c.fail(protocol.ExitUsage, "%s is the source branch of !%d", target, mr.Number)
 628	}
 629	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
 630	if _, err := gitutil.ResolveRef(dir, "refs/heads/"+target); err != nil {
 631		return c.fail(protocol.ExitNotFound, "branch %s not found in %s", target, repo.Path())
 632	}
 633	// The diff, the commit list and the merge gates all derive their base
 634	// from the target on every read, so the only thing to check here is
 635	// that a base exists at all: without one there is nothing to show and
 636	// nothing to merge.
 637	base, err := gitutil.MergeBase(dir, "refs/heads/"+target, mrHeadRef(mr.Number))
 638	if err != nil || base == "" {
 639		return c.fail(protocol.ExitUsage, "%s shares no history with the head of !%d", target, mr.Number)
 640	}
 641	old := mr.TargetRef
 642	if err := c.Store.SetMRTarget(mr.ID, target); err != nil {
 643		return c.fail(protocol.ExitFailure, "%v", err)
 644	}
 645	c.Store.AddMRSystemComment(mr.ID, c.User.ID, fmt.Sprintf("retargeted from %s to %s", old, target))
 646	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
 647		notify(c, parts, notice{repo: repo, kind: "mr",
 648			subject: mrSubject(repo, mr.Number, mr.Title),
 649			action:  fmt.Sprintf("retargeted !%d from %s to %s", mr.Number, old, target),
 650			path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
 651	}
 652	return c.emit(map[string]any{"number": mr.Number, "target_ref": target, "merge_base": base}, func(w io.Writer) {
 653		fmt.Fprintf(w, "retargeted %s!%d from %s to %s (base %.10s)\n", repo.Path(), mr.Number, old, target, base)
 654	})
 655}
 656
 657func runMRComment(c *Ctx, args []string) int {
 658	return runComment(c, args, mrThread, "mr",
 659		func(rest []string) (store.Repo, int64, int64, string, int) {
 660			repo, mr, code := mrRef(c, rest, policy.CanRead)
 661			return repo, mr.ID, mr.Number, mr.Title, code
 662		},
 663		c.Store.AddMRComment, c.Store.MRParticipants)
 664}
 665
 666func runMRReview(c *Ctx, args []string) int {
 667	verdict := ""
 668	var rest []string
 669	for _, a := range args {
 670		switch a {
 671		case "--approve":
 672			verdict = "approve"
 673		case "--request-changes":
 674			verdict = "request_changes"
 675		case "--comment":
 676			verdict = "comment"
 677		default:
 678			rest = append(rest, a)
 679		}
 680	}
 681	if verdict == "" {
 682		return c.fail(protocol.ExitUsage, "usage: mr review <owner/name> <n> --approve|--request-changes|--comment")
 683	}
 684	repo, mr, code := mrRef(c, rest, policy.CanRead)
 685	if code >= 0 {
 686		return code
 687	}
 688	if code := refuseArchived(c, repo); code >= 0 {
 689		return code
 690	}
 691	if mr.State != "open" {
 692		return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
 693	}
 694	if err := c.Store.AddMRReview(mr.ID, c.User.ID, verdict, mr.HeadSHA); err != nil {
 695		return c.fail(protocol.ExitFailure, "%v", err)
 696	}
 697	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
 698		notify(c, parts, notice{repo: repo, kind: "mr",
 699			subject: mrSubject(repo, mr.Number, mr.Title),
 700			action:  fmt.Sprintf("reviewed !%d: %s", mr.Number, verdict),
 701			path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
 702	}
 703	return c.emit(map[string]any{"number": mr.Number, "verdict": verdict}, func(w io.Writer) {
 704		fmt.Fprintf(w, "reviewed %s!%d: %s\n", repo.Path(), mr.Number, verdict)
 705	})
 706}
 707
 708func runMRMerge(c *Ctx, args []string) int {
 709	f, err := parseFlags(args, flagSpec{Values: []string{"--strategy"}, MaxPos: -1, Usage: "mr merge <owner/name> <n> [--strategy ff|merge|squash|rebase]"})
 710	if err != nil {
 711		return c.fail(protocol.ExitUsage, "%v", err)
 712	}
 713	strategy, rest := f.Value("--strategy"), f.Pos
 714	valid := map[string]bool{"": true, "ff": true, "merge": true, "squash": true, "rebase": true}
 715	if !valid[strategy] {
 716		return c.fail(protocol.ExitUsage, "--strategy must be ff, merge, squash, or rebase")
 717	}
 718	repo, mr, code := mrRef(c, rest, policy.CanWrite)
 719	if code >= 0 {
 720		return code
 721	}
 722	if code := refuseArchived(c, repo); code >= 0 {
 723		return code
 724	}
 725	if mr.State != "open" && mr.State != "source_gone" {
 726		return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
 727	}
 728
 729	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
 730	targetRef := "refs/heads/" + mr.TargetRef
 731	targetSHA, err := gitutil.ResolveRef(dir, targetRef)
 732	if err != nil {
 733		return c.fail(protocol.ExitFailure, "target branch %s: %v", mr.TargetRef, err)
 734	}
 735	headSHA, err := gitutil.ResolveRef(dir, mrHeadRef(mr.Number))
 736	if err != nil {
 737		return c.fail(protocol.ExitFailure, "MR head ref: %v", err)
 738	}
 739
 740	// Check gate: with require_checks, the MR head must carry statuses
 741	// and every one of them must be green.
 742	if repo.Settings.RequireChecks {
 743		statuses, err := c.Store.ListCommitStatuses(repo.ID, headSHA)
 744		if err != nil {
 745			return c.fail(protocol.ExitFailure, "%v", err)
 746		}
 747		switch store.CombinedStatus(statuses) {
 748		case "success":
 749		case "":
 750			return c.fail(protocol.ExitDenied,
 751				"%s requires green checks and none were reported on %.10s", repo.Path(), headSHA)
 752		default:
 753			var bad []string
 754			for _, st := range statuses {
 755				if st.State != "success" {
 756					bad = append(bad, st.Context+"="+st.State)
 757				}
 758			}
 759			return c.fail(protocol.ExitDenied,
 760				"%s requires green checks; %.10s has %s", repo.Path(), headSHA, strings.Join(bad, ", "))
 761		}
 762	}
 763
 764	// Review gates: approvals, CODEOWNERS, resolved threads.
 765	if code := c.reviewGates(repo, mr, dir, targetSHA, headSHA); code >= 0 {
 766		return code
 767	}
 768
 769	upToDate, err := gitutil.IsAncestor(dir, headSHA, targetSHA)
 770	if err != nil {
 771		return c.fail(protocol.ExitFailure, "%v", err)
 772	}
 773	if upToDate {
 774		// The head is already on the target: merged by hand and pushed, or
 775		// a merge whose ref update landed and whose record did not. Record
 776		// it rather than refuse, so a merge request cannot be stuck open
 777		// with no way to close it as merged (#108).
 778		if err := c.Store.MarkMerged(mr.ID, targetSHA, c.User.ID, ""); err != nil {
 779			return c.fail(protocol.ExitFailure, "%v", err)
 780		}
 781		c.Store.RecordEvent(repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d}`, mr.Number))
 782		return c.emit(map[string]any{"number": mr.Number, "strategy": "recorded", "sha": headSHA}, func(w io.Writer) {
 783			fmt.Fprintf(w, "%s already contains !%d; recorded as merged at %.10s\n", mr.TargetRef, mr.Number, headSHA)
 784		})
 785	}
 786	ffPossible, err := gitutil.IsAncestor(dir, targetSHA, headSHA)
 787	if err != nil {
 788		return c.fail(protocol.ExitFailure, "%v", err)
 789	}
 790
 791	// Signature policy matrix: with require_signed_commits, only
 792	// fast-forward is allowed — squash, rebase-replay, and merge commits
 793	// are all server-created and unsigned, violating the branch's own
 794	// policy — and every landed commit must be verified. An explicit
 795	// rebase when fast-forward is already possible IS a fast-forward
 796	// (nothing is rewritten), so it stays legal.
 797	if repo.Settings.RequireSignedCommits {
 798		if strategy == "merge" || strategy == "squash" || !ffPossible {
 799			return c.fail(protocol.ExitDenied,
 800				"%s requires signed commits, so only fast-forward merges are allowed; rebase %s onto %s locally, re-push, and merge again",
 801				repo.Path(), mr.SourceRef, mr.TargetRef)
 802		}
 803		strategy = "ff"
 804		commits, err := gitutil.RevListRange(dir, targetSHA, headSHA)
 805		if err != nil {
 806			return c.fail(protocol.ExitFailure, "%v", err)
 807		}
 808		for _, sha := range commits {
 809			raw, err := gitutil.ReadCommit(dir, sha)
 810			if err != nil {
 811				return c.fail(protocol.ExitFailure, "%v", err)
 812			}
 813			parsed, err := sigParse(raw)
 814			if err != nil {
 815				return c.fail(protocol.ExitFailure, "%v", err)
 816			}
 817			res, err := VerifyCommitCached(c.Store, repo, parsed, sha)
 818			if err != nil {
 819				return c.fail(protocol.ExitFailure, "%v", err)
 820			}
 821			if res.State != "verified" {
 822				return c.fail(protocol.ExitDenied,
 823					"%s requires signed commits: %.10s is %s", repo.Path(), sha, res.State)
 824			}
 825		}
 826	}
 827	if strategy == "" {
 828		if ffPossible {
 829			strategy = "ff"
 830		} else {
 831			strategy = "merge"
 832		}
 833	}
 834	if strategy == "rebase" && ffPossible {
 835		// Nothing to rewrite: a rebase onto an ancestor is a fast-forward,
 836		// and taking it keeps the original commits and their signatures.
 837		strategy = "ff"
 838	}
 839
 840	// Every server-created commit needs the merger's verified identity.
 841	mergerEmail := ""
 842	if strategy != "ff" {
 843		email, err := c.Store.PrimaryVerifiedEmail(c.User.ID)
 844		if err != nil {
 845			return c.fail(protocol.ExitFailure, "%v", err)
 846		}
 847		if email == "" {
 848			return c.fail(protocol.ExitDenied,
 849				"%s merges create commits carrying your identity: verify a primary email first (or use a fast-forward merge)", strategy)
 850		}
 851		mergerEmail = email
 852	}
 853
 854	var newSHA string
 855	switch strategy {
 856	case "ff":
 857		if !ffPossible {
 858			return c.fail(protocol.ExitUsage,
 859				"fast-forward not possible: %s has diverged from the MR head; use --strategy merge or rebase and re-push", mr.TargetRef)
 860		}
 861		newSHA = headSHA
 862
 863	case "merge":
 864		tree, conflict, err := gitutil.MergeTree(dir, targetSHA, headSHA)
 865		if err != nil {
 866			return c.fail(protocol.ExitFailure, "%v", err)
 867		}
 868		if conflict {
 869			return c.fail(protocol.ExitUsage,
 870				"merge conflicts between %s and the MR head; resolve locally and re-push", mr.TargetRef)
 871		}
 872		msg := fmt.Sprintf("Merge request !%d: %s\n\nMerged %s into %s", mr.Number, mr.Title, mr.SourceRef, mr.TargetRef)
 873		newSHA, err = gitutil.CommitTree(dir, tree, []string{targetSHA, headSHA}, c.User.Username, mergerEmail, msg)
 874		if err != nil {
 875			return c.fail(protocol.ExitFailure, "%v", err)
 876		}
 877
 878	case "squash":
 879		// One new commit with the merged tree. Authorship credit goes to
 880		// the MR author (their verified identity when they have one); the
 881		// committer is the merger.
 882		tree := ""
 883		if ffPossible {
 884			t, err := gitutil.ResolveTree(dir, headSHA)
 885			if err != nil {
 886				return c.fail(protocol.ExitFailure, "%v", err)
 887			}
 888			tree = t
 889		} else {
 890			t, conflict, err := gitutil.MergeTree(dir, targetSHA, headSHA)
 891			if err != nil {
 892				return c.fail(protocol.ExitFailure, "%v", err)
 893			}
 894			if conflict {
 895				return c.fail(protocol.ExitUsage,
 896					"merge conflicts between %s and the MR head; resolve locally and re-push", mr.TargetRef)
 897			}
 898			tree = t
 899		}
 900		authorName, authorEmail := c.User.Username, mergerEmail
 901		if author, err := c.Store.UserByUsername(mr.Author); err == nil {
 902			if ae, err := c.Store.PrimaryVerifiedEmail(author.ID); err == nil && ae != "" {
 903				authorName, authorEmail = author.Username, ae
 904			}
 905		}
 906		msg := fmt.Sprintf("%s (!%d)", mr.Title, mr.Number)
 907		if mr.Body != "" {
 908			msg += "\n\n" + mr.Body
 909		}
 910		var err error
 911		newSHA, err = gitutil.CommitTreeIdent(dir, tree, []string{targetSHA},
 912			authorName, authorEmail, "", c.User.Username, mergerEmail, msg)
 913		if err != nil {
 914			return c.fail(protocol.ExitFailure, "%v", err)
 915		}
 916
 917	case "rebase":
 918		commits, err := gitutil.RevListRange(dir, targetSHA, headSHA)
 919		if err != nil {
 920			return c.fail(protocol.ExitFailure, "%v", err)
 921		}
 922		// Oldest first.
 923		for i, j := 0, len(commits)-1; i < j; i, j = i+1, j-1 {
 924			commits[i], commits[j] = commits[j], commits[i]
 925		}
 926		onto := targetSHA
 927		for _, sha := range commits {
 928			parents, err := gitutil.CommitParents(dir, sha)
 929			if err != nil {
 930				return c.fail(protocol.ExitFailure, "%v", err)
 931			}
 932			if len(parents) > 1 {
 933				return c.fail(protocol.ExitUsage,
 934					"the MR contains merge commit %.10s; a rebase merge needs linear history — use --strategy merge or squash", sha)
 935			}
 936			base := onto // root commit: replay against the new tip itself
 937			if len(parents) == 1 {
 938				base = parents[0]
 939			}
 940			tree, conflict, err := gitutil.MergeTreeOnto(dir, base, onto, sha)
 941			if err != nil {
 942				return c.fail(protocol.ExitFailure, "%v", err)
 943			}
 944			if conflict {
 945				return c.fail(protocol.ExitUsage,
 946					"commit %.10s does not apply cleanly onto %s; rebase locally and re-push", sha, mr.TargetRef)
 947			}
 948			aName, aEmail, aDate, err := gitutil.AuthorIdent(dir, sha)
 949			if err != nil {
 950				return c.fail(protocol.ExitFailure, "%v", err)
 951			}
 952			msg, err := gitutil.CommitMessage(dir, sha)
 953			if err != nil {
 954				return c.fail(protocol.ExitFailure, "%v", err)
 955			}
 956			onto, err = gitutil.CommitTreeIdent(dir, tree, []string{onto},
 957				aName, aEmail, aDate, c.User.Username, mergerEmail, msg)
 958			if err != nil {
 959				return c.fail(protocol.ExitFailure, "%v", err)
 960			}
 961		}
 962		newSHA = onto
 963	}
 964
 965	// A stacked merge request's diff is against this branch. After a
 966	// fast-forward or merge commit the same commits are on the target and
 967	// its diff is unchanged there; after a squash or rebase they are not,
 968	// and the stack would carry this merge request's changes a second
 969	// time. Refuse rather than leave the stack wrong.
 970	var stack []store.MR
 971	if mr.SourceRepoID == repo.ID {
 972		stack, _ = c.Store.OpenMRsByTarget(repo.ID, mr.SourceRef)
 973	}
 974	if len(stack) > 0 && (strategy == "squash" || strategy == "rebase") {
 975		var nums []string
 976		for _, k := range stack {
 977			nums = append(nums, fmt.Sprintf("!%d", k.Number))
 978		}
 979		return c.fail(protocol.ExitUsage,
 980			"%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",
 981			fmt.Sprintf("!%d", mr.Number), strings.Join(nums, ", "), strategy, mr.SourceRef)
 982	}
 983
 984	// CAS so a concurrent push between our read and this write fails the
 985	// merge instead of silently discarding the push.
 986	if err := gitutil.UpdateRefCAS(dir, targetRef, newSHA, targetSHA); err != nil {
 987		return c.fail(protocol.ExitFailure, "target branch moved during merge; retry: %v", err)
 988	}
 989	if err := c.Store.MarkMerged(mr.ID, targetSHA, c.User.ID, ""); err != nil {
 990		return c.fail(protocol.ExitFailure, "%v", err)
 991	}
 992	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d,"sha":%q}`, mr.Number, newSHA))
 993	// The stack moves up: whatever targeted this branch now targets what
 994	// it merged into, reviews intact, since that diff is the one they
 995	// were of.
 996	for _, k := range stack {
 997		if err := c.Store.RetargetKeepingReviews(k.ID, mr.TargetRef); err != nil {
 998			continue
 999		}
1000		c.Store.AddMRSystemComment(k.ID, c.User.ID, fmt.Sprintf("retargeted from %s to %s: !%d merged", mr.SourceRef, mr.TargetRef, mr.Number))
1001		if parts, err := c.Store.MRParticipants(k.ID); err == nil {
1002			notify(c, parts, notice{repo: repo, kind: "mr",
1003				subject: mrSubject(repo, k.Number, k.Title),
1004				action:  fmt.Sprintf("retargeted !%d from %s to %s: !%d merged", k.Number, mr.SourceRef, mr.TargetRef, mr.Number),
1005				path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), k.Number)})
1006		}
1007	}
1008	// Merges bypass receive-pack, so the commit-message issue actions
1009	// (closes #N, references) run here for the newly landed commits. The
1010	// description is scanned after them, so a commit wins the attribution
1011	// when both name the same issue.
1012	if mr.TargetRef == repo.DefaultBranch {
1013		ProcessCommitMessages(c.Store, dir, repo, c.User.ID, targetSHA, newSHA)
1014		ProcessMRDescription(c.Store, repo, mr, c.User.ID)
1015		RecordLandedCommits(c.Store, dir, repo, targetSHA, newSHA)
1016	}
1017	// A merge moves the ref directly, so it never reaches post-receive and
1018	// none of the ref-update work fires on its own. The event webhooks
1019	// subscribe to, and the branch's CI jobs, happen here instead.
1020	c.Store.RecordEvent(repo.ID, c.User.ID, "push", fmt.Sprintf(
1021		`{"ref":%q,"old":%q,"new":%q,"forced":false,"deleted":false}`,
1022		targetRef, targetSHA, newSHA))
1023	QueueBranchBuilds(c.Store, c.Cfg.Server.Root, c.Cfg.Server.SiteURL,
1024		repo, c.User.ID, mr.TargetRef, newSHA, time.Now())
1025	c.Store.MarkMirrorsDirty(repo.ID, "push")
1026	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
1027		notify(c, parts, notice{repo: repo, kind: "mr",
1028			subject: mrSubject(repo, mr.Number, mr.Title),
1029			action:  fmt.Sprintf("merged !%d into %s (%s)", mr.Number, mr.TargetRef, strategy),
1030			path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
1031	}
1032	return c.emit(map[string]any{"number": mr.Number, "strategy": strategy, "sha": newSHA}, func(w io.Writer) {
1033		fmt.Fprintf(w, "merged %s!%d into %s (%s) at %.10s\n", repo.Path(), mr.Number, mr.TargetRef, strategy, newSHA)
1034	})
1035}
1036
1037// reviewGates enforces require_approvals (fresh, non-author, latest review
1038// per reviewer; a fresh request-changes blocks), require_codeowners, and
1039// require_resolved. Returns -1 to proceed.
1040func (c *Ctx) reviewGates(repo store.Repo, mr store.MR, dir, targetSHA, headSHA string) int {
1041	set := repo.Settings
1042	reviews, err := c.Store.ListMRReviews(mr.ID)
1043	if err != nil {
1044		return c.fail(protocol.ExitFailure, "%v", err)
1045	}
1046	// Latest fresh review per reviewer decides their stance.
1047	latest := map[string]string{}
1048	for _, r := range reviews {
1049		if r.Stale || r.Reviewer == mr.Author {
1050			continue
1051		}
1052		latest[r.Reviewer] = r.Verdict
1053	}
1054	var approvers []string
1055	var blockers []string
1056	for who, verdict := range latest {
1057		switch verdict {
1058		case "approve":
1059			approvers = append(approvers, who)
1060		case "request_changes":
1061			blockers = append(blockers, who)
1062		}
1063	}
1064
1065	if set.RequireApprovals > 0 {
1066		if len(blockers) > 0 {
1067			slices.Sort(blockers)
1068			return c.fail(protocol.ExitDenied,
1069				"%s requested changes on !%d; resolve their review before merging", strings.Join(blockers, ", "), mr.Number)
1070		}
1071		if len(approvers) < set.RequireApprovals {
1072			return c.fail(protocol.ExitDenied,
1073				"%s requires %d fresh approval(s); !%d has %d", repo.Path(), set.RequireApprovals, mr.Number, len(approvers))
1074		}
1075	}
1076
1077	// CODEOWNERS: every owned changed file needs an approval from one of
1078	// its owners. require_codeowners is the opt-in — a repository can
1079	// carry the file as documentation of who to ask without it gating
1080	// merges — and it does not wait on require_approvals (#99).
1081	if set.RequireCodeowners {
1082		content, err := gitutil.ReadBlob(dir, "refs/heads/"+mr.TargetRef, "CODEOWNERS", 1<<20)
1083		if err != nil {
1084			content, err = gitutil.ReadBlob(dir, "refs/heads/"+mr.TargetRef, ".gitbay/CODEOWNERS", 1<<20)
1085		}
1086		if err != nil || len(content) == 0 {
1087			return c.fail(protocol.ExitDenied,
1088				"%s requires CODEOWNERS approval but %s carries no CODEOWNERS file",
1089				repo.Path(), mr.TargetRef)
1090		}
1091		rules := policy.ParseCodeowners(string(content))
1092		base, err := gitutil.MergeBase(dir, targetSHA, headSHA)
1093		if err != nil {
1094			return c.fail(protocol.ExitFailure, "%v", err)
1095		}
1096		files, err := gitutil.DiffFiles(dir, base, headSHA)
1097		if err != nil {
1098			return c.fail(protocol.ExitFailure, "%v", err)
1099		}
1100		approved := map[string]bool{}
1101		for _, a := range approvers {
1102			approved[a] = true
1103		}
1104		missing := map[string][]string{} // owner-set key -> example paths
1105		for _, f := range files {
1106			owners := policy.OwnersFor(rules, f)
1107			if owners == nil {
1108				continue
1109			}
1110			ok := false
1111			for _, o := range owners {
1112				if approved[o] {
1113					ok = true
1114					break
1115				}
1116			}
1117			if !ok {
1118				key := strings.Join(owners, ",")
1119				if len(missing[key]) < 3 {
1120					missing[key] = append(missing[key], f)
1121				}
1122			}
1123		}
1124		if len(missing) > 0 {
1125			var parts []string
1126			for owners, paths := range missing {
1127				parts = append(parts, fmt.Sprintf("%s (owned by %s)", strings.Join(paths, ", "), owners))
1128			}
1129			slices.Sort(parts)
1130			return c.fail(protocol.ExitDenied,
1131				"CODEOWNERS approval missing for: %s", strings.Join(parts, "; "))
1132		}
1133	}
1134
1135	if set.RequireResolved {
1136		n, err := c.Store.UnresolvedThreadCount(mr.ID)
1137		if err != nil {
1138			return c.fail(protocol.ExitFailure, "%v", err)
1139		}
1140		if n > 0 {
1141			return c.fail(protocol.ExitDenied,
1142				"%s requires review threads resolved; !%d has %d open (mr threads %s %d)", repo.Path(), mr.Number, n, repo.Path(), mr.Number)
1143		}
1144	}
1145	return -1
1146}
1147
1148func runMRClose(c *Ctx, args []string) int {
1149	repo, mr, code := mrRef(c, args, policy.CanRead)
1150	if code >= 0 {
1151		return code
1152	}
1153	if code := refuseArchived(c, repo); code >= 0 {
1154		return code
1155	}
1156	if len(args) != 2 {
1157		return c.fail(protocol.ExitUsage, "usage: mr close <owner/name> <n>")
1158	}
1159	if code := authorOrWrite(c, repo, mr.Author, "close this merge request"); code >= 0 {
1160		return code
1161	}
1162	if mr.State == "merged" || mr.State == "closed" {
1163		return c.fail(protocol.ExitUsage, "MR !%d is already %s", mr.Number, mr.State)
1164	}
1165	if err := c.Store.MarkClosed(mr.ID, c.User.ID, ""); err != nil {
1166		return c.fail(protocol.ExitFailure, "%v", err)
1167	}
1168	return c.emit(map[string]any{"number": mr.Number, "state": "closed"}, func(w io.Writer) {
1169		fmt.Fprintf(w, "closed %s!%d\n", repo.Path(), mr.Number)
1170	})
1171}