internal/control/mr.go

8e6fc2062ca26f7a848bdf6ad6345fd345351231
gitbay/internal/control/mr.go history · blame · raw

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