internal/control/mr.go

353f68a2e57ac692964b73ae1f9acd91fcdcae20
gitbay/internal/control/mr.go history · blame · raw

1700 lines · 61405 bytes

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