internal/control/mr.go

61564b7c32807deb349e28f2b5c6909cb4143870
gitbay/internal/control/mr.go history · blame · raw

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