internal/control/mr.go

94884a22329740d40876a987689c17ab77aa9965
gitbay/internal/control/mr.go history · blame · raw

1213 lines · 43539 bytes

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