internal/control/mr.go

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