internal/control/mr.go

f150dbe6d87e2cd72e724d229eb642d681a23c32
gitbay/internal/control/mr.go

1189 lines · 43380 bytes

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