internal/control/mr.go

e3632a550366fe23b2619edba30fc58fab19b598
gitbay/internal/control/mr.go history · blame · raw

1593 lines · 58187 bytes

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