internal/control/mr.go

1769 lines · 63858 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/ci"
  13	"gitbay.org/gitbay/internal/gitutil"
  14	"gitbay.org/gitbay/internal/policy"
  15	"gitbay.org/gitbay/internal/protocol"
  16	"gitbay.org/gitbay/internal/sig"
  17	"gitbay.org/gitbay/internal/store"
  18)
  19
  20func init() {
  21	register(Command{Path: []string{"repo", "fork"},
  22		Summary: "fork a repository under your account",
  23		Usage:   "repo fork <owner/name> [--name <n>]", Run: runRepoFork})
  24	register(Command{Path: []string{"repo", "settings", "require-approvals"},
  25		Summary: "require N fresh approvals to merge",
  26		Usage:   "repo settings require-approvals <owner/name> <n> (0 = off)", Run: runRequireApprovals})
  27	register(Command{Path: []string{"repo", "settings", "require-resolved"},
  28		Summary: "require all review threads resolved to merge",
  29		Usage:   "repo settings require-resolved <owner/name> on|off", Run: runRequireResolved})
  30	register(Command{Path: []string{"repo", "settings", "require-codeowners"},
  31		Summary: "require an owner's approval for every file CODEOWNERS covers",
  32		Usage:   "repo settings require-codeowners <owner/name> on|off", Run: runRequireCodeowners})
  33	register(Command{Path: []string{"repo", "settings", "require-checks"},
  34		Summary: "gate merges on green statuses",
  35		Usage:   "repo settings require-checks <owner/name> on|off", Run: runRequireChecks})
  36	register(Command{Path: []string{"repo", "settings", "require-mr"},
  37		Summary: "protected branches take changes through merge requests only",
  38		Usage:   "repo settings require-mr <owner/name> on|off", Run: runRequireMR})
  39	register(Command{Path: []string{"repo", "settings", "require-signed"},
  40		Summary: "require verified commit signatures",
  41		Usage:   "repo settings require-signed <owner/name> on|off", Run: runRequireSigned})
  42	register(Command{Path: []string{"mr", "create"},
  43		Summary:    "open a merge request",
  44		Usage:      "mr create <target owner/name> --source [owner/name:]<branch> --target <branch> --title <t> [--body <b> | --file -] [--format md|org] [--draft]",
  45		ReadsStdin: true, Run: runMRCreate})
  46	register(Command{Path: []string{"mr", "range-diff"},
  47		Summary:  "what changed between two revisions of a merge request",
  48		Usage:    "mr range-diff <owner/name> <n> [--from <sha>] [--to <sha>]",
  49		ReadOnly: true, Run: runMRRangeDiff})
  50	register(Command{Path: []string{"mr", "revisions"},
  51		Summary:  "the heads a merge request has had",
  52		Usage:    "mr revisions <owner/name> <n>",
  53		ReadOnly: true, Run: runMRRevisions})
  54	register(Command{Path: []string{"mr", "draft"},
  55		Summary: "mark a merge request as work in progress",
  56		Usage:   "mr draft <owner/name> <n>", Run: runMRDraft})
  57	register(Command{Path: []string{"mr", "ready"},
  58		Summary: "take the draft mark off, so it can merge",
  59		Usage:   "mr ready <owner/name> <n>", Run: runMRReady})
  60	register(Command{Path: []string{"mr", "list"},
  61		Summary: "list merge requests",
  62		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})
  63	register(Command{Path: []string{"mr", "show"},
  64		Summary: "show a merge request",
  65		Usage:   "mr show <owner/name> <n>", ReadOnly: true, Run: runMRShow})
  66	register(Command{Path: []string{"mr", "diff"},
  67		Summary: "show the diff",
  68		Usage:   "mr diff <owner/name> <n>", ReadOnly: true, Run: runMRDiff})
  69	register(Command{Path: []string{"mr", "edit"},
  70		Summary:    "edit title or body",
  71		Usage:      "mr edit <owner/name> <n> [--title <t>] [--body <b> | --file -] [--format md|org] [--superseded-by <m>|none]",
  72		ReadsStdin: true, Run: runMREdit})
  73	register(Command{Path: []string{"mr", "retarget"},
  74		Summary: "retarget onto another branch",
  75		Usage:   "mr retarget <owner/name> <n> <branch>", Run: runMRRetarget})
  76	register(Command{Path: []string{"mr", "comment"},
  77		Summary:    "comment",
  78		Usage:      "mr comment <owner/name> <n> [--message <m> | --file -] [--format md|org]",
  79		ReadsStdin: true, Run: runMRComment})
  80	register(Command{Path: []string{"mr", "review"},
  81		Summary: "review",
  82		Usage:   "mr review <owner/name> <n> --approve|--request-changes|--comment|--discard", Run: runMRReview})
  83	register(Command{Path: []string{"mr", "review", "request"},
  84		Summary: "ask specific people for a review",
  85		Usage:   "mr review request <owner/name> <n> [--add <user>]... [--remove <user>]...", Run: runMRReviewRequest})
  86	register(Command{Path: []string{"mr", "merge"},
  87		Summary: "merge",
  88		Usage:   "mr merge <owner/name> <n> [--strategy ff|merge|squash|rebase]", Run: runMRMerge})
  89	register(Command{Path: []string{"mr", "close"},
  90		Summary: "close without merging",
  91		Usage:   "mr close <owner/name> <n> [--by <m>]", Run: runMRClose})
  92}
  93
  94// ForkOut is what `repo fork` emits: where the fork landed, and what it
  95// came from. Named so the web can send a person to the new repository.
  96type ForkOut struct {
  97	Path   string `json:"path"`
  98	ForkOf string `json:"fork_of"`
  99}
 100
 101func runRepoFork(c *Ctx, args []string) int {
 102	f, err := parseFlags(args, flagSpec{Values: []string{"--name"}, MaxPos: 1, Usage: "repo fork <owner/name> [--name <n>]"})
 103	if err != nil {
 104		return c.fail(protocol.ExitUsage, "%v", err)
 105	}
 106	path, name := f.pos(0), f.Value("--name")
 107	if path == "" {
 108		return c.usage()
 109	}
 110	src, code := resolveRepo(c, path, policy.CanRead)
 111	if code >= 0 {
 112		return code
 113	}
 114	if name == "" {
 115		name = src.Name
 116	}
 117	if err := policy.ValidateName(name); err != nil {
 118		return c.failInput(err)
 119	}
 120	repoCreateMu.Lock()
 121	if code := checkRepoQuota(c); code >= 0 {
 122		repoCreateMu.Unlock()
 123		return code
 124	}
 125	id, err := c.Store.CreateFork("user", c.User.ID, name, src.Visibility, src.ID)
 126	repoCreateMu.Unlock()
 127	if err != nil {
 128		return c.fail(protocol.ExitFailure, "%v", err)
 129	}
 130	dstDir := RepoDir(c.Cfg.Server.Root, c.User.Username, name)
 131	srcDir := RepoDir(c.Cfg.Server.Root, src.OwnerName, src.Name)
 132	if err := gitutil.InitBare(dstDir, "main", HooksDir(c.Cfg.Server.Root)); err != nil {
 133		c.Store.DeleteRepo(id)
 134		return c.fail(protocol.ExitFailure, "%v", err)
 135	}
 136	if desc := gitutil.ReadDescription(srcDir); desc != "" {
 137		gitutil.WriteDescription(dstDir, desc)
 138	}
 139	if err := gitutil.FetchInto(dstDir, srcDir, "refs/heads/*", "refs/heads/*"); err != nil {
 140		// Empty source repos have nothing to fetch; that is fine.
 141		if _, rerr := gitutil.ResolveRef(srcDir, src.DefaultBranch); rerr == nil {
 142			c.Store.DeleteRepo(id)
 143			return c.fail(protocol.ExitFailure, "copying refs: %v", err)
 144		}
 145	}
 146	forkPath := c.User.Username + "/" + name
 147	return c.emit(ForkOut{Path: forkPath, ForkOf: src.Path()}, func(w io.Writer) {
 148		fmt.Fprintf(w, "forked %s to %s\n", src.Path(), forkPath)
 149	})
 150}
 151
 152func runRequireApprovals(c *Ctx, args []string) int {
 153	if len(args) != 2 {
 154		return c.usage()
 155	}
 156	n, err := strconv.Atoi(args[1])
 157	if err != nil || n < 0 || n > 20 {
 158		return c.fail(protocol.ExitUsage, "approvals must be 0..20")
 159	}
 160	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
 161	if code >= 0 {
 162		return code
 163	}
 164	s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.RequireApprovals = n })
 165	if err != nil {
 166		return c.fail(protocol.ExitFailure, "%v", err)
 167	}
 168	return c.emit(s, func(w io.Writer) {
 169		fmt.Fprintf(w, "require_approvals %d on %s\n", n, repo.Path())
 170	})
 171}
 172
 173func runRequireResolved(c *Ctx, args []string) int {
 174	if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
 175		return c.usage()
 176	}
 177	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
 178	if code >= 0 {
 179		return code
 180	}
 181	s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.RequireResolved = args[1] == "on" })
 182	if err != nil {
 183		return c.fail(protocol.ExitFailure, "%v", err)
 184	}
 185	return c.emit(s, func(w io.Writer) {
 186		fmt.Fprintf(w, "require_resolved %s on %s\n", args[1], repo.Path())
 187	})
 188}
 189
 190func runRequireCodeowners(c *Ctx, args []string) int {
 191	if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
 192		return c.usage()
 193	}
 194	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
 195	if code >= 0 {
 196		return code
 197	}
 198	s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.RequireCodeowners = args[1] == "on" })
 199	if err != nil {
 200		return c.fail(protocol.ExitFailure, "%v", err)
 201	}
 202	return c.emit(s, func(w io.Writer) {
 203		fmt.Fprintf(w, "require_codeowners %s on %s\n", args[1], repo.Path())
 204	})
 205}
 206
 207func runRequireChecks(c *Ctx, args []string) int {
 208	if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
 209		return c.usage()
 210	}
 211	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
 212	if code >= 0 {
 213		return code
 214	}
 215	s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.RequireChecks = args[1] == "on" })
 216	if err != nil {
 217		return c.fail(protocol.ExitFailure, "%v", err)
 218	}
 219	return c.emit(s, func(w io.Writer) {
 220		fmt.Fprintf(w, "require_checks %s on %s\n", args[1], repo.Path())
 221	})
 222}
 223
 224func runRequireMR(c *Ctx, args []string) int {
 225	if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
 226		return c.usage()
 227	}
 228	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
 229	if code >= 0 {
 230		return code
 231	}
 232	s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.RequireMR = args[1] == "on" })
 233	if err != nil {
 234		return c.fail(protocol.ExitFailure, "%v", err)
 235	}
 236	return c.emit(s, func(w io.Writer) {
 237		fmt.Fprintf(w, "require_mr %s on %s\n", args[1], repo.Path())
 238	})
 239}
 240
 241func runRequireSigned(c *Ctx, args []string) int {
 242	if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
 243		return c.usage()
 244	}
 245	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
 246	if code >= 0 {
 247		return code
 248	}
 249	s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.RequireSignedCommits = args[1] == "on" })
 250	if err != nil {
 251		return c.fail(protocol.ExitFailure, "%v", err)
 252	}
 253	return c.emit(s, func(w io.Writer) {
 254		fmt.Fprintf(w, "require_signed_commits %s on %s\n", args[1], repo.Path())
 255	})
 256}
 257
 258// mrRef parses "<owner/name> <n>" and loads the MR.
 259func mrRef(c *Ctx, args []string, perm func(store.User, store.Repo, string) bool) (store.Repo, store.MR, int) {
 260	repo, n, code := refArgs(c, args, perm, "MR")
 261	if code >= 0 {
 262		return repo, store.MR{}, code
 263	}
 264	mr, err := c.Store.MRByNumber(repo.ID, n)
 265	if errors.Is(err, store.ErrNotFound) {
 266		return repo, mr, c.fail(protocol.ExitNotFound, "MR !%d not found in %s", n, repo.Path())
 267	}
 268	if err != nil {
 269		return repo, mr, c.fail(protocol.ExitFailure, "%v", err)
 270	}
 271	return repo, mr, -1
 272}
 273
 274func mrHeadRef(n int64) string { return fmt.Sprintf("refs/merge-requests/%d/head", n) }
 275
 276func runMRCreate(c *Ctx, args []string) int {
 277	f, err := parseFlags(args, flagSpec{Values: []string{"--source", "--target", "--title", "--body", "--file", "--format"},
 278		Bools: []string{"--draft"}, MaxPos: 1,
 279		Usage: "mr create <target owner/name> --source [owner/name:]<branch> --target <branch> --title <t> [--draft]"})
 280	if err != nil {
 281		return c.fail(protocol.ExitUsage, "%v", err)
 282	}
 283	path, source, target := f.pos(0), f.Value("--source"), f.Value("--target")
 284	title, body, file, format := f.Value("--title"), f.Value("--body"), f.Value("--file"), f.Value("--format")
 285	if path == "" || source == "" || title == "" {
 286		return c.usage()
 287	}
 288	fmtName, err := markupFormat(format)
 289	if err != nil {
 290		return c.failInput(err)
 291	}
 292	if fmtName == "" {
 293		fmtName = "md"
 294	}
 295	repo, code := resolveRepo(c, path, policy.CanRead)
 296	if code >= 0 {
 297		return code
 298	}
 299	if code := refuseArchived(c, repo); code >= 0 {
 300		return code
 301	}
 302	if target == "" {
 303		target = repo.DefaultBranch
 304	}
 305
 306	// Source is "branch" (same repo) or "owner/name:branch" (a fork).
 307	srcRepo := repo
 308	srcBranch := source
 309	if sp, br, ok := strings.Cut(source, ":"); ok {
 310		srcBranch = br
 311		var scode int
 312		srcRepo, scode = resolveRepo(c, sp, policy.CanRead)
 313		if scode >= 0 {
 314			return scode
 315		}
 316		if srcRepo.ForkOf != repo.ID && srcRepo.ID != repo.ID {
 317			return c.fail(protocol.ExitUsage, "%s is not a fork of %s", srcRepo.Path(), repo.Path())
 318		}
 319	}
 320	srcDir := RepoDir(c.Cfg.Server.Root, srcRepo.OwnerName, srcRepo.Name)
 321	headSHA, err := gitutil.ResolveRef(srcDir, "refs/heads/"+srcBranch)
 322	if err != nil {
 323		return c.fail(protocol.ExitNotFound, "branch %s not found in %s", srcBranch, srcRepo.Path())
 324	}
 325	b, err := bodyFrom(c, body, file)
 326	if err != nil {
 327		return c.failInput(err)
 328	}
 329	n, err := c.Store.CreateMR(repo.ID, c.User.ID, srcRepo.ID, srcBranch, target, title, b, headSHA, fmtName, f.Has("--draft"))
 330	if err != nil {
 331		return c.fail(protocol.ExitFailure, "%v", err)
 332	}
 333	// Fetch the head into the target so the target owns the objects.
 334	dstDir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
 335	if err := gitutil.FetchInto(dstDir, srcDir, headSHA, mrHeadRef(n)); err != nil {
 336		return c.fail(protocol.ExitFailure, "recording MR head: %v", err)
 337	}
 338	if srcRepo.ID != repo.ID {
 339		QueueMRBuilds(c.Store, c.Cfg.Server.Root, c.Cfg.Server.SiteURL, repo, c.User.ID, n, headSHA)
 340	}
 341	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.created", fmt.Sprintf(`{"number":%d}`, n))
 342	if targets, err := c.Store.RepoNotifyTargets(repo); err == nil {
 343		notify(c, targets, notice{repo: repo, kind: "mr",
 344			subject: mrSubject(repo, n, title),
 345			action:  fmt.Sprintf("opened merge request !%d (%s -> %s)", n, source, target),
 346			excerpt: b, path: fmt.Sprintf("%s/mrs/%d", repo.Path(), n)})
 347	}
 348	if created, err := c.Store.MRByNumber(repo.ID, n); err == nil {
 349		notifyMentions(c, repo, mrThread, created.ID, n, title, b)
 350	}
 351	out := MRCreated{Number: n, HeadSHA: headSHA}
 352	if p, ok, err := c.Store.OpenMRBySource(repo.ID, target); err == nil && ok {
 353		out.StackedOn = &stackRef{p.Number, p.Title}
 354	}
 355	return c.emit(out, func(w io.Writer) {
 356		fmt.Fprintf(w, "created %s!%d (%s -> %s)\n", repo.Path(), n, source, target)
 357		if out.StackedOn != nil {
 358			fmt.Fprintf(w, "stacked on !%d %s\n", out.StackedOn.Number, out.StackedOn.Title)
 359		}
 360	})
 361}
 362
 363type mrOut struct {
 364	Number int64  `json:"number"`
 365	Title  string `json:"title"`
 366	State  string `json:"state"`
 367	// Draft is an open merge request not asking to be merged yet.
 368	Draft      bool   `json:"draft,omitempty"`
 369	Author     string `json:"author"`
 370	Source     string `json:"source"` // owner/name:branch, or branch, "" if gone
 371	TargetRef  string `json:"target_ref"`
 372	HeadSHA    string `json:"head_sha"`
 373	Body       string `json:"body,omitempty"`
 374	BodyFormat string `json:"body_format,omitempty"`
 375	Milestone  string `json:"milestone,omitempty"`
 376	// ReviewRequests is who has been asked, directly, for a review.
 377	ReviewRequests []string `json:"review_requests,omitempty"`
 378	// StackedOn is the open merge request whose source branch this one
 379	// targets; Stacked are the open ones targeting this one's source.
 380	StackedOn *stackRef  `json:"stacked_on,omitempty"`
 381	Stacked   []stackRef `json:"stacked,omitempty"`
 382	CreatedAt string     `json:"created_at"`
 383	MergedAt  string     `json:"merged_at,omitempty"`
 384	MergedBy  string     `json:"merged_by,omitempty"`
 385	ClosedAt  string     `json:"closed_at,omitempty"`
 386	ClosedBy  string     `json:"closed_by,omitempty"`
 387	// SupersededBy is the merge request, by number, this one was closed
 388	// in favour of. 0 means none.
 389	SupersededBy int64 `json:"superseded_by,omitempty"`
 390}
 391
 392type stackRef struct {
 393	Number int64  `json:"number"`
 394	Title  string `json:"title"`
 395}
 396
 397// stackOf derives the stack around m: the open merge request whose source
 398// branch m targets, and the open ones targeting m's source. Both only
 399// within m's repository; a fork's branch is not a target anything can
 400// stack on.
 401func stackOf(c *Ctx, repo store.Repo, m store.MR) (*stackRef, []stackRef) {
 402	if m.State != "open" {
 403		return nil, nil
 404	}
 405	var parent *stackRef
 406	if p, ok, err := c.Store.OpenMRBySource(repo.ID, m.TargetRef); err == nil && ok && p.ID != m.ID {
 407		parent = &stackRef{p.Number, p.Title}
 408	}
 409	var children []stackRef
 410	if m.SourceRepoID == repo.ID {
 411		if kids, err := c.Store.OpenMRsByTarget(repo.ID, m.SourceRef); err == nil {
 412			for _, k := range kids {
 413				if k.ID != m.ID {
 414					children = append(children, stackRef{k.Number, k.Title})
 415				}
 416			}
 417		}
 418	}
 419	return parent, children
 420}
 421
 422func mrToOut(repo store.Repo, m store.MR, withBody bool) mrOut {
 423	src := ""
 424	if m.SourcePath != "" {
 425		if m.SourceRepoID == repo.ID {
 426			src = m.SourceRef
 427		} else {
 428			src = m.SourcePath + ":" + m.SourceRef
 429		}
 430	}
 431	o := mrOut{Number: m.Number, Title: m.Title, State: m.State, Draft: m.Draft, Author: m.Author,
 432		Source: src, TargetRef: m.TargetRef, HeadSHA: m.HeadSHA, Milestone: m.Milestone,
 433		ReviewRequests: m.ReviewRequests,
 434		CreatedAt:      m.CreatedAt, MergedAt: m.MergedAt, MergedBy: m.MergedBy,
 435		ClosedAt: m.ClosedAt, ClosedBy: m.ClosedBy, SupersededBy: m.SupersededBy}
 436	if withBody {
 437		o.Body = m.Body
 438		o.BodyFormat = m.BodyFormat
 439	}
 440	return o
 441}
 442
 443func runMRList(c *Ctx, args []string) int {
 444	args, p, code := parsePageFlags(c, args, "mr", true)
 445	if code >= 0 {
 446		return code
 447	}
 448	f := store.MRFilter{State: "open"}
 449	fl, err := parseFlags(args, flagSpec{Values: []string{"--state", "--author", "--milestone", "--search"}, MaxPos: 1, Usage: c.Cmd.Usage})
 450	if err != nil {
 451		return c.fail(protocol.ExitUsage, "%v", err)
 452	}
 453	path := fl.pos(0)
 454	if fl.Has("--state") {
 455		f.State = fl.Value("--state")
 456	}
 457	f.Author, f.Milestone = fl.Value("--author"), fl.Value("--milestone")
 458	f.Search = fl.Value("--search")
 459	if fl.Has("--search") {
 460		if err := validQuery(f.Search); err != nil {
 461			return c.failInput(err)
 462		}
 463	}
 464	valid := map[string]bool{"open": true, "merged": true, "closed": true, "source_gone": true, "all": true}
 465	if path == "" || !valid[f.State] {
 466		return c.usage()
 467	}
 468	repo, code := resolveRepo(c, path, policy.CanRead)
 469	if code >= 0 {
 470		return code
 471	}
 472	f.Limit, f.Before = p.queryLimit(), p.keyInt()
 473	mrs, err := c.Store.QueryMRs(repo.ID, f)
 474	if err != nil {
 475		return c.fail(protocol.ExitFailure, "%v", err)
 476	}
 477	mrs, next := trimPage(p, mrs, "mr", func(m store.MR) string {
 478		return strconv.FormatInt(m.Number, 10)
 479	})
 480	var ds []mrOut
 481	for _, m := range mrs {
 482		o := mrToOut(repo, m, false)
 483		o.StackedOn, _ = stackOf(c, repo, m)
 484		ds = append(ds, o)
 485	}
 486	return c.emitPage(p, ds, next, func(w io.Writer) {
 487		for _, d := range ds {
 488			stacked := ""
 489			if d.StackedOn != nil {
 490				stacked = fmt.Sprintf("\tstacked on !%d", d.StackedOn.Number)
 491			}
 492			state := d.State
 493			if d.Draft {
 494				state = "draft"
 495			}
 496			fmt.Fprintf(w, "!%d\t%s\t%s\t%s -> %s%s\n", d.Number, state, d.Title, d.Source, d.TargetRef, stacked)
 497		}
 498	})
 499}
 500
 501// byWhom renders " by <user>", or nothing when the actor is unknown — an
 502// imported merge request carries a time but no local account.
 503func byWhom(user string) string {
 504	if user == "" {
 505		return ""
 506	}
 507	return " by " + user
 508}
 509
 510func runMRShow(c *Ctx, args []string) int {
 511	repo, mr, code := mrRef(c, args, policy.CanRead)
 512	if code >= 0 {
 513		return code
 514	}
 515	if len(args) != 2 {
 516		return c.usage()
 517	}
 518	comments, err := c.Store.ListMRComments(mr.ID)
 519	if err != nil {
 520		return c.fail(protocol.ExitFailure, "%v", err)
 521	}
 522	reviews, err := c.Store.ListMRReviews(mr.ID)
 523	if err != nil {
 524		return c.fail(protocol.ExitFailure, "%v", err)
 525	}
 526	statuses, combined, err := c.Store.ChecksForCommit(repo.ID, mr.HeadSHA)
 527	if err != nil {
 528		return c.fail(protocol.ExitFailure, "%v", err)
 529	}
 530	unresolved, err := c.Store.UnresolvedThreadCount(mr.ID)
 531	if err != nil {
 532		return c.fail(protocol.ExitFailure, "%v", err)
 533	}
 534	var checks []CheckOut
 535	for _, st := range statuses {
 536		out := CheckOut{Context: st.Context, State: st.State, URL: st.TargetURL, UpdatedAt: st.UpdatedAt}
 537		if st.Duration > 0 {
 538			out.Duration = st.Duration.String()
 539		}
 540		checks = append(checks, out)
 541	}
 542	var cs []commentOut
 543	for _, cm := range comments {
 544		cs = append(cs, commentOut{cm.Author, cm.Body, cm.BodyFormat, cm.CreatedAt})
 545	}
 546	var rs []ReviewOut
 547	counts := ReviewersWhoCount(c.Store, repo, reviews)
 548	for _, r := range reviews {
 549		rs = append(rs, ReviewOut{r.Reviewer, r.Verdict, r.Stale, counts[r.Reviewer], r.CreatedAt})
 550	}
 551	// The commits this MR carries: base..head, the diff's range.
 552	var commits []CommitOut
 553	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
 554	base := mr.MergedBase
 555	if base == "" {
 556		if b, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, mrHeadRef(mr.Number)); err == nil {
 557			base = b
 558		}
 559	}
 560	if base != "" {
 561		if shas, err := gitutil.RevListRange(dir, base, mrHeadRef(mr.Number)); err == nil {
 562			for _, sha := range shas {
 563				subject := ""
 564				if raw, err := gitutil.ReadCommit(dir, sha); err == nil {
 565					if parsed, err := sig.ParseCommit(raw); err == nil {
 566						subject = parsed.Subject
 567					}
 568				}
 569				commits = append(commits, CommitOut{sha, subject})
 570			}
 571		}
 572	}
 573	d := MRShow{mrOut: mrToOut(repo, mr, true), Checks: checks, Combined: combined,
 574		UnresolvedThreads: unresolved, Commits: commits, Comments: cs, Reviews: rs}
 575	d.StackedOn, d.Stacked = stackOf(c, repo, mr)
 576	if mr.State == "open" || mr.State == "source_gone" {
 577		if targetSHA, err := gitutil.ResolveRef(dir, "refs/heads/"+mr.TargetRef); err == nil {
 578			if g, err := MergeGates(c.Store, repo, mr, dir, targetSHA, mr.HeadSHA); err == nil {
 579				d.Gates = &g
 580			}
 581		}
 582	}
 583	return c.emit(d, func(w io.Writer) {
 584		state := d.State
 585		if d.Draft {
 586			state = "draft"
 587		}
 588		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)
 589		if len(d.ReviewRequests) > 0 {
 590			fmt.Fprintf(w, "reviewers: %s\n", strings.Join(d.ReviewRequests, ", "))
 591		}
 592		if d.StackedOn != nil {
 593			fmt.Fprintf(w, "stacked on !%d %s\n", d.StackedOn.Number, d.StackedOn.Title)
 594		}
 595		for _, k := range d.Stacked {
 596			fmt.Fprintf(w, "stacked: !%d %s\n", k.Number, k.Title)
 597		}
 598		if d.MergedAt != "" {
 599			fmt.Fprintf(w, "merged %s%s\n", d.MergedAt, byWhom(d.MergedBy))
 600		}
 601		if d.ClosedAt != "" {
 602			fmt.Fprintf(w, "closed %s%s\n", d.ClosedAt, byWhom(d.ClosedBy))
 603		}
 604		if d.SupersededBy != 0 {
 605			fmt.Fprintf(w, "superseded by: !%d\n", d.SupersededBy)
 606		}
 607		if d.Body != "" {
 608			fmt.Fprintf(w, "\n%s\n", d.Body)
 609		}
 610		for _, cm := range commits {
 611			fmt.Fprintf(w, "commit: %.10s %s\n", cm.SHA, cm.Subject)
 612		}
 613		for _, x := range checks {
 614			dur := ""
 615			if x.Duration != "" {
 616				dur = " in " + x.Duration
 617			}
 618			fmt.Fprintf(w, "check: %s %s at %s%s\n", x.Context, x.State, x.UpdatedAt, dur)
 619		}
 620		if d.UnresolvedThreads > 0 {
 621			fmt.Fprintf(w, "unresolved threads: %d\n", d.UnresolvedThreads)
 622		}
 623		if g := d.Gates; g != nil {
 624			ff := "fast-forward possible"
 625			if !g.FastForward {
 626				ff = "fast-forward not possible"
 627			}
 628			if len(g.Unmet) == 0 {
 629				fmt.Fprintf(w, "gates: met; %s\n", ff)
 630			} else {
 631				fmt.Fprintf(w, "gates: %d unmet; %s\n", len(g.Unmet), ff)
 632				for _, u := range g.Unmet {
 633					fmt.Fprintf(w, "gate: %s\n", u)
 634				}
 635			}
 636		}
 637		for _, r := range rs {
 638			stale := ""
 639			if r.Stale {
 640				stale = " (stale)"
 641			}
 642			advisory := ""
 643			if !r.Counts {
 644				advisory = " (advisory: no write access)"
 645			}
 646			fmt.Fprintf(w, "review: %s %s%s%s at %s\n", r.Reviewer, r.Verdict, stale, advisory, r.CreatedAt)
 647		}
 648		for _, cm := range cs {
 649			fmt.Fprintf(w, "\n--- %s at %s\n%s\n", cm.Author, cm.CreatedAt, cm.Body)
 650		}
 651	})
 652}
 653
 654func runMRDiff(c *Ctx, args []string) int {
 655	repo, mr, code := mrRef(c, args, policy.CanRead)
 656	if code >= 0 {
 657		return code
 658	}
 659	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
 660	head := mrHeadRef(mr.Number)
 661	if _, err := gitutil.ResolveRef(dir, head); err != nil {
 662		return c.fail(protocol.ExitFailure, "the head of !%d is no longer in the repository; its diff is not available", mr.Number)
 663	}
 664	// After a merge (especially fast-forward) the live merge-base equals
 665	// the head and the diff would vanish; use the recorded base instead.
 666	base := mr.MergedBase
 667	if base == "" {
 668		b, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, head)
 669		if err != nil {
 670			return c.fail(protocol.ExitFailure, "%v", err)
 671		}
 672		base = b
 673	}
 674	patch, truncated, err := gitutil.Diff(dir, base, head, 4<<20)
 675	if err != nil {
 676		return c.fail(protocol.ExitFailure, "%v", err)
 677	}
 678	fmt.Fprint(c.Stdout, patch)
 679	if truncated {
 680		fmt.Fprintln(c.Stderr, "diff truncated at 4 MiB; fetch the branch for the rest")
 681	}
 682	return protocol.ExitOK
 683}
 684
 685func runMREdit(c *Ctx, args []string) int {
 686	rest, title, body, format, fl, code := editText(c, args, "mr", "--superseded-by")
 687	if code >= 0 {
 688		return code
 689	}
 690	repo, mr, code := mrRef(c, rest, policy.CanRead)
 691	if code >= 0 {
 692		return code
 693	}
 694	if code := refuseArchived(c, repo); code >= 0 {
 695		return code
 696	}
 697	if code := authorOrWrite(c, repo, mr.Author, "edit this merge request"); code >= 0 {
 698		return code
 699	}
 700	var clearSuperseded bool
 701	var supersededBy int64
 702	if fl.Has("--superseded-by") {
 703		if mr.State != "closed" {
 704			return c.fail(protocol.ExitUsage, "only a closed merge request can be superseded")
 705		}
 706		if v := fl.Value("--superseded-by"); v == "none" {
 707			clearSuperseded = true
 708		} else {
 709			supersededBy, code = resolveSupersededBy(c, repo, mr.Number, v)
 710			if code >= 0 {
 711				return code
 712			}
 713		}
 714	}
 715	if err := c.Store.UpdateMRText(mr.ID, title, body, format); err != nil {
 716		return c.fail(protocol.ExitFailure, "%v", err)
 717	}
 718	if clearSuperseded {
 719		if err := c.Store.SetSupersededBy(mr.ID, 0); err != nil {
 720			return c.fail(protocol.ExitFailure, "%v", err)
 721		}
 722	} else if supersededBy != 0 {
 723		if err := c.Store.SetSupersededBy(mr.ID, supersededBy); err != nil {
 724			return c.fail(protocol.ExitFailure, "%v", err)
 725		}
 726	}
 727	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.edited", fmt.Sprintf(`{"number":%d}`, mr.Number))
 728	return c.emit(map[string]any{"number": mr.Number}, func(w io.Writer) {
 729		fmt.Fprintf(w, "edited %s!%d\n", repo.Path(), mr.Number)
 730	})
 731}
 732
 733// runMRRetarget moves an open merge request onto another branch of the
 734// same repository.
 735func runMRRetarget(c *Ctx, args []string) int {
 736	if len(args) != 3 {
 737		return c.usage()
 738	}
 739	repo, mr, code := mrRef(c, args[:2], policy.CanRead)
 740	if code >= 0 {
 741		return code
 742	}
 743	if code := refuseArchived(c, repo); code >= 0 {
 744		return code
 745	}
 746	if code := authorOrWrite(c, repo, mr.Author, "retarget this merge request"); code >= 0 {
 747		return code
 748	}
 749	if mr.State == "merged" || mr.State == "closed" {
 750		return c.fail(protocol.ExitUsage, "!%d is %s; only an open merge request can be retargeted", mr.Number, mr.State)
 751	}
 752	target := args[2]
 753	if target == mr.TargetRef {
 754		return c.fail(protocol.ExitUsage, "!%d already targets %s", mr.Number, target)
 755	}
 756	if mr.SourceRepoID == repo.ID && target == mr.SourceRef {
 757		return c.fail(protocol.ExitUsage, "%s is the source branch of !%d", target, mr.Number)
 758	}
 759	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
 760	if _, err := gitutil.ResolveRef(dir, "refs/heads/"+target); err != nil {
 761		return c.fail(protocol.ExitNotFound, "branch %s not found in %s", target, repo.Path())
 762	}
 763	// The diff, the commit list and the merge gates all derive their base
 764	// from the target on every read, so the only thing to check here is
 765	// that a base exists at all: without one there is nothing to show and
 766	// nothing to merge.
 767	base, err := gitutil.MergeBase(dir, "refs/heads/"+target, mrHeadRef(mr.Number))
 768	if err != nil || base == "" {
 769		return c.fail(protocol.ExitUsage, "%s shares no history with the head of !%d", target, mr.Number)
 770	}
 771	old := mr.TargetRef
 772	if err := c.Store.SetMRTarget(mr.ID, target); err != nil {
 773		return c.fail(protocol.ExitFailure, "%v", err)
 774	}
 775	c.Store.AddMRSystemComment(mr.ID, c.User.ID, fmt.Sprintf("retargeted from %s to %s", old, target))
 776	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.retargeted",
 777		fmt.Sprintf(`{"number":%d,"from":%q,"to":%q}`, mr.Number, old, target))
 778	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
 779		notify(c, parts, notice{repo: repo, kind: "mr",
 780			subject: mrSubject(repo, mr.Number, mr.Title),
 781			action:  fmt.Sprintf("retargeted !%d from %s to %s", mr.Number, old, target),
 782			path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
 783	}
 784	return c.emit(map[string]any{"number": mr.Number, "target_ref": target, "merge_base": base}, func(w io.Writer) {
 785		fmt.Fprintf(w, "retargeted %s!%d from %s to %s (base %.10s)\n", repo.Path(), mr.Number, old, target, base)
 786	})
 787}
 788
 789func runMRComment(c *Ctx, args []string) int {
 790	return runComment(c, args, mrThread, "mr",
 791		func(rest []string) (store.Repo, int64, int64, string, int) {
 792			repo, mr, code := mrRef(c, rest, policy.CanRead)
 793			return repo, mr.ID, mr.Number, mr.Title, code
 794		},
 795		c.Store.AddMRComment, c.Store.MRParticipants)
 796}
 797
 798func runMRReview(c *Ctx, args []string) int {
 799	verdict, discard := "", false
 800	var rest []string
 801	for _, a := range args {
 802		switch a {
 803		case "--approve":
 804			verdict = "approve"
 805		case "--request-changes":
 806			verdict = "request_changes"
 807		case "--comment":
 808			verdict = "comment"
 809		case "--discard":
 810			discard = true
 811		default:
 812			rest = append(rest, a)
 813		}
 814	}
 815	if discard && verdict != "" {
 816		return c.fail(protocol.ExitUsage, "--discard throws the batch away; it takes no verdict")
 817	}
 818	if verdict == "" && !discard {
 819		return c.usage()
 820	}
 821	repo, mr, code := mrRef(c, rest, policy.CanRead)
 822	if code >= 0 {
 823		return code
 824	}
 825	if code := refuseArchived(c, repo); code >= 0 {
 826		return code
 827	}
 828	if mr.State != "open" {
 829		return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
 830	}
 831	// Throwing the batch away is not a review, so it stops here: no
 832	// verdict, no event, nobody told about comments nobody ever saw.
 833	if discard {
 834		n, err := c.Store.DiscardPendingComments(mr.ID, c.User.ID)
 835		if err != nil {
 836			return c.fail(protocol.ExitFailure, "%v", err)
 837		}
 838		return c.emit(map[string]any{"number": mr.Number, "discarded": n}, func(w io.Writer) {
 839			fmt.Fprintf(w, "discarded %d pending comment(s) on %s!%d\n", n, repo.Path(), mr.Number)
 840		})
 841	}
 842	if err := c.Store.AddMRReview(mr.ID, c.User.ID, verdict, mr.HeadSHA); err != nil {
 843		return c.fail(protocol.ExitFailure, "%v", err)
 844	}
 845	// The batch the reviewer composed becomes visible with the verdict,
 846	// which is what makes it one review rather than a trickle.
 847	published, err := c.Store.PublishPendingComments(mr.ID, c.User.ID)
 848	if err != nil {
 849		return c.fail(protocol.ExitFailure, "%v", err)
 850	}
 851	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.reviewed",
 852		fmt.Sprintf(`{"number":%d,"verdict":%q}`, mr.Number, verdict))
 853	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
 854		notify(c, parts, notice{repo: repo, kind: "mr",
 855			subject: mrSubject(repo, mr.Number, mr.Title),
 856			action:  reviewAction(mr.Number, verdict, published),
 857			path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
 858	}
 859	// Whether the merge gates will count this verdict, said now rather
 860	// than at the refusal (#199).
 861	counts := ReviewersWhoCount(c.Store, repo, []store.MRReview{{Reviewer: c.User.Username}})[c.User.Username]
 862	return c.emit(map[string]any{"number": mr.Number, "verdict": verdict, "published": published, "counts": counts}, func(w io.Writer) {
 863		fmt.Fprintf(w, "reviewed %s!%d: %s", repo.Path(), mr.Number, verdict)
 864		if published > 0 {
 865			fmt.Fprintf(w, " (%d comment(s))", published)
 866		}
 867		if !counts {
 868			fmt.Fprintf(w, " (advisory: no write access on %s, so the merge gates do not count it)", repo.Path())
 869		}
 870		fmt.Fprintln(w)
 871	})
 872}
 873
 874// runMRReviewRequest is issue assign's counterpart for merge requests: it
 875// pushes a merge request into a specific person's review queue and inbox
 876// directly, rather than waiting for them to be otherwise involved (#145).
 877func runMRReviewRequest(c *Ctx, args []string) int {
 878	rest, adds, removes, err := addRemoveFlags(args)
 879	if err != nil {
 880		return c.failInput(err)
 881	}
 882	if len(adds)+len(removes) == 0 {
 883		return c.usage()
 884	}
 885	repo, mr, code := mrRef(c, rest, policy.CanWrite)
 886	if code >= 0 {
 887		return code
 888	}
 889	if code := refuseArchived(c, repo); code >= 0 {
 890		return code
 891	}
 892	resolve := func(name string) (store.User, int) {
 893		u, err := c.Store.UserByUsername(name)
 894		if errors.Is(err, store.ErrNotFound) {
 895			return u, c.fail(protocol.ExitNotFound, "no such user %q", name)
 896		}
 897		if err != nil {
 898			return u, c.fail(protocol.ExitFailure, "%v", err)
 899		}
 900		return u, -1
 901	}
 902	// Notified on every return, not just success: a name later in --add
 903	// that fails to resolve or lacks access must not silence the people
 904	// already added earlier in the same call.
 905	var added []store.User
 906	defer func() {
 907		if len(added) == 0 {
 908			return
 909		}
 910		ids := make([]int64, len(added))
 911		for i, u := range added {
 912			ids[i] = u.ID
 913		}
 914		notify(c, ids, notice{repo: repo, kind: "mr",
 915			subject: mrSubject(repo, mr.Number, mr.Title),
 916			action:  fmt.Sprintf("asked for a review on !%d", mr.Number),
 917			path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
 918	}()
 919	for _, name := range adds {
 920		u, code := resolve(name)
 921		if code >= 0 {
 922			return code
 923		}
 924		// A review request that lands nowhere the recipient can see it is
 925		// worse than useless: it looks like the ask went through.
 926		grant, err := c.Store.AccessRole(repo.ID, u.ID)
 927		if err != nil {
 928			return c.fail(protocol.ExitFailure, "%v", err)
 929		}
 930		if !policy.CanRead(u, repo, grant) {
 931			return c.fail(protocol.ExitDenied, "%s cannot read %s", name, repo.Path())
 932		}
 933		if err := c.Store.SetMRReviewRequest(mr.ID, u.ID, true); err != nil {
 934			return c.fail(protocol.ExitFailure, "%v", err)
 935		}
 936		added = append(added, u)
 937	}
 938	for _, name := range removes {
 939		u, code := resolve(name)
 940		if code >= 0 {
 941			return code
 942		}
 943		if err := c.Store.SetMRReviewRequest(mr.ID, u.ID, false); err != nil {
 944			if errors.Is(err, store.ErrNotFound) {
 945				return c.fail(protocol.ExitNotFound, "%s is not a requested reviewer", name)
 946			}
 947			return c.fail(protocol.ExitFailure, "%v", err)
 948		}
 949	}
 950	updated, err := c.Store.MRByNumber(repo.ID, mr.Number)
 951	if err != nil {
 952		return c.fail(protocol.ExitFailure, "%v", err)
 953	}
 954	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.review_requested",
 955		fmt.Sprintf(`{"number":%d,"reviewers":%s}`, mr.Number, jsonStrings(updated.ReviewRequests)))
 956	return c.emit(map[string]any{"number": mr.Number, "reviewers": updated.ReviewRequests}, func(w io.Writer) {
 957		fmt.Fprintf(w, "requested reviewers on %s!%d: %s\n", repo.Path(), mr.Number, strings.Join(updated.ReviewRequests, ", "))
 958	})
 959}
 960
 961func runMRMerge(c *Ctx, args []string) int {
 962	f, err := parseFlags(args, flagSpec{Values: []string{"--strategy"}, MaxPos: -1, Usage: "mr merge <owner/name> <n> [--strategy ff|merge|squash|rebase]"})
 963	if err != nil {
 964		return c.fail(protocol.ExitUsage, "%v", err)
 965	}
 966	strategy, rest := f.Value("--strategy"), f.Pos
 967	valid := map[string]bool{"": true, "ff": true, "merge": true, "squash": true, "rebase": true}
 968	if !valid[strategy] {
 969		return c.fail(protocol.ExitUsage, "--strategy must be ff, merge, squash, or rebase")
 970	}
 971	repo, mr, code := mrRef(c, rest, policy.CanWrite)
 972	if code >= 0 {
 973		return code
 974	}
 975	if code := refuseArchived(c, repo); code >= 0 {
 976		return code
 977	}
 978	if mr.State != "open" && mr.State != "source_gone" {
 979		return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
 980	}
 981
 982	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
 983	targetRef := "refs/heads/" + mr.TargetRef
 984	targetSHA, err := gitutil.ResolveRef(dir, targetRef)
 985	if err != nil {
 986		return c.fail(protocol.ExitFailure, "target branch %s: %v", mr.TargetRef, err)
 987	}
 988	headSHA, err := gitutil.ResolveRef(dir, mrHeadRef(mr.Number))
 989	if err != nil {
 990		return c.fail(protocol.ExitFailure, "MR head ref: %v", err)
 991	}
 992
 993	// Merge gates: draft, checks, approvals, CODEOWNERS, resolved threads,
 994	// all reported at once.
 995	if code := c.reviewGates(repo, mr, dir, targetSHA, headSHA); code >= 0 {
 996		return code
 997	}
 998
 999	upToDate, err := gitutil.IsAncestor(dir, headSHA, targetSHA)
1000	if err != nil {
1001		return c.fail(protocol.ExitFailure, "%v", err)
1002	}
1003	if upToDate {
1004		// The head is already on the target: merged by hand and pushed, or
1005		// a merge whose ref update landed and whose record did not. Record
1006		// it rather than refuse, so a merge request cannot be stuck open
1007		// with no way to close it as merged (#108).
1008		if err := c.Store.MarkMerged(mr.ID, targetSHA, c.User.ID, ""); err != nil {
1009			return c.fail(protocol.ExitFailure, "%v", err)
1010		}
1011		c.Store.RecordEvent(repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d}`, mr.Number))
1012		return c.emit(map[string]any{"number": mr.Number, "strategy": "recorded", "sha": headSHA}, func(w io.Writer) {
1013			fmt.Fprintf(w, "%s already contains !%d; recorded as merged at %.10s\n", mr.TargetRef, mr.Number, headSHA)
1014		})
1015	}
1016	ffPossible, err := gitutil.IsAncestor(dir, targetSHA, headSHA)
1017	if err != nil {
1018		return c.fail(protocol.ExitFailure, "%v", err)
1019	}
1020
1021	// Signature policy matrix: with require_signed_commits, only
1022	// fast-forward is allowed — squash, rebase-replay, and merge commits
1023	// are all server-created and unsigned, violating the branch's own
1024	// policy — and every landed commit must be verified. An explicit
1025	// rebase when fast-forward is already possible IS a fast-forward
1026	// (nothing is rewritten), so it stays legal.
1027	if repo.Settings.RequireSignedCommits {
1028		if strategy == "merge" || strategy == "squash" || !ffPossible {
1029			return c.fail(protocol.ExitDenied,
1030				"%s requires signed commits, so only fast-forward merges are allowed; rebase %s onto %s locally, re-push, and merge again",
1031				repo.Path(), mr.SourceRef, mr.TargetRef)
1032		}
1033		strategy = "ff"
1034		commits, err := gitutil.RevListRange(dir, targetSHA, headSHA)
1035		if err != nil {
1036			return c.fail(protocol.ExitFailure, "%v", err)
1037		}
1038		for _, sha := range commits {
1039			raw, err := gitutil.ReadCommit(dir, sha)
1040			if err != nil {
1041				return c.fail(protocol.ExitFailure, "%v", err)
1042			}
1043			parsed, err := sigParse(raw)
1044			if err != nil {
1045				return c.fail(protocol.ExitFailure, "%v", err)
1046			}
1047			res, err := VerifyCommitCached(c.Store, repo, parsed, sha)
1048			if err != nil {
1049				return c.fail(protocol.ExitFailure, "%v", err)
1050			}
1051			if res.State != "verified" {
1052				return c.fail(protocol.ExitDenied,
1053					"%s requires signed commits: %.10s is %s", repo.Path(), sha, res.State)
1054			}
1055		}
1056	}
1057	if strategy == "" {
1058		if ffPossible {
1059			strategy = "ff"
1060		} else {
1061			strategy = "merge"
1062		}
1063	}
1064	if strategy == "rebase" && ffPossible {
1065		// Nothing to rewrite: a rebase onto an ancestor is a fast-forward,
1066		// and taking it keeps the original commits and their signatures.
1067		strategy = "ff"
1068	}
1069
1070	// Every server-created commit needs the merger's verified identity.
1071	mergerEmail := ""
1072	if strategy != "ff" {
1073		email, err := c.Store.PrimaryVerifiedEmail(c.User.ID)
1074		if err != nil {
1075			return c.fail(protocol.ExitFailure, "%v", err)
1076		}
1077		if email == "" {
1078			return c.fail(protocol.ExitDenied,
1079				"%s merges create commits carrying your identity: verify a primary email first (or use a fast-forward merge)", strategy)
1080		}
1081		mergerEmail = email
1082	}
1083
1084	var newSHA string
1085	switch strategy {
1086	case "ff":
1087		if !ffPossible {
1088			return c.fail(protocol.ExitUsage,
1089				"fast-forward not possible: %s has diverged from the MR head; merge with the merge strategy, or rebase and push again", mr.TargetRef)
1090		}
1091		newSHA = headSHA
1092
1093	case "merge":
1094		tree, conflict, err := gitutil.MergeTree(dir, targetSHA, headSHA)
1095		if err != nil {
1096			return c.fail(protocol.ExitFailure, "%v", err)
1097		}
1098		if conflict {
1099			return c.fail(protocol.ExitUsage,
1100				"merge conflicts between %s and the MR head; resolve locally and re-push", mr.TargetRef)
1101		}
1102		msg := fmt.Sprintf("Merge request !%d: %s\n\nMerged %s into %s", mr.Number, mr.Title, mr.SourceRef, mr.TargetRef)
1103		newSHA, err = gitutil.CommitTree(dir, tree, []string{targetSHA, headSHA}, c.User.Username, mergerEmail, msg)
1104		if err != nil {
1105			return c.fail(protocol.ExitFailure, "%v", err)
1106		}
1107
1108	case "squash":
1109		// One new commit with the merged tree. Authorship credit goes to
1110		// the MR author (their verified identity when they have one); the
1111		// committer is the merger.
1112		tree := ""
1113		if ffPossible {
1114			t, err := gitutil.ResolveTree(dir, headSHA)
1115			if err != nil {
1116				return c.fail(protocol.ExitFailure, "%v", err)
1117			}
1118			tree = t
1119		} else {
1120			t, conflict, err := gitutil.MergeTree(dir, targetSHA, headSHA)
1121			if err != nil {
1122				return c.fail(protocol.ExitFailure, "%v", err)
1123			}
1124			if conflict {
1125				return c.fail(protocol.ExitUsage,
1126					"merge conflicts between %s and the MR head; resolve locally and re-push", mr.TargetRef)
1127			}
1128			tree = t
1129		}
1130		authorName, authorEmail := c.User.Username, mergerEmail
1131		if author, err := c.Store.UserByUsername(mr.Author); err == nil {
1132			if ae, err := c.Store.PrimaryVerifiedEmail(author.ID); err == nil && ae != "" {
1133				authorName, authorEmail = author.Username, ae
1134			}
1135		}
1136		msg := fmt.Sprintf("%s (!%d)", mr.Title, mr.Number)
1137		if mr.Body != "" {
1138			msg += "\n\n" + mr.Body
1139		}
1140		var err error
1141		newSHA, err = gitutil.CommitTreeIdent(dir, tree, []string{targetSHA},
1142			authorName, authorEmail, "", c.User.Username, mergerEmail, msg)
1143		if err != nil {
1144			return c.fail(protocol.ExitFailure, "%v", err)
1145		}
1146
1147	case "rebase":
1148		commits, err := gitutil.RevListRange(dir, targetSHA, headSHA)
1149		if err != nil {
1150			return c.fail(protocol.ExitFailure, "%v", err)
1151		}
1152		// Oldest first.
1153		for i, j := 0, len(commits)-1; i < j; i, j = i+1, j-1 {
1154			commits[i], commits[j] = commits[j], commits[i]
1155		}
1156		onto := targetSHA
1157		for _, sha := range commits {
1158			parents, err := gitutil.CommitParents(dir, sha)
1159			if err != nil {
1160				return c.fail(protocol.ExitFailure, "%v", err)
1161			}
1162			if len(parents) > 1 {
1163				return c.fail(protocol.ExitUsage,
1164					"the MR contains merge commit %.10s; a rebase merge needs linear history — choose the merge or squash strategy", sha)
1165			}
1166			base := onto // root commit: replay against the new tip itself
1167			if len(parents) == 1 {
1168				base = parents[0]
1169			}
1170			tree, conflict, err := gitutil.MergeTreeOnto(dir, base, onto, sha)
1171			if err != nil {
1172				return c.fail(protocol.ExitFailure, "%v", err)
1173			}
1174			if conflict {
1175				return c.fail(protocol.ExitUsage,
1176					"commit %.10s does not apply cleanly onto %s; rebase locally and re-push", sha, mr.TargetRef)
1177			}
1178			aName, aEmail, aDate, err := gitutil.AuthorIdent(dir, sha)
1179			if err != nil {
1180				return c.fail(protocol.ExitFailure, "%v", err)
1181			}
1182			msg, err := gitutil.CommitMessage(dir, sha)
1183			if err != nil {
1184				return c.fail(protocol.ExitFailure, "%v", err)
1185			}
1186			onto, err = gitutil.CommitTreeIdent(dir, tree, []string{onto},
1187				aName, aEmail, aDate, c.User.Username, mergerEmail, msg)
1188			if err != nil {
1189				return c.fail(protocol.ExitFailure, "%v", err)
1190			}
1191		}
1192		newSHA = onto
1193	}
1194
1195	// A stacked merge request's diff is against this branch. After a
1196	// fast-forward or merge commit the same commits are on the target and
1197	// its diff is unchanged there; after a squash or rebase they are not,
1198	// and the stack would carry this merge request's changes a second
1199	// time. Refuse rather than leave the stack wrong.
1200	var stack []store.MR
1201	if mr.SourceRepoID == repo.ID {
1202		stack, _ = c.Store.OpenMRsByTarget(repo.ID, mr.SourceRef)
1203	}
1204	if len(stack) > 0 && (strategy == "squash" || strategy == "rebase") {
1205		var nums []string
1206		for _, k := range stack {
1207			nums = append(nums, fmt.Sprintf("!%d", k.Number))
1208		}
1209		return c.fail(protocol.ExitUsage,
1210			"%s is stacked on by %s; a %s merge rewrites the commits they build on. Merge with the fast-forward or merge strategy, or merge the stack into %s first",
1211			fmt.Sprintf("!%d", mr.Number), strings.Join(nums, ", "), strategy, mr.SourceRef)
1212	}
1213
1214	// CAS so a concurrent push between our read and this write fails the
1215	// merge instead of silently discarding the push.
1216	if err := gitutil.UpdateRefCAS(dir, targetRef, newSHA, targetSHA); err != nil {
1217		return c.fail(protocol.ExitFailure, "target branch moved during merge; retry: %v", err)
1218	}
1219	if err := c.Store.MarkMerged(mr.ID, targetSHA, c.User.ID, ""); err != nil {
1220		return c.fail(protocol.ExitFailure, "%v", err)
1221	}
1222	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d,"sha":%q}`, mr.Number, newSHA))
1223	// The stack moves up: whatever targeted this branch now targets what
1224	// it merged into, reviews intact, since that diff is the one they
1225	// were of.
1226	for _, k := range stack {
1227		if err := c.Store.RetargetKeepingReviews(k.ID, mr.TargetRef); err != nil {
1228			continue
1229		}
1230		c.Store.AddMRSystemComment(k.ID, c.User.ID, fmt.Sprintf("retargeted from %s to %s: !%d merged", mr.SourceRef, mr.TargetRef, mr.Number))
1231		if parts, err := c.Store.MRParticipants(k.ID); err == nil {
1232			notify(c, parts, notice{repo: repo, kind: "mr",
1233				subject: mrSubject(repo, k.Number, k.Title),
1234				action:  fmt.Sprintf("retargeted !%d from %s to %s: !%d merged", k.Number, mr.SourceRef, mr.TargetRef, mr.Number),
1235				path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), k.Number)})
1236		}
1237	}
1238	// Merges bypass receive-pack, so the commit-message issue actions
1239	// (closes #N, references) run here for the newly landed commits. The
1240	// description is scanned after them, so a commit wins the attribution
1241	// when both name the same issue.
1242	if mr.TargetRef == repo.DefaultBranch {
1243		ProcessCommitMessages(c.Store, dir, repo, c.User.ID, c.Scope, targetSHA, newSHA)
1244		ProcessMRDescription(c.Store, repo, mr, c.User.ID, c.Scope)
1245		RecordLandedCommits(c.Store, dir, repo, targetSHA, newSHA)
1246	}
1247	// A merge moves the ref directly, so it never reaches post-receive and
1248	// none of the ref-update work fires on its own. The event webhooks
1249	// subscribe to, and the branch's CI jobs, happen here instead.
1250	c.Store.RecordEvent(repo.ID, c.User.ID, "push", fmt.Sprintf(
1251		`{"ref":%q,"old":%q,"new":%q,"forced":false,"deleted":false}`,
1252		targetRef, targetSHA, newSHA))
1253	QueueBranchBuilds(c.Store, c.Cfg.Server.Root, c.Cfg.Server.SiteURL,
1254		repo, c.User.ID, mr.TargetRef, targetSHA, newSHA, time.Now())
1255	c.Store.MarkMirrorsDirty(repo.ID, "push")
1256	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
1257		notify(c, parts, notice{repo: repo, kind: "mr",
1258			subject: mrSubject(repo, mr.Number, mr.Title),
1259			action:  fmt.Sprintf("merged !%d into %s (%s)", mr.Number, mr.TargetRef, strategy),
1260			path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
1261	}
1262	return c.emit(map[string]any{"number": mr.Number, "strategy": strategy, "sha": newSHA}, func(w io.Writer) {
1263		fmt.Fprintf(w, "merged %s!%d into %s (%s) at %.10s\n", repo.Path(), mr.Number, mr.TargetRef, strategy, newSHA)
1264	})
1265}
1266
1267// reviewGates refuses a merge whose gates are not all met, naming every
1268// unmet one. Returns -1 to proceed.
1269func (c *Ctx) reviewGates(repo store.Repo, mr store.MR, dir, targetSHA, headSHA string) int {
1270	g, err := MergeGates(c.Store, repo, mr, dir, targetSHA, headSHA)
1271	if err != nil {
1272		return c.fail(protocol.ExitFailure, "%v", err)
1273	}
1274	if len(g.Unmet) > 0 {
1275		return c.fail(protocol.ExitDenied, "%s", strings.Join(g.Unmet, "; "))
1276	}
1277	return -1
1278}
1279
1280// checksExpected reports whether anything was going to report a status
1281// on this head. A repository with no CI configuration and no history of
1282// statuses can never satisfy require_checks, and refusing its merges
1283// leaves no remedy but turning the setting off. Two things say a report
1284// was coming: a .gitbay/ci.yml at the head with a job a push runs, and a
1285// status having ever been recorded in the repository, which is how a
1286// repository reporting from outside through `status set` looks.
1287func checksExpected(st *store.Store, repoID int64, dir, headSHA string) bool {
1288	if seen, err := st.RepoHasStatuses(repoID); err != nil || seen {
1289		return true
1290	}
1291	return headRunsJobs(dir, headSHA)
1292}
1293
1294// headRunsJobs reports whether a push of this head would have queued or
1295// skipped a job, and so left it a status. A configuration that will not
1296// parse counts as running jobs: the push recorded a ci/config failure
1297// for it, so the head is not silent and this is not the branch that
1298// decides.
1299func headRunsJobs(dir, headSHA string) bool {
1300	raw, err := gitutil.ReadBlob(dir, headSHA, ci.ConfigPath, 1<<16)
1301	if err != nil {
1302		return false
1303	}
1304	jobs, err := ci.Parse(raw)
1305	if err != nil {
1306		return true
1307	}
1308	for _, j := range jobs {
1309		if j.Tags == "" && j.Schedule == "" {
1310			return true
1311		}
1312	}
1313	return false
1314}
1315
1316// MergeGates computes where a merge request stands against its
1317// repository's gates: draft, require_checks, require_approvals (fresh,
1318// non-author, latest review per reviewer from someone who can write; a
1319// fresh request-changes blocks), require_codeowners and require_resolved.
1320// Unmet carries one sentence per gate not passed. Fast-forward is
1321// reported, not gated: whether it matters depends on the strategy.
1322func MergeGates(st *store.Store, repo store.Repo, mr store.MR, dir, targetSHA, headSHA string) (GatesOut, error) {
1323	set := repo.Settings
1324	g := GatesOut{Draft: mr.Draft, ApprovalsRequired: set.RequireApprovals,
1325		CodeownersRequired: set.RequireCodeowners, ResolvedRequired: set.RequireResolved,
1326		ChecksRequired: set.RequireChecks}
1327	// A draft is open but not asking. This gate is unconditional — no
1328	// setting turns it off — because the author said so themselves.
1329	if mr.Draft {
1330		g.Unmet = append(g.Unmet, fmt.Sprintf("!%d is a draft; `gitbay mr ready %s %d` first", mr.Number, repo.Path(), mr.Number))
1331	}
1332
1333	// Checks: with require_checks, every status the head carries must be
1334	// green, and a head something was going to report on must carry some.
1335	statuses, err := st.ListCommitStatuses(repo.ID, headSHA)
1336	if err != nil {
1337		return g, err
1338	}
1339	g.Checks = store.CombinedStatus(statuses)
1340	if set.RequireChecks {
1341		switch g.Checks {
1342		case "success":
1343		case "":
1344			if checksExpected(st, repo.ID, dir, headSHA) {
1345				g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires green checks and none were reported on %.10s", repo.Path(), headSHA))
1346			}
1347		default:
1348			var bad []string
1349			for _, st := range statuses {
1350				if st.State != "success" {
1351					bad = append(bad, st.Context+"="+st.State)
1352				}
1353			}
1354			g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires green checks; %.10s has %s", repo.Path(), headSHA, strings.Join(bad, ", ")))
1355		}
1356	}
1357
1358	reviews, err := st.ListMRReviews(mr.ID)
1359	if err != nil {
1360		return g, err
1361	}
1362	// Latest fresh review per reviewer decides their stance — but only
1363	// from someone the repository trusts to write to it. Reviewing is
1364	// open to any reader, which is what makes an outside opinion on a
1365	// public change possible; deciding a merge gate is not the same
1366	// thing, and counting every verdict let anyone with an account
1367	// satisfy require_approvals or block a merge indefinitely (#147).
1368	counts := ReviewersWhoCount(st, repo, reviews)
1369	latest := map[string]string{}
1370	for _, r := range reviews {
1371		if r.Stale || r.Reviewer == mr.Author || !counts[r.Reviewer] {
1372			continue
1373		}
1374		latest[r.Reviewer] = r.Verdict
1375	}
1376	for who, verdict := range latest {
1377		switch verdict {
1378		case "approve":
1379			g.Approvals = append(g.Approvals, who)
1380		case "request_changes":
1381			g.ChangesRequested = append(g.ChangesRequested, who)
1382		}
1383	}
1384	slices.Sort(g.Approvals)
1385	slices.Sort(g.ChangesRequested)
1386	if set.RequireApprovals > 0 {
1387		if len(g.ChangesRequested) > 0 {
1388			g.Unmet = append(g.Unmet, fmt.Sprintf("%s requested changes on !%d; resolve their review before merging", strings.Join(g.ChangesRequested, ", "), mr.Number))
1389		}
1390		if len(g.Approvals) < set.RequireApprovals {
1391			g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires %d fresh approval(s); !%d has %d", repo.Path(), set.RequireApprovals, mr.Number, len(g.Approvals)))
1392		}
1393	}
1394
1395	// CODEOWNERS: every owned changed file needs an approval from one of
1396	// its owners. require_codeowners is the opt-in — a repository can
1397	// carry the file as documentation of who to ask without it gating
1398	// merges — and it does not wait on require_approvals (#99).
1399	if set.RequireCodeowners {
1400		content, err := gitutil.ReadBlob(dir, "refs/heads/"+mr.TargetRef, "CODEOWNERS", 1<<20)
1401		if err != nil {
1402			content, err = gitutil.ReadBlob(dir, "refs/heads/"+mr.TargetRef, ".gitbay/CODEOWNERS", 1<<20)
1403		}
1404		if err != nil || len(content) == 0 {
1405			g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires CODEOWNERS approval but %s carries no CODEOWNERS file", repo.Path(), mr.TargetRef))
1406		} else {
1407			rules := policy.ParseCodeowners(string(content))
1408			base, err := gitutil.MergeBase(dir, targetSHA, headSHA)
1409			if err != nil {
1410				return g, err
1411			}
1412			files, err := gitutil.DiffFiles(dir, base, headSHA)
1413			if err != nil {
1414				return g, err
1415			}
1416			approved := map[string]bool{}
1417			for _, a := range g.Approvals {
1418				approved[a] = true
1419			}
1420			missing := map[string][]string{} // owner-set key -> paths
1421			var keys []string
1422			for _, f := range files {
1423				owners := policy.OwnersFor(rules, f)
1424				if owners == nil {
1425					continue
1426				}
1427				ok := false
1428				for _, o := range owners {
1429					if approved[o] {
1430						ok = true
1431						break
1432					}
1433				}
1434				if !ok {
1435					key := strings.Join(owners, ",")
1436					if _, seen := missing[key]; !seen {
1437						keys = append(keys, key)
1438					}
1439					missing[key] = append(missing[key], f)
1440				}
1441			}
1442			if len(missing) > 0 {
1443				slices.Sort(keys)
1444				var parts []string
1445				for _, key := range keys {
1446					paths := missing[key]
1447					g.OwnersOutstanding = append(g.OwnersOutstanding, OwnersOut{Files: paths, Owners: strings.Split(key, ",")})
1448					if len(paths) > 3 {
1449						paths = paths[:3]
1450					}
1451					parts = append(parts, fmt.Sprintf("%s (owned by %s)", strings.Join(paths, ", "), key))
1452				}
1453				g.Unmet = append(g.Unmet, "CODEOWNERS approval missing for: "+strings.Join(parts, "; "))
1454			}
1455		}
1456	}
1457
1458	n, err := st.UnresolvedThreadCount(mr.ID)
1459	if err != nil {
1460		return g, err
1461	}
1462	g.OpenThreads = n
1463	if set.RequireResolved && n > 0 {
1464		g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires review threads resolved; !%d has %d open (mr threads %s %d)", repo.Path(), mr.Number, n, repo.Path(), mr.Number))
1465	}
1466
1467	if ff, err := gitutil.IsAncestor(dir, targetSHA, headSHA); err == nil {
1468		g.FastForward = ff
1469	}
1470	return g, nil
1471}
1472
1473func runMRDraft(c *Ctx, args []string) int { return setMRDraft(c, args, true) }
1474func runMRReady(c *Ctx, args []string) int { return setMRDraft(c, args, false) }
1475
1476func setMRDraft(c *Ctx, args []string, draft bool) int {
1477	repo, mr, code := mrRef(c, args, policy.CanRead)
1478	if code >= 0 {
1479		return code
1480	}
1481	if code := refuseArchived(c, repo); code >= 0 {
1482		return code
1483	}
1484	if len(args) != 2 {
1485		return c.usage()
1486	}
1487	if code := authorOrWrite(c, repo, mr.Author, "change this merge request"); code >= 0 {
1488		return code
1489	}
1490	if mr.State != "open" && mr.State != "source_gone" {
1491		return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
1492	}
1493	if mr.Draft == draft {
1494		state := "already ready"
1495		if draft {
1496			state = "already a draft"
1497		}
1498		return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, state)
1499	}
1500	if err := c.Store.SetMRDraft(mr.ID, draft); err != nil {
1501		return c.fail(protocol.ExitFailure, "%v", err)
1502	}
1503	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.draft",
1504		fmt.Sprintf(`{"number":%d,"draft":%t}`, mr.Number, draft))
1505	// Marking ready is the request for review; going back to draft
1506	// withdraws it and is not worth anyone's inbox.
1507	//
1508	// The targets are the repository's, not the thread's participants.
1509	// Until someone comments or reviews, the only participant is the
1510	// author, who is the actor and excluded — so notifying participants
1511	// here reaches nobody, which is exactly what opening it as a draft
1512	// and then marking it ready would do. Opening a merge request tells
1513	// the repository; so does saying it is finally asking. A review
1514	// request made before ready — or on an earlier revision — reaches its
1515	// target here too: they are exactly who else is being asked.
1516	if !draft {
1517		if targets, err := c.Store.RepoNotifyTargets(repo); err == nil {
1518			parts, _ := c.Store.MRParticipants(mr.ID)
1519			reviewers, _ := c.Store.MRReviewRequestIDs(mr.ID)
1520			notify(c, append(append(targets, parts...), reviewers...), notice{repo: repo, kind: "mr",
1521				subject: mrSubject(repo, mr.Number, mr.Title),
1522				action:  fmt.Sprintf("marked !%d ready for review", mr.Number),
1523				path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
1524		}
1525	}
1526	return c.emit(map[string]any{"number": mr.Number, "draft": draft}, func(w io.Writer) {
1527		fmt.Fprintf(w, "%s!%d is %s\n", repo.Path(), mr.Number, map[bool]string{true: "a draft", false: "ready"}[draft])
1528	})
1529}
1530
1531func runMRClose(c *Ctx, args []string) int {
1532	f, err := parseFlags(args, flagSpec{Values: []string{"--by"}, MaxPos: 2,
1533		Usage: "mr close <owner/name> <n> [--by <m>]"})
1534	if err != nil {
1535		return c.fail(protocol.ExitUsage, "%v", err)
1536	}
1537	repo, mr, code := mrRef(c, f.Pos, policy.CanRead)
1538	if code >= 0 {
1539		return code
1540	}
1541	if code := refuseArchived(c, repo); code >= 0 {
1542		return code
1543	}
1544	if len(f.Pos) != 2 {
1545		return c.usage()
1546	}
1547	if code := authorOrWrite(c, repo, mr.Author, "close this merge request"); code >= 0 {
1548		return code
1549	}
1550	if mr.State == "merged" || mr.State == "closed" {
1551		return c.fail(protocol.ExitUsage, "MR !%d is already %s", mr.Number, mr.State)
1552	}
1553	var by int64
1554	if f.Has("--by") {
1555		by, code = resolveSupersededBy(c, repo, mr.Number, f.Value("--by"))
1556		if code >= 0 {
1557			return code
1558		}
1559	}
1560	if err := c.Store.MarkClosed(mr.ID, c.User.ID, ""); err != nil {
1561		return c.fail(protocol.ExitFailure, "%v", err)
1562	}
1563	eventData := fmt.Sprintf(`{"number":%d}`, mr.Number)
1564	if by != 0 {
1565		if err := c.Store.SetSupersededBy(mr.ID, by); err != nil {
1566			return c.fail(protocol.ExitFailure, "%v", err)
1567		}
1568		eventData = fmt.Sprintf(`{"number":%d,"by":%d}`, mr.Number, by)
1569	}
1570	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.closed", eventData)
1571	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
1572		notify(c, parts, notice{repo: repo, kind: "mr",
1573			subject: mrSubject(repo, mr.Number, mr.Title),
1574			action:  fmt.Sprintf("closed !%d", mr.Number),
1575			path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
1576	}
1577	return c.emit(map[string]any{"number": mr.Number, "state": "closed"}, func(w io.Writer) {
1578		fmt.Fprintf(w, "closed %s!%d\n", repo.Path(), mr.Number)
1579	})
1580}
1581
1582// resolveSupersededBy validates a --superseded-by/--by value against the
1583// merge request it would be set on: it must parse, name another merge
1584// request in the same repository (never itself), and that request must
1585// exist. -1 as the returned code means the value is good to use.
1586func resolveSupersededBy(c *Ctx, repo store.Repo, number int64, v string) (int64, int) {
1587	m, err := strconv.ParseInt(v, 10, 64)
1588	if err != nil {
1589		return 0, c.fail(protocol.ExitUsage, "bad MR number %q", v)
1590	}
1591	if m == number {
1592		return 0, c.fail(protocol.ExitUsage, "a merge request cannot supersede itself")
1593	}
1594	if _, err := c.Store.MRByNumber(repo.ID, m); errors.Is(err, store.ErrNotFound) {
1595		return 0, c.fail(protocol.ExitNotFound, "no merge request !%d on %s", m, repo.Path())
1596	} else if err != nil {
1597		return 0, c.fail(protocol.ExitFailure, "%v", err)
1598	}
1599	return m, -1
1600}
1601
1602// reviewAction is what a review notification says it was. A verdict with
1603// a batch behind it is a different thing from a bare verdict, and the
1604// person reading the mail is deciding whether to open it.
1605func reviewAction(number int64, verdict string, published int64) string {
1606	if published > 0 {
1607		return fmt.Sprintf("reviewed !%d: %s, with %d comment(s)", number, verdict, published)
1608	}
1609	return fmt.Sprintf("reviewed !%d: %s", number, verdict)
1610}
1611
1612// RevisionOut is one head a merge request has had.
1613type RevisionOut struct {
1614	N         int    `json:"n"` // 1 is the first push
1615	SHA       string `json:"sha"`
1616	BaseSHA   string `json:"base_sha,omitempty"`
1617	CreatedAt string `json:"created_at"`
1618	Current   bool   `json:"current,omitempty"`
1619}
1620
1621func mrRevisions(c *Ctx, mr store.MR) ([]RevisionOut, error) {
1622	heads, err := c.Store.MRHeads(mr.ID)
1623	if err != nil {
1624		return nil, err
1625	}
1626	out := make([]RevisionOut, 0, len(heads))
1627	for i, h := range heads {
1628		out = append(out, RevisionOut{N: i + 1, SHA: h.SHA, BaseSHA: h.BaseSHA,
1629			CreatedAt: h.CreatedAt, Current: h.SHA == mr.HeadSHA})
1630	}
1631	return out, nil
1632}
1633
1634func runMRRevisions(c *Ctx, args []string) int {
1635	repo, mr, code := mrRef(c, args, policy.CanRead)
1636	if code >= 0 {
1637		return code
1638	}
1639	if len(args) != 2 {
1640		return c.usage()
1641	}
1642	revs, err := mrRevisions(c, mr)
1643	if err != nil {
1644		return c.fail(protocol.ExitFailure, "%v", err)
1645	}
1646	return c.emit(revs, func(w io.Writer) {
1647		for _, r := range revs {
1648			mark := " "
1649			if r.Current {
1650				mark = "*"
1651			}
1652			fmt.Fprintf(w, "%s v%d\t%.10s\t%s\n", mark, r.N, r.SHA, r.CreatedAt)
1653		}
1654		if len(revs) < 2 {
1655			fmt.Fprintf(w, "\nonly one revision; %s!%d has not been pushed to since it was opened\n",
1656				repo.Path(), mr.Number)
1657		}
1658	})
1659}
1660
1661func runMRRangeDiff(c *Ctx, args []string) int {
1662	f, err := parseFlags(args, flagSpec{Values: []string{"--from", "--to"}, MaxPos: 2, Usage: c.Cmd.Usage})
1663	if err != nil {
1664		return c.fail(protocol.ExitUsage, "%v", err)
1665	}
1666	repo, mr, code := mrRef(c, f.Pos, policy.CanRead)
1667	if code >= 0 {
1668		return code
1669	}
1670	if len(f.Pos) != 2 {
1671		return c.usage()
1672	}
1673	revs, err := mrRevisions(c, mr)
1674	if err != nil {
1675		return c.fail(protocol.ExitFailure, "%v", err)
1676	}
1677	// One revision is a merge request nobody has pushed to since it was
1678	// opened. The argv was fine and the answer is "nothing changed", so
1679	// this succeeds with an empty patch rather than failing.
1680	if len(revs) < 2 {
1681		fmt.Fprintf(c.Stderr, "%s!%d has one revision; nothing to compare it against\n",
1682			repo.Path(), mr.Number)
1683		return protocol.ExitOK
1684	}
1685	// Default to the two most recent, which is "what changed since the
1686	// last push" — the question a stale review asks.
1687	from, to := revs[len(revs)-2], revs[len(revs)-1]
1688	pick := func(sha string) (RevisionOut, bool) {
1689		for _, r := range revs {
1690			if strings.HasPrefix(r.SHA, sha) {
1691				return r, true
1692			}
1693		}
1694		return RevisionOut{}, false
1695	}
1696	if v := f.Value("--from"); v != "" {
1697		r, ok := pick(v)
1698		if !ok {
1699			return c.fail(protocol.ExitNotFound, "%.12s is not a revision of !%d; see `mr revisions`", v, mr.Number)
1700		}
1701		from = r
1702	}
1703	if v := f.Value("--to"); v != "" {
1704		r, ok := pick(v)
1705		if !ok {
1706			return c.fail(protocol.ExitNotFound, "%.12s is not a revision of !%d; see `mr revisions`", v, mr.Number)
1707		}
1708		to = r
1709	}
1710	if from.SHA == to.SHA {
1711		return c.fail(protocol.ExitUsage, "--from and --to are the same revision")
1712	}
1713
1714	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
1715	// A revision recorded before its base could be worked out, or by a
1716	// migration backfill, falls back to the target's merge base.
1717	baseOf := func(r RevisionOut) string {
1718		if r.BaseSHA != "" {
1719			return r.BaseSHA
1720		}
1721		b, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, r.SHA)
1722		if err != nil {
1723			return r.SHA + "^"
1724		}
1725		return b
1726	}
1727	patch, truncated, err := gitutil.RangeDiff(dir, baseOf(from), from.SHA, baseOf(to), to.SHA, 4<<20)
1728	if err != nil {
1729		return c.fail(protocol.ExitFailure,
1730			"%v (the objects for an older revision may have been garbage-collected)", err)
1731	}
1732	fmt.Fprint(c.Stdout, patch)
1733	if truncated {
1734		fmt.Fprintln(c.Stderr, "range-diff truncated at 4 MiB")
1735	}
1736	return protocol.ExitOK
1737}
1738
1739// reviewersWhoCount is the set of reviewers whose verdict decides a merge
1740// gate: those with write access to the repository.
1741//
1742// Write, rather than a separate reviewer role, because it is the same
1743// question the gates already answer — a person who could push this change
1744// themselves is the person whose approval means the repository accepts
1745// it. Someone named in CODEOWNERS without write is a misconfiguration the
1746// owner should fix rather than a case to special-case here: they could
1747// not merge what they approved.
1748// Exported because the web renders the same distinction: a page that
1749// showed an approval the gate ignores would differ from the gate, and the
1750// difference would only surface when a merge was refused.
1751func ReviewersWhoCount(st *store.Store, repo store.Repo, reviews []store.MRReview) map[string]bool {
1752	counts := map[string]bool{}
1753	for _, r := range reviews {
1754		if _, done := counts[r.Reviewer]; done {
1755			continue
1756		}
1757		counts[r.Reviewer] = false
1758		u, err := st.UserByUsername(r.Reviewer)
1759		if err != nil {
1760			continue
1761		}
1762		grant, err := st.AccessRole(repo.ID, u.ID)
1763		if err != nil {
1764			continue
1765		}
1766		counts[r.Reviewer] = policy.CanWrite(u, repo, grant)
1767	}
1768	return counts
1769}