internal/control/mr.go

545ba0bcdea3b534903bd78c918c0c025a97eda7
gitbay/internal/control/mr.go

2454 lines · 88286 bytes

78 symbols in this file
   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>]",
  24		Flags: []Flag{
  25			{"--owner", "<o>", "fork under this user or org, default your account", ""},
  26			{"--name", "<n>", "name the fork", "the source's name"},
  27		},
  28		Examples: []string{"repo fork krz/gitbay"},
  29		Run:      runRepoFork})
  30	register(Command{Path: []string{"repo", "settings", "require-approvals"},
  31		Summary:  "require N fresh approvals to merge",
  32		Usage:    "repo settings require-approvals <owner/name> <n> (0 = off)",
  33		Examples: []string{"repo settings require-approvals krz/gitbay 1"},
  34		Run:      runRequireApprovals})
  35	register(Command{Path: []string{"repo", "settings", "require-resolved"},
  36		Summary:  "require all review threads resolved to merge",
  37		Usage:    "repo settings require-resolved <owner/name> on|off",
  38		Examples: []string{"repo settings require-resolved krz/gitbay on"},
  39		Run:      runRequireResolved})
  40	register(Command{Path: []string{"repo", "settings", "require-codeowners"},
  41		Summary:  "require an owner's approval for every file CODEOWNERS covers",
  42		Usage:    "repo settings require-codeowners <owner/name> on|off",
  43		Examples: []string{"repo settings require-codeowners krz/gitbay on"},
  44		Run:      runRequireCodeowners})
  45	register(Command{Path: []string{"repo", "settings", "require-checks"},
  46		Summary:  "gate merges on green statuses",
  47		Usage:    "repo settings require-checks <owner/name> on|off",
  48		Examples: []string{"repo settings require-checks krz/gitbay on"},
  49		Run:      runRequireChecks})
  50	register(Command{Path: []string{"repo", "settings", "require-contexts"},
  51		Summary:  "name the statuses the checks gate waits for, and turn the gate on",
  52		Usage:    "repo settings require-contexts <owner/name> [<context>...] (none clears the list)",
  53		Examples: []string{"repo settings require-contexts krz/gitbay ci/build ci/test"},
  54		Run:      runRequireContexts})
  55	register(Command{Path: []string{"repo", "settings", "require-mr"},
  56		Summary:  "protected branches take changes through merge requests only",
  57		Usage:    "repo settings require-mr <owner/name> on|off",
  58		Examples: []string{"repo settings require-mr krz/gitbay on"},
  59		Run:      runRequireMR})
  60	register(Command{Path: []string{"repo", "settings", "require-signed"},
  61		Summary:  "require verified commit signatures",
  62		Usage:    "repo settings require-signed <owner/name> on|off",
  63		Examples: []string{"repo settings require-signed krz/gitbay on"},
  64		Run:      runRequireSigned})
  65	register(Command{Path: []string{"mr", "create"},
  66		Summary: "open a merge request",
  67		Usage:   "mr create <target owner/name> --source [owner/name:]<branch> [--target <branch>] --title <t> [--body <b> | --file -] [--format md|org] [--draft]",
  68		Flags: []Flag{
  69			{"--source", "[owner/name:]<branch>", "the branch to merge, from a fork with owner/name:", ""},
  70			{"--target", "<branch>", "the branch to merge into", "default branch"},
  71			{"--title", "<t>", "the merge request's title", ""},
  72			{"--body", "<b>", "the merge request's body", ""},
  73			{"--file", "-", "read the body from stdin", ""},
  74			{"--format", "md|org", "the body's markup", "md"},
  75			{"--draft", "", "open it as work in progress", ""},
  76		},
  77		Examples: []string{
  78			`mr create krz/gitbay --source cli-output-help --target main --title "control: flag help"`,
  79			"mr create krz/gitbay --source cli-output-help --target main --title notes --file - < notes.md",
  80		},
  81		ReadsStdin: true, Run: runMRCreate})
  82	register(Command{Path: []string{"mr", "range-diff"},
  83		Summary: "what changed between two revisions of a merge request",
  84		Usage:   "mr range-diff <owner/name> <n> [--from <sha>] [--to <sha>]",
  85		Flags: []Flag{
  86			{"--from", "<sha>", "earlier revision, default the one before --to", ""},
  87			{"--to", "<sha>", "later revision, default the head", ""},
  88		},
  89		Examples: []string{"mr range-diff krz/gitbay 431"},
  90		ReadOnly: true, Run: runMRRangeDiff})
  91	register(Command{Path: []string{"mr", "revisions"},
  92		Summary:  "the heads a merge request has had",
  93		Usage:    "mr revisions <owner/name> <n>",
  94		Examples: []string{"mr revisions krz/gitbay 431"},
  95		ReadOnly: true, Run: runMRRevisions})
  96	register(Command{Path: []string{"mr", "draft"},
  97		Summary:  "mark a merge request as work in progress",
  98		Usage:    "mr draft <owner/name> <n>",
  99		Examples: []string{"mr draft krz/gitbay 431"},
 100		Run:      runMRDraft})
 101	register(Command{Path: []string{"mr", "ready"},
 102		Summary:  "take the draft mark off, so it can merge",
 103		Usage:    "mr ready <owner/name> <n>",
 104		Examples: []string{"mr ready krz/gitbay 431"},
 105		Run:      runMRReady})
 106	register(Command{Path: []string{"mr", "list"},
 107		Summary: "list merge requests",
 108		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>] | mr list --query <name> | --q <query> [--limit <n>] [--cursor <c>]",
 109		Flags: []Flag{
 110			{"--state", "open|merged|closed|source_gone|all", "which merge requests", "open"},
 111			{"--label", "<l>", "only MRs carrying this label", ""},
 112			{"--author", "<user>", "only MRs opened by this user", ""},
 113			{"--milestone", "<title>|none", "only MRs in this milestone, or in none", ""},
 114			{"--search", "<text>", "match title and body", ""},
 115			{"--query", "<name>", "a saved query, across repositories, in place of a repository and filters", ""},
 116			{"--q", "<query>", "a query written out, as query save takes it", ""},
 117			{"--limit", "<n>", "rows per page", ""},
 118			{"--cursor", "<c>", "continue from the previous page", ""},
 119		},
 120		Examples: []string{
 121			"mr list krz/gitbay --state open",
 122			"mr list krz/gitbay --author cmc --state all",
 123			"mr list --query reviews",
 124			`mr list --q "repo:krz/* is:open author:@me"`,
 125		},
 126		ReadOnly: true, Run: runMRList})
 127	register(Command{Path: []string{"mr", "show"},
 128		Summary:  "show a merge request",
 129		Usage:    "mr show <owner/name> <n>",
 130		Examples: []string{"mr show krz/gitbay 431"},
 131		ReadOnly: true, Run: runMRShow})
 132	register(Command{Path: []string{"mr", "diff"},
 133		Summary:  "show the diff",
 134		Usage:    "mr diff <owner/name> <n>",
 135		Examples: []string{"mr diff krz/gitbay 431"},
 136		ReadOnly: true, Run: runMRDiff})
 137	register(Command{Path: []string{"mr", "edit"},
 138		Summary: "edit title or body",
 139		Usage:   "mr edit <owner/name> <n> [--title <t>] [--body <b> | --file -] [--format md|org] [--superseded-by <m>|none]",
 140		Flags: []Flag{
 141			{"--title", "<t>", "the merge request's new title", ""},
 142			{"--body", "<b>", "the merge request's new body", ""},
 143			{"--file", "-", "read the new body from stdin", ""},
 144			{"--format", "md|org", "the body's markup", ""},
 145			{"--superseded-by", "<m>|none", "the MR replacing this one, or none to clear", ""},
 146		},
 147		Examples:   []string{`mr edit krz/gitbay 431 --title "control: flag help, take two"`},
 148		ReadsStdin: true, Run: runMREdit})
 149	register(Command{Path: []string{"mr", "retarget"},
 150		Summary:  "retarget onto another branch",
 151		Usage:    "mr retarget <owner/name> <n> <branch>",
 152		Examples: []string{"mr retarget krz/gitbay 431 main"},
 153		Run:      runMRRetarget})
 154	register(Command{Path: []string{"mr", "comment"},
 155		Summary: "add a comment",
 156		Usage:   "mr comment <owner/name> <n> [--message <m> | --file -] [--format md|org]",
 157		Flags: []Flag{
 158			{"--message", "<m>", "the comment's text", ""},
 159			{"--file", "-", "read the comment from stdin", ""},
 160			{"--format", "md|org", "the comment's markup", "md"},
 161		},
 162		Examples:   []string{`mr comment krz/gitbay 431 --message "looks good"`},
 163		ReadsStdin: true, Run: runMRComment})
 164	register(Command{Path: []string{"mr", "review"},
 165		Summary: "record a review verdict",
 166		Usage:   "mr review <owner/name> <n> --approve|--request-changes|--comment|--discard",
 167		Flags: []Flag{
 168			{"--approve", "", "approve the merge request", ""},
 169			{"--request-changes", "", "ask for changes", ""},
 170			{"--comment", "", "submit pending diff comments without a verdict", ""},
 171			{"--discard", "", "throw away pending diff comments", ""},
 172		},
 173		Examples: []string{"mr review krz/gitbay 431 --approve"},
 174		Run:      runMRReview})
 175	register(Command{Path: []string{"mr", "review", "request"},
 176		Summary: "ask specific people for a review",
 177		Usage:   "mr review request <owner/name> <n> [--add <user>]... [--remove <user>]...",
 178		Flags: []Flag{
 179			{"--add", "<user>", "reviewer to add, may repeat", ""},
 180			{"--remove", "<user>", "reviewer to remove, may repeat", ""},
 181		},
 182		Examples: []string{"mr review request krz/gitbay 431 --add cmc"},
 183		Run:      runMRReviewRequest})
 184	register(Command{Path: []string{"mr", "label"},
 185		Summary: "add or remove labels",
 186		Usage:   "mr label <owner/name> <n> [--add <l>]... [--remove <l>]...",
 187		Flags: []Flag{
 188			{"--add", "<l>", "label to add, may repeat", ""},
 189			{"--remove", "<l>", "label to remove, may repeat", ""},
 190		},
 191		Examples: []string{"mr label krz/gitbay 431 --add needs-review"},
 192		Run:      runMRLabel})
 193	register(Command{Path: []string{"mr", "merge"},
 194		Summary: "merge",
 195		Usage:   "mr merge <owner/name> <n> [--strategy ff|merge|squash|rebase] [--when-ready | --cancel]",
 196		Flags: []Flag{
 197			{"--strategy", "ff|merge|squash|rebase", "how to merge", ""},
 198			{"--when-ready", "", "queue the merge until the gates pass; merges now if they already do", ""},
 199			{"--cancel", "", "take a queued merge off the queue", ""},
 200		},
 201		Examples: []string{"mr merge krz/gitbay 431 --strategy ff", "mr merge krz/gitbay 431 --when-ready", "mr merge krz/gitbay 431 --cancel"},
 202		Run:      runMRMerge})
 203	register(Command{Path: []string{"mr", "close"},
 204		Summary: "close without merging",
 205		Usage:   "mr close <owner/name> <n> [--by <m>]",
 206		Flags: []Flag{
 207			{"--by", "<m>", "the MR that supersedes this one", ""},
 208		},
 209		Examples: []string{"mr close krz/gitbay 431"},
 210		Run:      runMRClose})
 211}
 212
 213// ForkOut is what `repo fork` emits: where the fork landed, and what it
 214// came from. Named so the web can send a person to the new repository.
 215type ForkOut struct {
 216	Path   string `json:"path"`
 217	ForkOf string `json:"fork_of"`
 218}
 219
 220func runRepoFork(c *Ctx, args []string) int {
 221	f, err := c.parseArgs(args, flagSpec{Values: []string{"--name", "--owner"}, MaxPos: 1, Usage: "repo fork <owner/name> [--owner <o>] [--name <n>]"})
 222	if err != nil {
 223		return c.fail(protocol.ExitUsage, "%v", err)
 224	}
 225	path, name, owner := f.pos(0), f.Value("--name"), f.Value("--owner")
 226	if path == "" {
 227		return c.usage()
 228	}
 229	src, code := resolveRepo(c, path, policy.CanRead)
 230	if code >= 0 {
 231		return code
 232	}
 233	if name == "" {
 234		name = src.Name
 235	}
 236	if err := policy.ValidateName(name); err != nil {
 237		return c.failInput(err)
 238	}
 239	if owner == "" {
 240		owner = c.User.Username
 241	}
 242	ownerKind, ownerID, code := resolveNewRepoOwner(c, owner)
 243	if code >= 0 {
 244		return code
 245	}
 246	repoCreateMu.Lock()
 247	if code := checkRepoQuota(c, ownerKind, ownerID); code >= 0 {
 248		repoCreateMu.Unlock()
 249		return code
 250	}
 251	id, err := c.Store.CreateFork(ownerKind, ownerID, name, src.Visibility, src.ID)
 252	repoCreateMu.Unlock()
 253	if err != nil {
 254		return c.fail(protocol.ExitFailure, "%v", err)
 255	}
 256	dstDir := RepoDir(c.Cfg.Server.Root, owner, name)
 257	srcDir := RepoDir(c.Cfg.Server.Root, src.OwnerName, src.Name)
 258	if err := gitutil.InitBare(dstDir, "main", HooksDir(c.Cfg.Server.Root)); err != nil {
 259		c.Store.DeleteRepo(id)
 260		return c.fail(protocol.ExitFailure, "%v", err)
 261	}
 262	if desc := gitutil.ReadDescription(srcDir); desc != "" {
 263		gitutil.WriteDescription(dstDir, desc)
 264	}
 265	if err := gitutil.FetchInto(dstDir, srcDir, "refs/heads/*", "refs/heads/*"); err != nil {
 266		// Empty source repos have nothing to fetch; that is fine.
 267		if _, rerr := gitutil.ResolveRef(srcDir, src.DefaultBranch); rerr == nil {
 268			c.Store.DeleteRepo(id)
 269			return c.fail(protocol.ExitFailure, "copying refs: %v", err)
 270		}
 271	}
 272	forkPath := owner + "/" + name
 273	return c.emit(ForkOut{Path: forkPath, ForkOf: src.Path()}, func(w io.Writer) {
 274		fmt.Fprintf(w, "forked %s to %s\n", src.Path(), forkPath)
 275	})
 276}
 277
 278func runRequireApprovals(c *Ctx, args []string) int {
 279	if len(args) != 2 {
 280		return c.usage()
 281	}
 282	n, err := strconv.Atoi(args[1])
 283	if err != nil || n < 0 || n > 20 {
 284		return c.fail(protocol.ExitUsage, "approvals must be 0..20")
 285	}
 286	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
 287	if code >= 0 {
 288		return code
 289	}
 290	s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.RequireApprovals = n })
 291	if err != nil {
 292		return c.fail(protocol.ExitFailure, "%v", err)
 293	}
 294	return c.emit(s, func(w io.Writer) {
 295		fmt.Fprintf(w, "require_approvals %d on %s\n", n, repo.Path())
 296	})
 297}
 298
 299func runRequireResolved(c *Ctx, args []string) int {
 300	return setRepoToggle(c, args, "require_resolved", func(s *store.RepoSettings, on bool) { s.RequireResolved = on })
 301}
 302
 303func runRequireCodeowners(c *Ctx, args []string) int {
 304	return setRepoToggle(c, args, "require_codeowners", func(s *store.RepoSettings, on bool) { s.RequireCodeowners = on })
 305}
 306
 307func runRequireChecks(c *Ctx, args []string) int {
 308	return setRepoToggle(c, args, "require_checks", func(s *store.RepoSettings, on bool) { s.RequireChecks = on })
 309}
 310
 311// setRepoToggle is `<owner/name> on|off` for one boolean repository setting,
 312// reported under `name`.
 313func setRepoToggle(c *Ctx, args []string, name string, set func(*store.RepoSettings, bool)) int {
 314	if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
 315		return c.usage()
 316	}
 317	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
 318	if code >= 0 {
 319		return code
 320	}
 321	s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { set(s, args[1] == "on") })
 322	if err != nil {
 323		return c.fail(protocol.ExitFailure, "%v", err)
 324	}
 325	return c.emit(s, func(w io.Writer) {
 326		fmt.Fprintf(w, "%s %s on %s\n", name, args[1], repo.Path())
 327	})
 328}
 329
 330// maxRequiredContexts bounds the list: a gate naming more checks than
 331// this is a configuration mistake.
 332const maxRequiredContexts = 20
 333
 334func runRequireContexts(c *Ctx, args []string) int {
 335	if len(args) < 1 {
 336		return c.usage()
 337	}
 338	var contexts []string
 339	for _, ctx := range args[1:] {
 340		if ctx == "" || len(ctx) > 100 || strings.ContainsAny(ctx, " \t\r\n") {
 341			return c.fail(protocol.ExitUsage, "a context is 1 to 100 characters with no whitespace: %q", ctx)
 342		}
 343		if !slices.Contains(contexts, ctx) {
 344			contexts = append(contexts, ctx)
 345		}
 346	}
 347	if len(contexts) > maxRequiredContexts {
 348		return c.fail(protocol.ExitUsage, "at most %d required contexts", maxRequiredContexts)
 349	}
 350	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
 351	if code >= 0 {
 352		return code
 353	}
 354	// Naming contexts asks for the gate, so it turns require_checks on in
 355	// the same update. Clearing the list leaves the gate as it was.
 356	s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) {
 357		s.RequiredContexts = contexts
 358		if len(contexts) > 0 {
 359			s.RequireChecks = true
 360		}
 361	})
 362	if err != nil {
 363		return c.fail(protocol.ExitFailure, "%v", err)
 364	}
 365	return c.emit(s, func(w io.Writer) {
 366		if len(contexts) > 0 {
 367			fmt.Fprintf(w, "required contexts on %s: %s; require_checks on\n", repo.Path(), strings.Join(contexts, ", "))
 368			return
 369		}
 370		gate := "off"
 371		if s.RequireChecks {
 372			gate = "on"
 373		}
 374		fmt.Fprintf(w, "required contexts cleared on %s; require_checks %s\n", repo.Path(), gate)
 375	})
 376}
 377
 378func runRequireMR(c *Ctx, args []string) int {
 379	return setRepoToggle(c, args, "require_mr", func(s *store.RepoSettings, on bool) { s.RequireMR = on })
 380}
 381
 382func runRequireSigned(c *Ctx, args []string) int {
 383	return setRepoToggle(c, args, "require_signed_commits", func(s *store.RepoSettings, on bool) { s.RequireSignedCommits = on })
 384}
 385
 386// mrRef parses "<owner/name> <n>" and loads the MR.
 387func mrRef(c *Ctx, args []string, perm func(store.User, store.Repo, string) bool) (store.Repo, store.MR, int) {
 388	repo, n, code := refArgs(c, args, perm, "MR")
 389	if code >= 0 {
 390		return repo, store.MR{}, code
 391	}
 392	mr, err := c.Store.MRByNumber(repo.ID, n)
 393	if errors.Is(err, store.ErrNotFound) {
 394		return repo, mr, c.fail(protocol.ExitNotFound, "MR !%d not found in %s", n, repo.Path())
 395	}
 396	if err != nil {
 397		return repo, mr, c.fail(protocol.ExitFailure, "%v", err)
 398	}
 399	return repo, mr, -1
 400}
 401
 402func mrHeadRef(n int64) string { return fmt.Sprintf("refs/merge-requests/%d/head", n) }
 403
 404func runMRCreate(c *Ctx, args []string) int {
 405	f, err := c.parseArgs(args, flagSpec{Values: []string{"--source", "--target", "--title", "--body", "--file", "--format"},
 406		Bools: []string{"--draft"}, MaxPos: 1,
 407		Usage: "mr create <target owner/name> --source [owner/name:]<branch> --target <branch> --title <t> [--draft]"})
 408	if err != nil {
 409		return c.fail(protocol.ExitUsage, "%v", err)
 410	}
 411	path, source, target := f.pos(0), f.Value("--source"), f.Value("--target")
 412	title, body, file, format := f.Value("--title"), f.Value("--body"), f.Value("--file"), f.Value("--format")
 413	if path == "" || source == "" || title == "" {
 414		return c.usage()
 415	}
 416	fmtName, err := markupFormat(format)
 417	if err != nil {
 418		return c.failInput(err)
 419	}
 420	if fmtName == "" {
 421		fmtName = "md"
 422	}
 423	repo, code := resolveRepo(c, path, policy.CanRead)
 424	if code >= 0 {
 425		return code
 426	}
 427	if code := refuseArchived(c, repo); code >= 0 {
 428		return code
 429	}
 430	if target == "" {
 431		target = repo.DefaultBranch
 432	}
 433
 434	// Source is "branch" (same repo) or "owner/name:branch" (a fork).
 435	srcRepo := repo
 436	srcBranch := source
 437	if sp, br, ok := strings.Cut(source, ":"); ok {
 438		srcBranch = br
 439		var scode int
 440		srcRepo, scode = resolveRepo(c, sp, policy.CanRead)
 441		if scode >= 0 {
 442			return scode
 443		}
 444		if srcRepo.ForkOf != repo.ID && srcRepo.ID != repo.ID {
 445			return c.fail(protocol.ExitUsage, "%s is not a fork of %s", srcRepo.Path(), repo.Path())
 446		}
 447	}
 448	srcDir := RepoDir(c.Cfg.Server.Root, srcRepo.OwnerName, srcRepo.Name)
 449	headSHA, err := gitutil.ResolveRef(srcDir, "refs/heads/"+srcBranch)
 450	if err != nil {
 451		return c.fail(protocol.ExitNotFound, "branch %s not found in %s", srcBranch, srcRepo.Path())
 452	}
 453	b, err := bodyFrom(c, body, file)
 454	if err != nil {
 455		return c.failInput(err)
 456	}
 457	n, err := c.Store.CreateMR(repo.ID, c.User.ID, srcRepo.ID, srcBranch, target, title, b, headSHA, fmtName, f.Has("--draft"))
 458	if err != nil {
 459		return c.fail(protocol.ExitFailure, "%v", err)
 460	}
 461	// Fetch the head into the target so the target owns the objects.
 462	dstDir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
 463	if err := gitutil.FetchInto(dstDir, srcDir, headSHA, mrHeadRef(n)); err != nil {
 464		return c.fail(protocol.ExitFailure, "recording MR head: %v", err)
 465	}
 466	if srcRepo.ID != repo.ID {
 467		QueueMRBuilds(c.Store, c.Cfg.Server.Root, c.Cfg.Server.SiteURL, repo, c.User.ID, n, headSHA)
 468	}
 469	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.created", fmt.Sprintf(`{"number":%d}`, n))
 470	if targets, err := c.Store.RepoNotifyTargets(repo); err == nil {
 471		notify(c, targets, notice{repo: repo, kind: "mr", number: n,
 472			subject: mrSubject(repo, n, title),
 473			action:  fmt.Sprintf("opened merge request !%d (%s -> %s)", n, source, target),
 474			excerpt: b, path: fmt.Sprintf("%s/mrs/%d", repo.Path(), n)})
 475	}
 476	if created, err := c.Store.MRByNumber(repo.ID, n); err == nil {
 477		notifyMentions(c, repo, mrThread, created.ID, n, title, b)
 478	}
 479	out := MRCreated{Number: n, HeadSHA: headSHA}
 480	if p, ok, err := c.Store.OpenMRBySource(repo.ID, target); err == nil && ok {
 481		out.StackedOn = &stackRef{p.Number, p.Title}
 482	}
 483	return c.emit(out, func(w io.Writer) {
 484		fmt.Fprintf(w, "created %s!%d (%s -> %s)\n", repo.Path(), n, source, target)
 485		if c.Term.Cols > 0 {
 486			fmt.Fprintln(w, c.siteURL(repo.Path(), "mrs", strconv.FormatInt(n, 10)))
 487		}
 488		if out.StackedOn != nil {
 489			fmt.Fprintf(w, "stacked on !%d %s\n", out.StackedOn.Number, out.StackedOn.Title)
 490		}
 491	})
 492}
 493
 494type mrOut struct {
 495	Number int64  `json:"number"`
 496	Title  string `json:"title"`
 497	State  string `json:"state"`
 498	// Draft is an open merge request not asking to be merged yet.
 499	Draft      bool     `json:"draft,omitempty"`
 500	Author     string   `json:"author"`
 501	Source     string   `json:"source"` // owner/name:branch, or branch, "" if gone
 502	TargetRef  string   `json:"target_ref"`
 503	HeadSHA    string   `json:"head_sha"`
 504	Body       string   `json:"body,omitempty"`
 505	BodyFormat string   `json:"body_format,omitempty"`
 506	Milestone  string   `json:"milestone,omitempty"`
 507	Labels     []string `json:"labels,omitempty"`
 508	// ReviewRequests is who has been asked, directly, for a review.
 509	ReviewRequests []string `json:"review_requests,omitempty"`
 510	// StackedOn is the open merge request whose source branch this one
 511	// targets; Stacked are the open ones targeting this one's source.
 512	StackedOn *stackRef  `json:"stacked_on,omitempty"`
 513	Stacked   []stackRef `json:"stacked,omitempty"`
 514	CreatedAt string     `json:"created_at"`
 515	MergedAt  string     `json:"merged_at,omitempty"`
 516	MergedBy  string     `json:"merged_by,omitempty"`
 517	ClosedAt  string     `json:"closed_at,omitempty"`
 518	ClosedBy  string     `json:"closed_by,omitempty"`
 519	// SupersededBy is the merge request, by number, this one was closed
 520	// in favour of. 0 means none.
 521	SupersededBy int64 `json:"superseded_by,omitempty"`
 522	// Queued is the merge queued with mr merge --when-ready, if any.
 523	Queued *QueuedOut `json:"queued,omitempty"`
 524}
 525
 526type stackRef struct {
 527	Number int64  `json:"number"`
 528	Title  string `json:"title"`
 529}
 530
 531// stackOf derives the stack around m: the open merge request whose source
 532// branch m targets, and the open ones targeting m's source. Both only
 533// within m's repository; a fork's branch is not a target anything can
 534// stack on.
 535func stackOf(c *Ctx, repo store.Repo, m store.MR) (*stackRef, []stackRef) {
 536	if m.State != "open" {
 537		return nil, nil
 538	}
 539	var parent *stackRef
 540	if p, ok, err := c.Store.OpenMRBySource(repo.ID, m.TargetRef); err == nil && ok && p.ID != m.ID {
 541		parent = &stackRef{p.Number, p.Title}
 542	}
 543	var children []stackRef
 544	if m.SourceRepoID == repo.ID {
 545		if kids, err := c.Store.OpenMRsByTarget(repo.ID, m.SourceRef); err == nil {
 546			for _, k := range kids {
 547				if k.ID != m.ID {
 548					children = append(children, stackRef{k.Number, k.Title})
 549				}
 550			}
 551		}
 552	}
 553	return parent, children
 554}
 555
 556func mrToOut(repo store.Repo, m store.MR, withBody bool) mrOut {
 557	src := ""
 558	if m.SourcePath != "" {
 559		if m.SourceRepoID == repo.ID {
 560			src = m.SourceRef
 561		} else {
 562			src = m.SourcePath + ":" + m.SourceRef
 563		}
 564	}
 565	o := mrOut{Number: m.Number, Title: m.Title, State: m.State, Draft: m.Draft, Author: m.Author,
 566		Source: src, TargetRef: m.TargetRef, HeadSHA: m.HeadSHA, Milestone: m.Milestone,
 567		Labels: m.Labels, ReviewRequests: m.ReviewRequests,
 568		CreatedAt: m.CreatedAt, MergedAt: m.MergedAt, MergedBy: m.MergedBy,
 569		ClosedAt: m.ClosedAt, ClosedBy: m.ClosedBy, SupersededBy: m.SupersededBy,
 570		Queued: queuedOut(m)}
 571	if withBody {
 572		o.Body = m.Body
 573		o.BodyFormat = m.BodyFormat
 574	}
 575	return o
 576}
 577
 578func runMRList(c *Ctx, args []string) int {
 579	if usesQuery(args) {
 580		args, p, code := parsePageFlags(c, args, "query", false)
 581		if code >= 0 {
 582			return code
 583		}
 584		fl, err := c.parseArgs(args, flagSpec{Values: []string{"--query", "--q", "--state", "--label", "--assignee", "--author", "--milestone", "--search"}, MaxPos: 1, Usage: c.Cmd.Usage})
 585		if err != nil {
 586			return c.fail(protocol.ExitUsage, "%v", err)
 587		}
 588		return listByQuery(c, fl, "mr", p)
 589	}
 590	args, p, code := parsePageFlags(c, args, "mr", true)
 591	if code >= 0 {
 592		return code
 593	}
 594	f := store.MRFilter{State: "open"}
 595	fl, err := c.parseArgs(args, flagSpec{Values: []string{"--state", "--label", "--author", "--milestone", "--search"}, MaxPos: 1, Usage: c.Cmd.Usage})
 596	if err != nil {
 597		return c.fail(protocol.ExitUsage, "%v", err)
 598	}
 599	path := fl.pos(0)
 600	if fl.Has("--state") {
 601		f.State = fl.Value("--state")
 602	}
 603	f.Label, f.Author, f.Milestone = fl.Value("--label"), fl.Value("--author"), fl.Value("--milestone")
 604	f.Search = fl.Value("--search")
 605	if fl.Has("--search") {
 606		if err := validQuery(f.Search); err != nil {
 607			return c.failInput(err)
 608		}
 609	}
 610	valid := map[string]bool{"open": true, "merged": true, "closed": true, "source_gone": true, "all": true}
 611	if path == "" || !valid[f.State] {
 612		return c.usage()
 613	}
 614	repo, code := resolveRepo(c, path, policy.CanRead)
 615	if code >= 0 {
 616		return code
 617	}
 618	f.Limit, f.Before = p.queryLimit(), p.keyInt()
 619	mrs, err := c.Store.QueryMRs(repo.ID, f)
 620	if err != nil {
 621		return c.fail(protocol.ExitFailure, "%v", err)
 622	}
 623	mrs, next := trimPage(p, mrs, "mr", func(m store.MR) string {
 624		return strconv.FormatInt(m.Number, 10)
 625	})
 626	var ds []mrOut
 627	for _, m := range mrs {
 628		o := mrToOut(repo, m, false)
 629		o.StackedOn, _ = stackOf(c, repo, m)
 630		ds = append(ds, o)
 631	}
 632	var checks, review map[int64]cell
 633	if c.Term.Cols > 0 && !c.JSON {
 634		if checks, review, err = mrMarks(c, repo, mrs); err != nil {
 635			return c.fail(protocol.ExitFailure, "%v", err)
 636		}
 637	}
 638	return c.emitPageView(p, ds, next, func(w io.Writer) {
 639		tb := c.table(w, "!", "STATE", "TITLE", "REF")
 640		for _, d := range ds {
 641			state := d.State
 642			if d.Draft {
 643				state = "draft"
 644			}
 645			cells := []cell{cRef(fmt.Sprintf("!%d", d.Number)), cState(state), cFlex(d.Title), cText(fmt.Sprintf("%s -> %s", d.Source, d.TargetRef))}
 646			if d.StackedOn != nil {
 647				cells = append(cells, cText(fmt.Sprintf("stacked on !%d", d.StackedOn.Number)))
 648			}
 649			tb.row(cells...)
 650		}
 651		tb.flush()
 652	}, func() screen { return mrListScreen(c, repo, f.State, mrs, ds, checks, review) })
 653}
 654
 655// mrListScreen is mr list at a terminal: one section of merge requests,
 656// each led by ● when its review waits on the viewer, otherwise by its
 657// checks' mark, then title, review state, branch and age. The source
 658// branch alone names a merge request into the default branch.
 659func mrListScreen(c *Ctx, repo store.Repo, state string, mrs []store.MR, ds []mrOut, checks, review map[int64]cell) screen {
 660	title, ok := map[string]string{"open": "Open merge requests", "closed": "Closed merge requests", "merged": "Merged merge requests"}[state]
 661	if !ok {
 662		title = "Merge requests"
 663	}
 664	sec := section{title: title, n: len(ds)}
 665	for i, d := range ds {
 666		m := mrs[i]
 667		lead := cell{kind: kindGlyph}
 668		if ch := checks[m.ID]; ch.s != "" {
 669			g, _, _ := strings.Cut(ch.s, " ")
 670			lead = cell{kind: kindGlyph, s: g, sgr: ch.sgr}
 671		}
 672		if review[m.ID].sgr == sgrYellow {
 673			lead = cYou()
 674		}
 675		branch := d.Source
 676		if d.TargetRef != repo.DefaultBranch {
 677			branch += " → " + d.TargetRef
 678		}
 679		if d.StackedOn != nil {
 680			branch += fmt.Sprintf(" (on !%d)", d.StackedOn.Number)
 681		}
 682		if d.Draft {
 683			branch = "draft · " + branch
 684		}
 685		ref := cLink(fmt.Sprintf("!%d", d.Number), c.siteURL(repo.Path(), "mrs", strconv.FormatInt(d.Number, 10)))
 686		sec.rows = append(sec.rows, rowOf(ref, lead, cFlex(d.Title), review[m.ID], cMeta(branch, relAge(m.UpdatedAt, termNow()))))
 687	}
 688	other := "all"
 689	if state == "all" {
 690		other = "open"
 691	}
 692	return screen{sections: []section{sec}, actions: []action{
 693		{"New", []string{"mr", "create", repo.Path()}},
 694		{"Filter", []string{"mr", "list", repo.Path(), "--state", other}},
 695	}}
 696}
 697
 698// byWhom renders " by <user>", or nothing when the actor is unknown — an
 699// imported merge request carries a time but no local account.
 700func byWhom(user string) string {
 701	if user == "" {
 702		return ""
 703	}
 704	return " by " + user
 705}
 706
 707func runMRShow(c *Ctx, args []string) int {
 708	repo, mr, code := mrRef(c, args, policy.CanRead)
 709	if code >= 0 {
 710		return code
 711	}
 712	if len(args) != 2 {
 713		return c.usage()
 714	}
 715	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
 716	d, err := mrShowData(c, repo, mr)
 717	if err != nil {
 718		return c.fail(protocol.ExitFailure, "%v", err)
 719	}
 720	// The commits this MR carries: base..head, the diff's range.
 721	base := mrBase(dir, mr)
 722	d.Commits = mrCommits(dir, base, mr)
 723	d.StackedOn, d.Stacked = stackOf(c, repo, mr)
 724	if mr.State == "open" || mr.State == "source_gone" {
 725		if targetSHA, err := gitutil.ResolveRef(dir, "refs/heads/"+mr.TargetRef); err == nil {
 726			if g, err := MergeGates(c.Store, repo, mr, dir, targetSHA, mr.HeadSHA); err == nil {
 727				d.Gates = &g
 728			}
 729		}
 730	}
 731	var files []gitutil.NumStat
 732	if c.Term.Cols > 0 && !c.JSON && base != "" {
 733		files, _ = gitutil.DiffNumstat(dir, base, mrHeadRef(mr.Number))
 734	}
 735	return c.emitView(d, func(w io.Writer) { writeMRShow(c, w, repo, d) },
 736		func() screen { return mrShowScreen(c, repo, d, files) })
 737}
 738
 739// mrShowData is a merge request with its comments, reviews, checks and
 740// reactions; commits, stack and gates are filled in by the caller.
 741func mrShowData(c *Ctx, repo store.Repo, mr store.MR) (MRShow, error) {
 742	comments, err := c.Store.ListMRComments(mr.ID)
 743	if err != nil {
 744		return MRShow{}, err
 745	}
 746	reviews, err := c.Store.ListMRReviews(mr.ID)
 747	if err != nil {
 748		return MRShow{}, err
 749	}
 750	statuses, combined, err := c.Store.ChecksForCommit(repo.ID, mr.HeadSHA)
 751	if err != nil {
 752		return MRShow{}, err
 753	}
 754	unresolved, err := c.Store.UnresolvedThreadCount(mr.ID)
 755	if err != nil {
 756		return MRShow{}, err
 757	}
 758	var checks []CheckOut
 759	for _, st := range statuses {
 760		out := CheckOut{Context: st.Context, State: st.State, URL: st.TargetURL, UpdatedAt: st.UpdatedAt}
 761		if st.Duration > 0 {
 762			out.Duration = st.Duration.String()
 763		}
 764		checks = append(checks, out)
 765	}
 766	rx, err := c.Store.ReactionCounts("mr", mr.ID, c.User.ID)
 767	if err != nil {
 768		return MRShow{}, err
 769	}
 770	var cs []commentOut
 771	for _, cm := range comments {
 772		cs = append(cs, commentOut{cm.ID, cm.Author, cm.Body, cm.BodyFormat, cm.CreatedAt, wireKind(cm.Kind), reactionsOut(rx[cm.ID])})
 773	}
 774	var rs []ReviewOut
 775	counts := ReviewersWhoCount(c.Store, repo, reviews)
 776	for _, r := range reviews {
 777		rs = append(rs, ReviewOut{r.Reviewer, r.Verdict, r.Stale, counts[r.Reviewer], r.CreatedAt})
 778	}
 779	return MRShow{mrOut: mrToOut(repo, mr, true), Checks: checks, Combined: combined,
 780		UnresolvedThreads: unresolved, Reactions: reactionsOut(rx[0]), Comments: cs, Reviews: rs}, nil
 781}
 782
 783// mrBase is where a merge request's diff starts: the base recorded at merge,
 784// or the live merge base with its target. Empty when neither is known.
 785func mrBase(dir string, mr store.MR) string {
 786	if mr.MergedBase != "" {
 787		return mr.MergedBase
 788	}
 789	if b, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, mrHeadRef(mr.Number)); err == nil {
 790		return b
 791	}
 792	return ""
 793}
 794
 795// mrCommits is base..head with each commit's subject, when it can be read.
 796func mrCommits(dir, base string, mr store.MR) []CommitOut {
 797	if base == "" {
 798		return nil
 799	}
 800	shas, err := gitutil.RevListRange(dir, base, mrHeadRef(mr.Number))
 801	if err != nil {
 802		return nil
 803	}
 804	var commits []CommitOut
 805	for _, sha := range shas {
 806		subject := ""
 807		if raw, err := gitutil.ReadCommit(dir, sha); err == nil {
 808			if parsed, err := sig.ParseCommit(raw); err == nil {
 809				subject = parsed.Subject
 810			}
 811		}
 812		commits = append(commits, CommitOut{sha, subject})
 813	}
 814	return commits
 815}
 816
 817// writeMRShow is `mr show` as text.
 818func writeMRShow(c *Ctx, w io.Writer, repo store.Repo, d MRShow) {
 819	state := d.State
 820	if d.Draft {
 821		state = "draft"
 822	}
 823	v := c.view(w)
 824	v.title(fmt.Sprintf("!%d", d.Number), d.Title, state)
 825	v.fields(mrShowFields(c, repo, d)...)
 826
 827	v.body(d.Body, d.BodyFormat)
 828	v.reactions(d.Reactions)
 829	writeMRTables(c, w, v, d)
 830
 831	events := false
 832	for _, cm := range d.Comments {
 833		if cm.Kind != "system" {
 834			continue
 835		}
 836		if !events {
 837			io.WriteString(w, "\n")
 838			events = true
 839		}
 840		v.event(cm.Body, cm.BodyFormat, cm.CreatedAt)
 841	}
 842	for _, cm := range d.Comments {
 843		if cm.Kind == "system" {
 844			continue
 845		}
 846		v.comment(cm.ID, cm.Author, cm.CreatedAt, cm.Body, cm.BodyFormat)
 847		v.reactions(cm.Reactions)
 848	}
 849}
 850
 851// mrShowFields is every one-row fact as key, value pairs, including the
 852// unmet gates and the commit/check/review that only has a single row to
 853// show: separate fields calls each compute their own key width, so keeping
 854// them in one call keeps every key aligned.
 855func mrShowFields(c *Ctx, repo store.Repo, d MRShow) []string {
 856	stackedOn, stacked := mrStackLines(d)
 857	merged, closed, superseded := "", "", ""
 858	if d.MergedAt != "" {
 859		merged = c.when(d.MergedAt) + byWhom(d.MergedBy)
 860	}
 861	if d.ClosedAt != "" {
 862		closed = c.when(d.ClosedAt) + byWhom(d.ClosedBy)
 863	}
 864	if d.SupersededBy != 0 {
 865		superseded = fmt.Sprintf("!%d", d.SupersededBy)
 866	}
 867	queued, waiting := mrQueuedLines(c, d.Queued)
 868	unresolved := ""
 869	if d.UnresolvedThreads > 0 {
 870		unresolved = fmt.Sprintf("%d", d.UnresolvedThreads)
 871	}
 872	kv := []string{
 873		"author", d.Author + ", " + c.when(d.CreatedAt),
 874		"source", fmt.Sprintf("%s -> %s", d.Source, d.TargetRef),
 875		"head", fmt.Sprintf("%.10s", d.HeadSHA),
 876		"milestone", d.Milestone,
 877		"labels", strings.Join(d.Labels, ", "),
 878		"reviewers", strings.Join(d.ReviewRequests, ", "),
 879		"stacked on", stackedOn,
 880		"stacked", stacked,
 881		"merged", merged,
 882		"closed", closed,
 883		"superseded by", superseded,
 884		"queued to merge", queued,
 885		"waiting on", waiting,
 886		"unresolved threads", unresolved,
 887		"gates", gatesSummary(d.Gates),
 888	}
 889	if g := d.Gates; g != nil {
 890		for _, u := range g.Unmet {
 891			kv = append(kv, "unmet", u)
 892		}
 893	}
 894	if len(d.Commits) == 1 {
 895		kv = append(kv, "commit", fmt.Sprintf("%.10s %s", d.Commits[0].SHA, d.Commits[0].Subject))
 896	}
 897	if len(d.Checks) == 1 {
 898		x := d.Checks[0]
 899		dur := ""
 900		if x.Duration != "" {
 901			dur = " in " + x.Duration
 902		}
 903		kv = append(kv, "check", fmt.Sprintf("%s %s at %s%s", x.Context, x.State, c.when(x.UpdatedAt), dur))
 904	}
 905	if len(d.Reviews) == 1 {
 906		kv = append(kv, "review", reviewLine(d.Reviews[0])+" at "+c.when(d.Reviews[0].CreatedAt))
 907	}
 908	return append(kv, "url", c.siteURL(repo.Path(), "mrs", strconv.FormatInt(d.Number, 10)))
 909}
 910
 911// mrStackLines names the merge request this one is stacked on, and those
 912// stacked on it.
 913func mrStackLines(d MRShow) (stackedOn, stacked string) {
 914	if d.StackedOn != nil {
 915		stackedOn = fmt.Sprintf("!%d %s", d.StackedOn.Number, d.StackedOn.Title)
 916	}
 917	for _, k := range d.Stacked {
 918		if stacked != "" {
 919			stacked += ", "
 920		}
 921		stacked += fmt.Sprintf("!%d %s", k.Number, k.Title)
 922	}
 923	return stackedOn, stacked
 924}
 925
 926// mrQueuedLines is who queued the merge, how and when, and what it waits on.
 927func mrQueuedLines(c *Ctx, q *QueuedOut) (queued, waiting string) {
 928	if q == nil {
 929		return "", ""
 930	}
 931	queued = "by " + q.By
 932	if q.Strategy != "" {
 933		queued += " (" + q.Strategy + ")"
 934	}
 935	return queued + ", " + c.when(q.QueuedAt), q.Reason
 936}
 937
 938// gatesSummary is "met" or the unmet count, and whether fast-forward is possible.
 939func gatesSummary(g *GatesOut) string {
 940	if g == nil {
 941		return ""
 942	}
 943	ff := "fast-forward possible"
 944	if !g.FastForward {
 945		ff = "fast-forward not possible"
 946	}
 947	if len(g.Unmet) == 0 {
 948		return "met; " + ff
 949	}
 950	return fmt.Sprintf("%d unmet; %s", len(g.Unmet), ff)
 951}
 952
 953// writeMRTables lists commits, checks and reviews when there is more than
 954// one of each; a single one is a field instead.
 955func writeMRTables(c *Ctx, w io.Writer, v *view, d MRShow) {
 956	if len(d.Commits) > 1 {
 957		v.section(fmt.Sprintf("commits (%d)", len(d.Commits)))
 958		tb := c.table(w, "SHA", "SUBJECT")
 959		for _, cm := range d.Commits {
 960			tb.row(cRef(fmt.Sprintf("%.10s", cm.SHA)), cFlex(cm.Subject))
 961		}
 962		tb.flush()
 963	}
 964	if len(d.Checks) > 1 {
 965		v.section(fmt.Sprintf("checks (%d)", len(d.Checks)))
 966		tb := c.table(w, "CHECK", "STATE", "DURATION", "UPDATED")
 967		for _, x := range d.Checks {
 968			tb.row(cText(x.Context), cState(x.State), cText(x.Duration), cText(c.when(x.UpdatedAt)))
 969		}
 970		tb.flush()
 971	}
 972	if len(d.Reviews) > 1 {
 973		v.section(fmt.Sprintf("reviews (%d)", len(d.Reviews)))
 974		tb := c.table(w, "REVIEWER", "VERDICT", "WHEN")
 975		for _, r := range d.Reviews {
 976			verdict := r.Verdict
 977			if r.Stale {
 978				verdict += " (stale)"
 979			}
 980			if !r.Counts {
 981				verdict += " (advisory)"
 982			}
 983			tb.row(cText(r.Reviewer), cState(verdict), cText(c.when(r.CreatedAt)))
 984		}
 985		tb.flush()
 986	}
 987}
 988
 989// reviewLine renders one review as fields prose: "reviewer verdict
 990// (stale) (advisory) at when".
 991func reviewLine(r ReviewOut) string {
 992	s := r.Reviewer + " " + r.Verdict
 993	if r.Stale {
 994		s += " (stale)"
 995	}
 996	if !r.Counts {
 997		s += " (advisory: no write access)"
 998	}
 999	return s
1000}
1001
1002func runMRDiff(c *Ctx, args []string) int {
1003	repo, mr, code := mrRef(c, args, policy.CanRead)
1004	if code >= 0 {
1005		return code
1006	}
1007	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
1008	head := mrHeadRef(mr.Number)
1009	if _, err := gitutil.ResolveRef(dir, head); err != nil {
1010		return c.fail(protocol.ExitFailure, "the head of !%d is no longer in the repository; its diff is not available", mr.Number)
1011	}
1012	// After a merge (especially fast-forward) the live merge-base equals
1013	// the head and the diff would vanish; use the recorded base instead.
1014	base := mr.MergedBase
1015	if base == "" {
1016		b, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, head)
1017		if err != nil {
1018			return c.fail(protocol.ExitFailure, "%v", err)
1019		}
1020		base = b
1021	}
1022	patch, truncated, err := gitutil.Diff(dir, base, head, 4<<20)
1023	if err != nil {
1024		return c.fail(protocol.ExitFailure, "%v", err)
1025	}
1026	fmt.Fprint(c.Stdout, c.Term.diff(patch))
1027	if truncated {
1028		fmt.Fprintln(c.Stderr, "diff truncated at 4 MiB; fetch the branch for the rest")
1029	}
1030	return protocol.ExitOK
1031}
1032
1033func runMREdit(c *Ctx, args []string) int {
1034	rest, title, body, format, fl, code := editText(c, args, "mr", "--superseded-by")
1035	if code >= 0 {
1036		return code
1037	}
1038	repo, mr, code := mrRef(c, rest, policy.CanRead)
1039	if code >= 0 {
1040		return code
1041	}
1042	if code := refuseArchived(c, repo); code >= 0 {
1043		return code
1044	}
1045	if code := authorOrWrite(c, repo, mr.Author, "edit this merge request"); code >= 0 {
1046		return code
1047	}
1048	var clearSuperseded bool
1049	var supersededBy int64
1050	if fl.Has("--superseded-by") {
1051		if mr.State != "closed" {
1052			return c.fail(protocol.ExitUsage, "only a closed merge request can be superseded")
1053		}
1054		if v := fl.Value("--superseded-by"); v == "none" {
1055			clearSuperseded = true
1056		} else {
1057			supersededBy, code = resolveSupersededBy(c, repo, mr.Number, v)
1058			if code >= 0 {
1059				return code
1060			}
1061		}
1062	}
1063	if err := c.Store.UpdateMRText(mr.ID, title, body, format); err != nil {
1064		return c.fail(protocol.ExitFailure, "%v", err)
1065	}
1066	if clearSuperseded {
1067		if err := c.Store.SetSupersededBy(mr.ID, 0); err != nil {
1068			return c.fail(protocol.ExitFailure, "%v", err)
1069		}
1070	} else if supersededBy != 0 {
1071		if err := c.Store.SetSupersededBy(mr.ID, supersededBy); err != nil {
1072			return c.fail(protocol.ExitFailure, "%v", err)
1073		}
1074	}
1075	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.edited", fmt.Sprintf(`{"number":%d}`, mr.Number))
1076	return c.emit(map[string]any{"number": mr.Number}, func(w io.Writer) {
1077		fmt.Fprintf(w, "edited %s!%d\n", repo.Path(), mr.Number)
1078	})
1079}
1080
1081// runMRRetarget moves an open merge request onto another branch of the
1082// same repository.
1083func runMRRetarget(c *Ctx, args []string) int {
1084	if len(args) != 3 {
1085		return c.usage()
1086	}
1087	repo, mr, code := mrRef(c, args[:2], policy.CanRead)
1088	if code >= 0 {
1089		return code
1090	}
1091	if code := refuseArchived(c, repo); code >= 0 {
1092		return code
1093	}
1094	if code := authorOrWrite(c, repo, mr.Author, "retarget this merge request"); code >= 0 {
1095		return code
1096	}
1097	if mr.State == "merged" || mr.State == "closed" {
1098		return c.fail(protocol.ExitUsage, "!%d is %s; only an open merge request can be retargeted", mr.Number, mr.State)
1099	}
1100	target := args[2]
1101	if target == mr.TargetRef {
1102		return c.fail(protocol.ExitUsage, "!%d already targets %s", mr.Number, target)
1103	}
1104	if mr.SourceRepoID == repo.ID && target == mr.SourceRef {
1105		return c.fail(protocol.ExitUsage, "%s is the source branch of !%d", target, mr.Number)
1106	}
1107	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
1108	if _, err := gitutil.ResolveRef(dir, "refs/heads/"+target); err != nil {
1109		return c.fail(protocol.ExitNotFound, "branch %s not found in %s", target, repo.Path())
1110	}
1111	// The diff, the commit list and the merge gates all derive their base
1112	// from the target on every read, so the only thing to check here is
1113	// that a base exists at all: without one there is nothing to show and
1114	// nothing to merge.
1115	base, err := gitutil.MergeBase(dir, "refs/heads/"+target, mrHeadRef(mr.Number))
1116	if err != nil || base == "" {
1117		return c.fail(protocol.ExitUsage, "%s shares no history with the head of !%d", target, mr.Number)
1118	}
1119	old := mr.TargetRef
1120	if err := c.Store.SetMRTarget(mr.ID, target); err != nil {
1121		return c.fail(protocol.ExitFailure, "%v", err)
1122	}
1123	c.Store.AddMRSystemComment(mr.ID, c.User.ID, fmt.Sprintf("retargeted from %s to %s", old, target))
1124	// A queued merge was asked for against the old target. Someone who
1125	// could not merge it themselves does not get to point it elsewhere.
1126	if mr.QueuedAt != "" {
1127		grant, err := c.Store.AccessRole(repo.ID, c.User.ID)
1128		if err != nil || !policy.CanWrite(c.User, repo, grant) {
1129			mergeQueueMu.Lock()
1130			dequeueWithReason(c.Store, mr, fmt.Sprintf("%s retargeted it to %s and cannot merge into %s", c.User.Username, target, repo.Path()))
1131			mergeQueueMu.Unlock()
1132		}
1133	}
1134	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.retargeted",
1135		fmt.Sprintf(`{"number":%d,"from":%q,"to":%q}`, mr.Number, old, target))
1136	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
1137		notify(c, parts, notice{repo: repo, kind: "mr", number: mr.Number,
1138			subject: mrSubject(repo, mr.Number, mr.Title),
1139			action:  fmt.Sprintf("retargeted !%d from %s to %s", mr.Number, old, target),
1140			path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
1141	}
1142	return c.emit(map[string]any{"number": mr.Number, "target_ref": target, "merge_base": base}, func(w io.Writer) {
1143		fmt.Fprintf(w, "retargeted %s!%d from %s to %s (base %.10s)\n", repo.Path(), mr.Number, old, target, base)
1144	})
1145}
1146
1147func runMRComment(c *Ctx, args []string) int {
1148	return runComment(c, args, mrThread, "mr",
1149		func(rest []string) (store.Repo, int64, int64, string, int) {
1150			repo, mr, code := mrRef(c, rest, policy.CanRead)
1151			return repo, mr.ID, mr.Number, mr.Title, code
1152		},
1153		c.Store.AddMRComment, c.Store.MRParticipants)
1154}
1155
1156func runMRReview(c *Ctx, args []string) int {
1157	verdict, discard := "", false
1158	var rest []string
1159	for _, a := range args {
1160		switch a {
1161		case "--approve":
1162			verdict = "approve"
1163		case "--request-changes":
1164			verdict = "request_changes"
1165		case "--comment":
1166			verdict = "comment"
1167		case "--discard":
1168			discard = true
1169		default:
1170			rest = append(rest, a)
1171		}
1172	}
1173	if discard && verdict != "" {
1174		return c.fail(protocol.ExitUsage, "--discard throws the batch away; it takes no verdict")
1175	}
1176	if verdict == "" && !discard {
1177		return c.usage()
1178	}
1179	repo, mr, code := mrRef(c, rest, policy.CanRead)
1180	if code >= 0 {
1181		return code
1182	}
1183	if code := refuseArchived(c, repo); code >= 0 {
1184		return code
1185	}
1186	if mr.State != "open" {
1187		return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
1188	}
1189	// Throwing the batch away is not a review, so it stops here: no
1190	// verdict, no event, nobody told about comments nobody ever saw.
1191	if discard {
1192		n, err := c.Store.DiscardPendingComments(mr.ID, c.User.ID)
1193		if err != nil {
1194			return c.fail(protocol.ExitFailure, "%v", err)
1195		}
1196		return c.emit(map[string]any{"number": mr.Number, "discarded": n}, func(w io.Writer) {
1197			fmt.Fprintf(w, "discarded %d pending comment(s) on %s!%d\n", n, repo.Path(), mr.Number)
1198		})
1199	}
1200	if err := c.Store.AddMRReview(mr.ID, c.User.ID, verdict, mr.HeadSHA); err != nil {
1201		return c.fail(protocol.ExitFailure, "%v", err)
1202	}
1203	// The batch the reviewer composed becomes visible with the verdict,
1204	// which is what makes it one review rather than a trickle.
1205	published, err := c.Store.PublishPendingComments(mr.ID, c.User.ID)
1206	if err != nil {
1207		return c.fail(protocol.ExitFailure, "%v", err)
1208	}
1209	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.reviewed",
1210		fmt.Sprintf(`{"number":%d,"verdict":%q}`, mr.Number, verdict))
1211	TryQueuedMerge(c.Store, c.Cfg, mr.ID)
1212	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
1213		notify(c, parts, notice{repo: repo, kind: "mr", number: mr.Number,
1214			subject: mrSubject(repo, mr.Number, mr.Title),
1215			action:  reviewAction(mr.Number, verdict, published),
1216			path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
1217	}
1218	// Whether the merge gates will count this verdict, said now rather
1219	// than at the refusal (#199).
1220	counts := ReviewersWhoCount(c.Store, repo, []store.MRReview{{Reviewer: c.User.Username}})[c.User.Username]
1221	return c.emit(map[string]any{"number": mr.Number, "verdict": verdict, "published": published, "counts": counts}, func(w io.Writer) {
1222		fmt.Fprintf(w, "reviewed %s!%d: %s", repo.Path(), mr.Number, verdict)
1223		if published > 0 {
1224			fmt.Fprintf(w, " (%d comment(s))", published)
1225		}
1226		if !counts {
1227			fmt.Fprintf(w, " (advisory: no write access on %s, so the merge gates do not count it)", repo.Path())
1228		}
1229		fmt.Fprintln(w)
1230	})
1231}
1232
1233// runMRReviewRequest is issue assign's counterpart for merge requests: it
1234// pushes a merge request into a specific person's review queue and inbox
1235// directly, rather than waiting for them to be otherwise involved (#145).
1236func runMRReviewRequest(c *Ctx, args []string) int {
1237	rest, adds, removes, err := addRemoveFlags(args)
1238	if err != nil {
1239		return c.failInput(err)
1240	}
1241	if len(adds)+len(removes) == 0 {
1242		return c.usage()
1243	}
1244	repo, mr, code := mrRef(c, rest, policy.CanWrite)
1245	if code >= 0 {
1246		return code
1247	}
1248	if code := refuseArchived(c, repo); code >= 0 {
1249		return code
1250	}
1251	resolve := func(name string) (store.User, int) {
1252		u, err := c.Store.UserByUsername(name)
1253		if errors.Is(err, store.ErrNotFound) {
1254			return u, c.fail(protocol.ExitNotFound, "no such user %q", name)
1255		}
1256		if err != nil {
1257			return u, c.fail(protocol.ExitFailure, "%v", err)
1258		}
1259		return u, -1
1260	}
1261	// Notified on every return, not just success: a name later in --add
1262	// that fails to resolve or lacks access must not silence the people
1263	// already added earlier in the same call.
1264	var added []store.User
1265	defer func() {
1266		if len(added) == 0 {
1267			return
1268		}
1269		ids := make([]int64, len(added))
1270		for i, u := range added {
1271			ids[i] = u.ID
1272		}
1273		notify(c, ids, notice{repo: repo, kind: "mr", number: mr.Number,
1274			subject: mrSubject(repo, mr.Number, mr.Title),
1275			action:  fmt.Sprintf("asked for a review on !%d", mr.Number),
1276			path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
1277	}()
1278	for _, name := range adds {
1279		u, code := resolve(name)
1280		if code >= 0 {
1281			return code
1282		}
1283		// A review request that lands nowhere the recipient can see it is
1284		// worse than useless: it looks like the ask went through.
1285		grant, err := c.Store.AccessRole(repo.ID, u.ID)
1286		if err != nil {
1287			return c.fail(protocol.ExitFailure, "%v", err)
1288		}
1289		if !policy.CanRead(u, repo, grant) {
1290			return c.fail(protocol.ExitDenied, "%s cannot read %s", name, repo.Path())
1291		}
1292		if err := c.Store.SetMRReviewRequest(mr.ID, u.ID, true); err != nil {
1293			return c.fail(protocol.ExitFailure, "%v", err)
1294		}
1295		added = append(added, u)
1296	}
1297	for _, name := range removes {
1298		u, code := resolve(name)
1299		if code >= 0 {
1300			return code
1301		}
1302		if err := c.Store.SetMRReviewRequest(mr.ID, u.ID, false); err != nil {
1303			if errors.Is(err, store.ErrNotFound) {
1304				return c.fail(protocol.ExitNotFound, "%s is not a requested reviewer", name)
1305			}
1306			return c.fail(protocol.ExitFailure, "%v", err)
1307		}
1308	}
1309	updated, err := c.Store.MRByNumber(repo.ID, mr.Number)
1310	if err != nil {
1311		return c.fail(protocol.ExitFailure, "%v", err)
1312	}
1313	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.review_requested",
1314		fmt.Sprintf(`{"number":%d,"reviewers":%s}`, mr.Number, jsonStrings(updated.ReviewRequests)))
1315	return c.emit(map[string]any{"number": mr.Number, "reviewers": updated.ReviewRequests}, func(w io.Writer) {
1316		fmt.Fprintf(w, "requested reviewers on %s!%d: %s\n", repo.Path(), mr.Number, strings.Join(updated.ReviewRequests, ", "))
1317	})
1318}
1319
1320// runMRLabel is issue label's counterpart for merge requests: the label
1321// set is the repository's (or its org's), shared with the issues (#231).
1322func runMRLabel(c *Ctx, args []string) int {
1323	rest, adds, removes, err := addRemoveFlags(args)
1324	if err != nil {
1325		return c.failInput(err)
1326	}
1327	if len(adds)+len(removes) == 0 {
1328		return c.usage()
1329	}
1330	repo, mr, code := mrRef(c, rest, policy.CanWrite)
1331	if code >= 0 {
1332		return code
1333	}
1334	if code := refuseArchived(c, repo); code >= 0 {
1335		return code
1336	}
1337	for _, l := range adds {
1338		if err := c.Store.SetMRLabel(repo, mr.ID, l, true); err != nil {
1339			return c.fail(protocol.ExitFailure, "%v", err)
1340		}
1341	}
1342	for _, l := range removes {
1343		if err := c.Store.SetMRLabel(repo, mr.ID, l, false); err != nil {
1344			if errors.Is(err, store.ErrNotFound) {
1345				return c.fail(protocol.ExitNotFound, "%v", err)
1346			}
1347			return c.fail(protocol.ExitFailure, "%v", err)
1348		}
1349	}
1350	updated, err := c.Store.MRByNumber(repo.ID, mr.Number)
1351	if err != nil {
1352		return c.fail(protocol.ExitFailure, "%v", err)
1353	}
1354	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.labeled",
1355		fmt.Sprintf(`{"number":%d,"labels":%s}`, mr.Number, jsonStrings(updated.Labels)))
1356	return c.emit(map[string]any{"number": mr.Number, "labels": updated.Labels}, func(w io.Writer) {
1357		fmt.Fprintf(w, "labels on %s!%d: %s\n", repo.Path(), mr.Number, strings.Join(updated.Labels, ", "))
1358	})
1359}
1360
1361func runMRMerge(c *Ctx, args []string) int {
1362	f, err := c.parseArgs(args, flagSpec{Values: []string{"--strategy"}, Bools: []string{"--when-ready", "--cancel"},
1363		MaxPos: -1, Usage: c.Cmd.Usage})
1364	if err != nil {
1365		return c.fail(protocol.ExitUsage, "%v", err)
1366	}
1367	strategy, rest := f.Value("--strategy"), f.Pos
1368	valid := map[string]bool{"": true, "ff": true, "merge": true, "squash": true, "rebase": true}
1369	if !valid[strategy] {
1370		return c.fail(protocol.ExitUsage, "--strategy must be ff, merge, squash, or rebase")
1371	}
1372	if f.Has("--cancel") && (f.Has("--when-ready") || f.Has("--strategy")) {
1373		return c.fail(protocol.ExitUsage, "--cancel takes no other flag")
1374	}
1375	repo, mr, code := mrRef(c, rest, policy.CanWrite)
1376	if code >= 0 {
1377		return code
1378	}
1379	switch {
1380	case f.Has("--cancel"):
1381		return cancelQueuedMerge(c, repo, mr)
1382	case f.Has("--when-ready"):
1383		return queueMerge(c, repo, mr, strategy)
1384	}
1385	return mergeMR(c, repo, mr, strategy)
1386}
1387
1388// mergeMR merges mr now as c.User, or refuses saying why. The queue runs
1389// it too, as the user who queued the merge.
1390func mergeMR(c *Ctx, repo store.Repo, mr store.MR, strategy string) int {
1391	if code := refuseArchived(c, repo); code >= 0 {
1392		return code
1393	}
1394	if mr.State != "open" && mr.State != "source_gone" {
1395		return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
1396	}
1397
1398	p := &mergePlan{repo: repo, mr: mr, strategy: strategy}
1399	p.dir = RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
1400	p.targetRef = "refs/heads/" + mr.TargetRef
1401	var err error
1402	p.targetSHA, err = gitutil.ResolveRef(p.dir, p.targetRef)
1403	if err != nil {
1404		return c.fail(protocol.ExitFailure, "target branch %s: %v", mr.TargetRef, err)
1405	}
1406	p.headSHA, err = gitutil.ResolveRef(p.dir, mrHeadRef(mr.Number))
1407	if err != nil {
1408		return c.fail(protocol.ExitFailure, "MR head ref: %v", err)
1409	}
1410
1411	// Merge gates: draft, checks, approvals, CODEOWNERS, resolved threads,
1412	// all reported at once.
1413	if code := c.reviewGates(repo, mr, p.dir, p.targetSHA, p.headSHA); code >= 0 {
1414		return code
1415	}
1416
1417	upToDate, err := gitutil.IsAncestor(p.dir, p.headSHA, p.targetSHA)
1418	if err != nil {
1419		return c.fail(protocol.ExitFailure, "%v", err)
1420	}
1421	if upToDate {
1422		return c.recordAlreadyMerged(p)
1423	}
1424	p.ffPossible, err = gitutil.IsAncestor(p.dir, p.targetSHA, p.headSHA)
1425	if err != nil {
1426		return c.fail(protocol.ExitFailure, "%v", err)
1427	}
1428
1429	if repo.Settings.RequireSignedCommits {
1430		if code := c.requireSignedMerge(p); code >= 0 {
1431			return code
1432		}
1433	}
1434	p.chooseStrategy()
1435	if code := c.mergerIdentity(p); code >= 0 {
1436		return code
1437	}
1438	newSHA, code := c.mergedCommit(p)
1439	if code >= 0 {
1440		return code
1441	}
1442	stack, code := c.stackForMerge(p)
1443	if code >= 0 {
1444		return code
1445	}
1446
1447	// CAS so a concurrent push between our read and this write fails the
1448	// merge instead of silently discarding the push.
1449	if err := gitutil.UpdateRefCAS(p.dir, p.targetRef, newSHA, p.targetSHA); err != nil {
1450		return c.fail(protocol.ExitFailure, "target branch moved during merge; retry: %v", err)
1451	}
1452	if err := c.Store.MarkMerged(mr.ID, p.targetSHA, newSHA, c.User.ID, ""); err != nil {
1453		return c.fail(protocol.ExitFailure, "%v", err)
1454	}
1455	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d,"sha":%q}`, mr.Number, newSHA))
1456	MarkLandedMRs(c.Store, c.Cfg, repo, c.User.ID, mr.TargetRef, p.targetSHA, newSHA)
1457	c.retargetStack(p, stack)
1458	c.afterMerge(p, newSHA)
1459	return c.emit(map[string]any{"number": mr.Number, "strategy": p.strategy, "sha": newSHA}, func(w io.Writer) {
1460		fmt.Fprintf(w, "merged %s!%d into %s (%s) at %.10s\n", repo.Path(), mr.Number, mr.TargetRef, p.strategy, newSHA)
1461	})
1462}
1463
1464// mergePlan is a merge in progress: what is merged where, how, and as whom.
1465type mergePlan struct {
1466	repo                  store.Repo
1467	mr                    store.MR
1468	dir, targetRef        string
1469	targetSHA, headSHA    string
1470	ffPossible            bool
1471	strategy, mergerEmail string
1472}
1473
1474// recordAlreadyMerged handles a head that is already on the target: merged
1475// by hand and pushed, or a merge whose ref update landed and whose record
1476// did not. Recording it rather than refusing means a merge request cannot be
1477// stuck open with no way to close it as merged (#108).
1478func (c *Ctx) recordAlreadyMerged(p *mergePlan) int {
1479	mr := p.mr
1480	if err := c.Store.MarkMerged(mr.ID, p.targetSHA, p.headSHA, c.User.ID, ""); err != nil {
1481		return c.fail(protocol.ExitFailure, "%v", err)
1482	}
1483	c.Store.RecordEvent(p.repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d}`, mr.Number))
1484	return c.emit(map[string]any{"number": mr.Number, "strategy": "recorded", "sha": p.headSHA}, func(w io.Writer) {
1485		fmt.Fprintf(w, "%s already contains !%d; recorded as merged at %.10s\n", mr.TargetRef, mr.Number, p.headSHA)
1486	})
1487}
1488
1489// requireSignedMerge applies the signature policy matrix: with
1490// require_signed_commits, only fast-forward is allowed — squash,
1491// rebase-replay, and merge commits are all server-created and unsigned,
1492// violating the branch's own policy — and every landed commit must be
1493// verified. An explicit rebase when fast-forward is already possible IS a
1494// fast-forward (nothing is rewritten), so it stays legal. Returns -1 to
1495// proceed, with the strategy set to fast-forward.
1496func (c *Ctx) requireSignedMerge(p *mergePlan) int {
1497	repo, mr := p.repo, p.mr
1498	if c.Source == queueSource && !p.ffPossible {
1499		return c.fail(protocol.ExitDenied,
1500			"%s is behind %s and %s requires signed commits, so the server cannot rebase it; rebase and push, and the merge stays queued",
1501			mr.SourceRef, mr.TargetRef, repo.Path())
1502	}
1503	if p.strategy == "merge" || p.strategy == "squash" || !p.ffPossible {
1504		return c.fail(protocol.ExitDenied,
1505			"%s requires signed commits, so only fast-forward merges are allowed; rebase %s onto %s locally, re-push, and merge again",
1506			repo.Path(), mr.SourceRef, mr.TargetRef)
1507	}
1508	p.strategy = "ff"
1509	commits, err := gitutil.RevListRange(p.dir, p.targetSHA, p.headSHA)
1510	if err != nil {
1511		return c.fail(protocol.ExitFailure, "%v", err)
1512	}
1513	for _, sha := range commits {
1514		state, err := c.commitSignatureState(repo, p.dir, sha)
1515		if err != nil {
1516			return c.fail(protocol.ExitFailure, "%v", err)
1517		}
1518		if state != "verified" {
1519			return c.fail(protocol.ExitDenied,
1520				"%s requires signed commits: %.10s is %s", repo.Path(), sha, state)
1521		}
1522	}
1523	return -1
1524}
1525
1526// commitSignatureState is a commit's signature verification state, such as "verified".
1527func (c *Ctx) commitSignatureState(repo store.Repo, dir, sha string) (sig.State, error) {
1528	raw, err := gitutil.ReadCommit(dir, sha)
1529	if err != nil {
1530		return "", err
1531	}
1532	parsed, err := sigParse(raw)
1533	if err != nil {
1534		return "", err
1535	}
1536	res, err := VerifyCommitCached(c.Store, repo, parsed, sha)
1537	if err != nil {
1538		return "", err
1539	}
1540	return res.State, nil
1541}
1542
1543// chooseStrategy fills in the default strategy: fast-forward when possible,
1544// otherwise a merge commit. A rebase onto an ancestor has nothing to
1545// rewrite, so it is a fast-forward, which keeps the original commits and
1546// their signatures.
1547func (p *mergePlan) chooseStrategy() {
1548	if p.strategy == "" {
1549		if p.ffPossible {
1550			p.strategy = "ff"
1551		} else {
1552			p.strategy = "merge"
1553		}
1554	}
1555	if p.strategy == "rebase" && p.ffPossible {
1556		p.strategy = "ff"
1557	}
1558}
1559
1560// mergerIdentity sets the email every server-created commit is committed
1561// under: the merger's verified primary one. Returns -1 to proceed.
1562func (c *Ctx) mergerIdentity(p *mergePlan) int {
1563	if p.strategy == "ff" {
1564		return -1
1565	}
1566	email, err := c.Store.PrimaryVerifiedEmail(c.User.ID)
1567	if err != nil {
1568		return c.fail(protocol.ExitFailure, "%v", err)
1569	}
1570	if email == "" {
1571		return c.fail(protocol.ExitDenied,
1572			"%s merges create commits carrying your identity: verify a primary email first (or use a fast-forward merge)", p.strategy)
1573	}
1574	p.mergerEmail = email
1575	return -1
1576}
1577
1578// mergedCommit is the commit the target moves to under the plan's strategy.
1579// The code is -1 unless the merge is refused.
1580func (c *Ctx) mergedCommit(p *mergePlan) (string, int) {
1581	switch p.strategy {
1582	case "ff":
1583		if !p.ffPossible {
1584			return "", c.fail(protocol.ExitUsage,
1585				"fast-forward not possible: %s has diverged from the MR head; merge with the merge strategy, or rebase and push again", p.mr.TargetRef)
1586		}
1587		return p.headSHA, -1
1588	case "merge":
1589		return c.mergeCommit(p)
1590	case "squash":
1591		return c.squashCommit(p)
1592	case "rebase":
1593		return c.rebaseCommits(p)
1594	}
1595	return "", -1
1596}
1597
1598// mergedTree is the tree of the target and head merged, refusing on conflict.
1599func (c *Ctx) mergedTree(p *mergePlan) (string, int) {
1600	tree, conflict, err := gitutil.MergeTree(p.dir, p.targetSHA, p.headSHA)
1601	if err != nil {
1602		return "", c.fail(protocol.ExitFailure, "%v", err)
1603	}
1604	if conflict {
1605		return "", c.fail(protocol.ExitUsage,
1606			"merge conflicts between %s and the MR head; resolve locally and re-push", p.mr.TargetRef)
1607	}
1608	return tree, -1
1609}
1610
1611func (c *Ctx) mergeCommit(p *mergePlan) (string, int) {
1612	tree, code := c.mergedTree(p)
1613	if code >= 0 {
1614		return "", code
1615	}
1616	mr := p.mr
1617	msg := fmt.Sprintf("Merge request !%d: %s\n\nMerged %s into %s", mr.Number, mr.Title, mr.SourceRef, mr.TargetRef)
1618	sha, err := gitutil.CommitTree(p.dir, tree, []string{p.targetSHA, p.headSHA}, c.User.Username, p.mergerEmail, msg)
1619	if err != nil {
1620		return "", c.fail(protocol.ExitFailure, "%v", err)
1621	}
1622	return sha, -1
1623}
1624
1625// squashCommit is one new commit with the merged tree. Authorship credit
1626// goes to the MR author (their verified identity when they have one); the
1627// committer is the merger.
1628func (c *Ctx) squashCommit(p *mergePlan) (string, int) {
1629	var tree string
1630	if p.ffPossible {
1631		t, err := gitutil.ResolveTree(p.dir, p.headSHA)
1632		if err != nil {
1633			return "", c.fail(protocol.ExitFailure, "%v", err)
1634		}
1635		tree = t
1636	} else {
1637		t, code := c.mergedTree(p)
1638		if code >= 0 {
1639			return "", code
1640		}
1641		tree = t
1642	}
1643	mr := p.mr
1644	authorName, authorEmail := c.User.Username, p.mergerEmail
1645	if author, err := c.Store.UserByUsername(mr.Author); err == nil {
1646		if ae, err := c.Store.PrimaryVerifiedEmail(author.ID); err == nil && ae != "" {
1647			authorName, authorEmail = author.Username, ae
1648		}
1649	}
1650	msg := fmt.Sprintf("%s (!%d)", mr.Title, mr.Number)
1651	if mr.Body != "" {
1652		msg += "\n\n" + mr.Body
1653	}
1654	sha, err := gitutil.CommitTreeIdent(p.dir, tree, []string{p.targetSHA},
1655		authorName, authorEmail, "", c.User.Username, p.mergerEmail, msg)
1656	if err != nil {
1657		return "", c.fail(protocol.ExitFailure, "%v", err)
1658	}
1659	return sha, -1
1660}
1661
1662// rebaseCommits replays the merge request's commits, oldest first, onto the
1663// target, keeping each one's author.
1664func (c *Ctx) rebaseCommits(p *mergePlan) (string, int) {
1665	commits, err := gitutil.RevListRange(p.dir, p.targetSHA, p.headSHA)
1666	if err != nil {
1667		return "", c.fail(protocol.ExitFailure, "%v", err)
1668	}
1669	slices.Reverse(commits)
1670	onto := p.targetSHA
1671	for _, sha := range commits {
1672		next, code := c.replayCommit(p, sha, onto)
1673		if code >= 0 {
1674			return "", code
1675		}
1676		onto = next
1677	}
1678	return onto, -1
1679}
1680
1681// replayCommit applies one commit onto `onto` as a new commit with its
1682// author, message and date, committed by the merger.
1683func (c *Ctx) replayCommit(p *mergePlan, sha, onto string) (string, int) {
1684	parents, err := gitutil.CommitParents(p.dir, sha)
1685	if err != nil {
1686		return "", c.fail(protocol.ExitFailure, "%v", err)
1687	}
1688	if len(parents) > 1 {
1689		return "", c.fail(protocol.ExitUsage,
1690			"the MR contains merge commit %.10s; a rebase merge needs linear history — choose the merge or squash strategy", sha)
1691	}
1692	base := onto // root commit: replay against the new tip itself
1693	if len(parents) == 1 {
1694		base = parents[0]
1695	}
1696	tree, conflict, err := gitutil.MergeTreeOnto(p.dir, base, onto, sha)
1697	if err != nil {
1698		return "", c.fail(protocol.ExitFailure, "%v", err)
1699	}
1700	if conflict {
1701		return "", c.fail(protocol.ExitUsage,
1702			"commit %.10s does not apply cleanly onto %s; rebase locally and re-push", sha, p.mr.TargetRef)
1703	}
1704	aName, aEmail, aDate, err := gitutil.AuthorIdent(p.dir, sha)
1705	if err != nil {
1706		return "", c.fail(protocol.ExitFailure, "%v", err)
1707	}
1708	msg, err := gitutil.CommitMessage(p.dir, sha)
1709	if err != nil {
1710		return "", c.fail(protocol.ExitFailure, "%v", err)
1711	}
1712	next, err := gitutil.CommitTreeIdent(p.dir, tree, []string{onto},
1713		aName, aEmail, aDate, c.User.Username, p.mergerEmail, msg)
1714	if err != nil {
1715		return "", c.fail(protocol.ExitFailure, "%v", err)
1716	}
1717	return next, -1
1718}
1719
1720// stackForMerge is the merge requests stacked on this one. A stacked merge
1721// request's diff is against this branch. After a fast-forward or merge
1722// commit the same commits are on the target and its diff is unchanged
1723// there; after a squash or rebase they are not, and the stack would carry
1724// this merge request's changes a second time. Refuse rather than leave the
1725// stack wrong.
1726func (c *Ctx) stackForMerge(p *mergePlan) ([]store.MR, int) {
1727	mr := p.mr
1728	var stack []store.MR
1729	if mr.SourceRepoID == p.repo.ID {
1730		stack, _ = c.Store.OpenMRsByTarget(p.repo.ID, mr.SourceRef)
1731	}
1732	if len(stack) > 0 && (p.strategy == "squash" || p.strategy == "rebase") {
1733		var nums []string
1734		for _, k := range stack {
1735			nums = append(nums, fmt.Sprintf("!%d", k.Number))
1736		}
1737		return nil, c.fail(protocol.ExitUsage,
1738			"%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",
1739			fmt.Sprintf("!%d", mr.Number), strings.Join(nums, ", "), p.strategy, mr.SourceRef)
1740	}
1741	return stack, -1
1742}
1743
1744// retargetStack moves the stack up: whatever targeted this branch now
1745// targets what it merged into, reviews intact, since that diff is the one
1746// they were of.
1747func (c *Ctx) retargetStack(p *mergePlan, stack []store.MR) {
1748	repo, mr := p.repo, p.mr
1749	for _, k := range stack {
1750		if err := c.Store.RetargetKeepingReviews(k.ID, mr.TargetRef); err != nil {
1751			continue
1752		}
1753		c.Store.AddMRSystemComment(k.ID, c.User.ID, fmt.Sprintf("retargeted from %s to %s: !%d merged", mr.SourceRef, mr.TargetRef, mr.Number))
1754		if parts, err := c.Store.MRParticipants(k.ID); err == nil {
1755			notify(c, parts, notice{repo: repo, kind: "mr", number: k.Number,
1756				subject: mrSubject(repo, k.Number, k.Title),
1757				action:  fmt.Sprintf("retargeted !%d from %s to %s: !%d merged", k.Number, mr.SourceRef, mr.TargetRef, mr.Number),
1758				path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), k.Number)})
1759		}
1760	}
1761}
1762
1763// afterMerge does the work a push of the target would have done.
1764func (c *Ctx) afterMerge(p *mergePlan, newSHA string) {
1765	repo, mr := p.repo, p.mr
1766	// Merges bypass receive-pack, so the commit-message issue actions
1767	// (closes #N, references) run here for the newly landed commits. The
1768	// description is scanned after them, so a commit wins the attribution
1769	// when both name the same issue.
1770	if mr.TargetRef == repo.DefaultBranch {
1771		ProcessCommitMessages(c.Store, p.dir, repo, c.User.ID, c.Scope, p.targetSHA, newSHA)
1772		ProcessMRDescription(c.Store, repo, mr, c.User.ID, c.Scope)
1773		RecordLandedCommits(c.Store, p.dir, repo, p.targetSHA, newSHA)
1774		c.Store.RequestSymbolIndex(repo.ID, false)
1775	}
1776	// A merge moves the ref directly, so it never reaches post-receive and
1777	// none of the ref-update work fires on its own. The event webhooks
1778	// subscribe to, and the branch's CI jobs, happen here instead.
1779	c.Store.RecordEvent(repo.ID, c.User.ID, "push", fmt.Sprintf(
1780		`{"ref":%q,"old":%q,"new":%q,"forced":false,"deleted":false}`,
1781		p.targetRef, p.targetSHA, newSHA))
1782	QueueBranchBuilds(c.Store, c.Cfg.Server.Root, c.Cfg.Server.SiteURL,
1783		repo, c.User.ID, mr.TargetRef, p.targetSHA, newSHA, time.Now())
1784	c.Store.MarkMirrorsDirty(repo.ID, "push")
1785	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
1786		notify(c, parts, notice{repo: repo, kind: "mr", number: mr.Number,
1787			subject: mrSubject(repo, mr.Number, mr.Title),
1788			action:  fmt.Sprintf("merged !%d into %s (%s)", mr.Number, mr.TargetRef, p.strategy),
1789			path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
1790	}
1791}
1792
1793// reviewGates refuses a merge whose gates are not all met, naming every
1794// unmet one. Returns -1 to proceed.
1795func (c *Ctx) reviewGates(repo store.Repo, mr store.MR, dir, targetSHA, headSHA string) int {
1796	g, err := MergeGates(c.Store, repo, mr, dir, targetSHA, headSHA)
1797	if err != nil {
1798		return c.fail(protocol.ExitFailure, "%v", err)
1799	}
1800	if len(g.Unmet) > 0 {
1801		return c.fail(protocol.ExitDenied, "%s", strings.Join(g.Unmet, "; "))
1802	}
1803	return -1
1804}
1805
1806// checksExpected reports whether anything was going to report a status
1807// on this head. A repository with no CI configuration and no history of
1808// statuses can never satisfy require_checks, and refusing its merges
1809// leaves no remedy but turning the setting off. Two things say a report
1810// was coming: a .gitbay/ci.yml at the head with a job a push runs, and a
1811// status having ever been recorded in the repository, which is how a
1812// repository reporting from outside through `status set` looks.
1813func checksExpected(st *store.Store, repoID int64, dir, headSHA string) bool {
1814	if seen, err := st.RepoHasStatuses(repoID); err != nil || seen {
1815		return true
1816	}
1817	return headRunsJobs(dir, headSHA)
1818}
1819
1820// headRunsJobs reports whether a push of this head would have queued or
1821// skipped a job, and so left it a status. A configuration that will not
1822// parse counts as running jobs: the push recorded a ci/config failure
1823// for it, so the head is not silent and this is not the branch that
1824// decides.
1825func headRunsJobs(dir, headSHA string) bool {
1826	raw, err := gitutil.ReadBlob(dir, headSHA, ci.ConfigPath, 1<<16)
1827	if err != nil {
1828		return false
1829	}
1830	jobs, err := ci.Parse(raw)
1831	if err != nil {
1832		return true
1833	}
1834	for _, j := range jobs {
1835		if j.Tags == "" && j.Schedule == "" {
1836			return true
1837		}
1838	}
1839	return false
1840}
1841
1842// MergeGates computes where a merge request stands against its
1843// repository's gates: draft, require_checks, require_approvals (fresh,
1844// non-author, latest review per reviewer from someone who can write; a
1845// fresh request-changes blocks), require_codeowners and require_resolved.
1846// Unmet carries one sentence per gate not passed. Fast-forward is
1847// reported, not gated: whether it matters depends on the strategy.
1848func MergeGates(st *store.Store, repo store.Repo, mr store.MR, dir, targetSHA, headSHA string) (GatesOut, error) {
1849	set := repo.Settings
1850	g := GatesOut{Draft: mr.Draft, ApprovalsRequired: set.RequireApprovals,
1851		CodeownersRequired: set.RequireCodeowners, ResolvedRequired: set.RequireResolved,
1852		ChecksRequired: set.RequireChecks}
1853	in := gateInputs{st: st, repo: repo, mr: mr, dir: dir, targetSHA: targetSHA, headSHA: headSHA}
1854	// A draft is open but not asking. This gate is unconditional — no
1855	// setting turns it off — because the author said so themselves.
1856	if mr.Draft {
1857		g.Unmet = append(g.Unmet, fmt.Sprintf("!%d is a draft; `gitbay mr ready %s %d` first", mr.Number, repo.Path(), mr.Number))
1858	}
1859	if err := in.checksGate(&g); err != nil {
1860		return g, err
1861	}
1862	if err := in.approvalsGate(&g); err != nil {
1863		return g, err
1864	}
1865	if set.RequireCodeowners {
1866		if err := in.codeownersGate(&g); err != nil {
1867			return g, err
1868		}
1869	}
1870
1871	n, err := st.UnresolvedThreadCount(mr.ID)
1872	if err != nil {
1873		return g, err
1874	}
1875	g.OpenThreads = n
1876	if set.RequireResolved && n > 0 {
1877		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))
1878	}
1879
1880	if ff, err := gitutil.IsAncestor(dir, targetSHA, headSHA); err == nil {
1881		g.FastForward = ff
1882	}
1883	return g, nil
1884}
1885
1886// gateInputs is what MergeGates judges a merge request on.
1887type gateInputs struct {
1888	st                 *store.Store
1889	repo               store.Repo
1890	mr                 store.MR
1891	dir                string
1892	targetSHA, headSHA string
1893}
1894
1895// checksGate records the head's combined status. With require_checks, every
1896// status the head carries must be green, a head something was going to
1897// report on must carry some, and every required context must have reported:
1898// one that has not is pending whatever the others say (#258). Setting
1899// contexts turns require_checks on; turned off again, the list is kept and
1900// unread.
1901func (in gateInputs) checksGate(g *GatesOut) error {
1902	statuses, err := in.st.ListCommitStatuses(in.repo.ID, in.headSHA)
1903	if err != nil {
1904		return err
1905	}
1906	g.Checks = store.CombinedStatus(statuses)
1907	set := in.repo.Settings
1908	if !set.RequireChecks {
1909		return nil
1910	}
1911	reported := map[string]bool{}
1912	for _, s := range statuses {
1913		reported[s.Context] = true
1914	}
1915	for _, want := range set.RequiredContexts {
1916		if !reported[want] {
1917			g.ChecksMissing = append(g.ChecksMissing, want)
1918		}
1919	}
1920	if len(g.ChecksMissing) > 0 && (g.Checks == "" || g.Checks == "success") {
1921		g.Checks = "pending"
1922	}
1923	switch g.Checks {
1924	case "success":
1925	case "":
1926		if checksExpected(in.st, in.repo.ID, in.dir, in.headSHA) {
1927			g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires green checks and none were reported on %.10s", in.repo.Path(), in.headSHA))
1928		}
1929	default:
1930		var bad []string
1931		for _, st := range statuses {
1932			if st.State != "success" {
1933				bad = append(bad, st.Context+"="+st.State)
1934			}
1935		}
1936		for _, m := range g.ChecksMissing {
1937			bad = append(bad, m+"=missing")
1938		}
1939		g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires green checks; %.10s has %s", in.repo.Path(), in.headSHA, strings.Join(bad, ", ")))
1940	}
1941	return nil
1942}
1943
1944// approvalsGate records approvals and change requests. The latest fresh
1945// review per reviewer decides their stance — but only from someone the
1946// repository trusts to write to it. Reviewing is open to any reader, which
1947// is what makes an outside opinion on a public change possible; deciding a
1948// merge gate is not the same thing, and counting every verdict let anyone
1949// with an account satisfy require_approvals or block a merge indefinitely
1950// (#147).
1951func (in gateInputs) approvalsGate(g *GatesOut) error {
1952	reviews, err := in.st.ListMRReviews(in.mr.ID)
1953	if err != nil {
1954		return err
1955	}
1956	counts := ReviewersWhoCount(in.st, in.repo, reviews)
1957	latest := map[string]string{}
1958	for _, r := range reviews {
1959		if r.Stale || r.Reviewer == in.mr.Author || !counts[r.Reviewer] {
1960			continue
1961		}
1962		latest[r.Reviewer] = r.Verdict
1963	}
1964	for who, verdict := range latest {
1965		switch verdict {
1966		case "approve":
1967			g.Approvals = append(g.Approvals, who)
1968		case "request_changes":
1969			g.ChangesRequested = append(g.ChangesRequested, who)
1970		}
1971	}
1972	slices.Sort(g.Approvals)
1973	slices.Sort(g.ChangesRequested)
1974	required := in.repo.Settings.RequireApprovals
1975	if required > 0 {
1976		if len(g.ChangesRequested) > 0 {
1977			g.Unmet = append(g.Unmet, fmt.Sprintf("%s requested changes on !%d; resolve their review before merging", strings.Join(g.ChangesRequested, ", "), in.mr.Number))
1978		}
1979		if len(g.Approvals) < required {
1980			g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires %d fresh approval(s); !%d has %d", in.repo.Path(), required, in.mr.Number, len(g.Approvals)))
1981		}
1982	}
1983	return nil
1984}
1985
1986// codeownersGate requires every owned changed file to have an approval from
1987// one of its owners. require_codeowners is the opt-in — a repository can
1988// carry the file as documentation of who to ask without it gating merges —
1989// and it does not wait on require_approvals (#99).
1990func (in gateInputs) codeownersGate(g *GatesOut) error {
1991	target := "refs/heads/" + in.mr.TargetRef
1992	content, err := gitutil.ReadBlob(in.dir, target, "CODEOWNERS", 1<<20)
1993	if err != nil {
1994		content, err = gitutil.ReadBlob(in.dir, target, ".gitbay/CODEOWNERS", 1<<20)
1995	}
1996	if err != nil || len(content) == 0 {
1997		g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires CODEOWNERS approval but %s carries no CODEOWNERS file", in.repo.Path(), in.mr.TargetRef))
1998		return nil
1999	}
2000	base, err := gitutil.MergeBase(in.dir, in.targetSHA, in.headSHA)
2001	if err != nil {
2002		return err
2003	}
2004	files, err := gitutil.DiffFiles(in.dir, base, in.headSHA)
2005	if err != nil {
2006		return err
2007	}
2008	keys, missing := unapprovedOwners(policy.ParseCodeowners(string(content)), files, g.Approvals)
2009	if len(missing) == 0 {
2010		return nil
2011	}
2012	var parts []string
2013	for _, key := range keys {
2014		paths := missing[key]
2015		g.OwnersOutstanding = append(g.OwnersOutstanding, OwnersOut{Files: paths, Owners: strings.Split(key, ",")})
2016		if len(paths) > 3 {
2017			paths = paths[:3]
2018		}
2019		parts = append(parts, fmt.Sprintf("%s (owned by %s)", strings.Join(paths, ", "), key))
2020	}
2021	g.Unmet = append(g.Unmet, "CODEOWNERS approval missing for: "+strings.Join(parts, "; "))
2022	return nil
2023}
2024
2025// unapprovedOwners groups the owned files no owner has approved by their
2026// owner set, joined with commas: the sorted keys, and the paths under each.
2027func unapprovedOwners(rules []policy.CodeownersRule, files, approvals []string) ([]string, map[string][]string) {
2028	approved := map[string]bool{}
2029	for _, a := range approvals {
2030		approved[a] = true
2031	}
2032	missing := map[string][]string{} // owner-set key -> paths
2033	var keys []string
2034	for _, f := range files {
2035		owners := policy.OwnersFor(rules, f)
2036		if owners == nil || slices.ContainsFunc(owners, func(o string) bool { return approved[o] }) {
2037			continue
2038		}
2039		key := strings.Join(owners, ",")
2040		if _, seen := missing[key]; !seen {
2041			keys = append(keys, key)
2042		}
2043		missing[key] = append(missing[key], f)
2044	}
2045	slices.Sort(keys)
2046	return keys, missing
2047}
2048
2049func runMRDraft(c *Ctx, args []string) int { return setMRDraft(c, args, true) }
2050func runMRReady(c *Ctx, args []string) int { return setMRDraft(c, args, false) }
2051
2052func setMRDraft(c *Ctx, args []string, draft bool) int {
2053	repo, mr, code := mrRef(c, args, policy.CanRead)
2054	if code >= 0 {
2055		return code
2056	}
2057	if code := refuseArchived(c, repo); code >= 0 {
2058		return code
2059	}
2060	if len(args) != 2 {
2061		return c.usage()
2062	}
2063	if code := authorOrWrite(c, repo, mr.Author, "change this merge request"); code >= 0 {
2064		return code
2065	}
2066	if mr.State != "open" && mr.State != "source_gone" {
2067		return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
2068	}
2069	if mr.Draft == draft {
2070		state := "already ready"
2071		if draft {
2072			state = "already a draft"
2073		}
2074		return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, state)
2075	}
2076	if err := c.Store.SetMRDraft(mr.ID, draft); err != nil {
2077		return c.fail(protocol.ExitFailure, "%v", err)
2078	}
2079	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.draft",
2080		fmt.Sprintf(`{"number":%d,"draft":%t}`, mr.Number, draft))
2081	if !draft {
2082		TryQueuedMerge(c.Store, c.Cfg, mr.ID)
2083	}
2084	// Marking ready is the request for review; going back to draft
2085	// withdraws it and is not worth anyone's inbox.
2086	//
2087	// The targets are the repository's, not the thread's participants.
2088	// Until someone comments or reviews, the only participant is the
2089	// author, who is the actor and excluded — so notifying participants
2090	// here reaches nobody, which is exactly what opening it as a draft
2091	// and then marking it ready would do. Opening a merge request tells
2092	// the repository; so does saying it is finally asking. A review
2093	// request made before ready — or on an earlier revision — reaches its
2094	// target here too: they are exactly who else is being asked.
2095	if !draft {
2096		if targets, err := c.Store.RepoNotifyTargets(repo); err == nil {
2097			parts, _ := c.Store.MRParticipants(mr.ID)
2098			reviewers, _ := c.Store.MRReviewRequestIDs(mr.ID)
2099			notify(c, append(append(targets, parts...), reviewers...), notice{repo: repo, kind: "mr", number: mr.Number,
2100				subject: mrSubject(repo, mr.Number, mr.Title),
2101				action:  fmt.Sprintf("marked !%d ready for review", mr.Number),
2102				path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
2103		}
2104	}
2105	return c.emit(map[string]any{"number": mr.Number, "draft": draft}, func(w io.Writer) {
2106		fmt.Fprintf(w, "%s!%d is %s\n", repo.Path(), mr.Number, map[bool]string{true: "a draft", false: "ready"}[draft])
2107	})
2108}
2109
2110func runMRClose(c *Ctx, args []string) int {
2111	f, err := c.parseArgs(args, flagSpec{Values: []string{"--by"}, MaxPos: 2,
2112		Usage: "mr close <owner/name> <n> [--by <m>]"})
2113	if err != nil {
2114		return c.fail(protocol.ExitUsage, "%v", err)
2115	}
2116	repo, mr, code := mrRef(c, f.Pos, policy.CanRead)
2117	if code >= 0 {
2118		return code
2119	}
2120	if code := refuseArchived(c, repo); code >= 0 {
2121		return code
2122	}
2123	if len(f.Pos) != 2 {
2124		return c.usage()
2125	}
2126	if code := authorOrWrite(c, repo, mr.Author, "close this merge request"); code >= 0 {
2127		return code
2128	}
2129	if mr.State == "merged" || mr.State == "closed" {
2130		return c.fail(protocol.ExitUsage, "MR !%d is already %s", mr.Number, mr.State)
2131	}
2132	var by int64
2133	if f.Has("--by") {
2134		by, code = resolveSupersededBy(c, repo, mr.Number, f.Value("--by"))
2135		if code >= 0 {
2136			return code
2137		}
2138	}
2139	if err := c.Store.MarkClosed(mr.ID, c.User.ID, ""); err != nil {
2140		return c.fail(protocol.ExitFailure, "%v", err)
2141	}
2142	eventData := fmt.Sprintf(`{"number":%d}`, mr.Number)
2143	if by != 0 {
2144		if err := c.Store.SetSupersededBy(mr.ID, by); err != nil {
2145			return c.fail(protocol.ExitFailure, "%v", err)
2146		}
2147		eventData = fmt.Sprintf(`{"number":%d,"by":%d}`, mr.Number, by)
2148	}
2149	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.closed", eventData)
2150	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
2151		notify(c, parts, notice{repo: repo, kind: "mr", number: mr.Number,
2152			subject: mrSubject(repo, mr.Number, mr.Title),
2153			action:  fmt.Sprintf("closed !%d", mr.Number),
2154			path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
2155	}
2156	return c.emit(map[string]any{"number": mr.Number, "state": "closed"}, func(w io.Writer) {
2157		fmt.Fprintf(w, "closed %s!%d\n", repo.Path(), mr.Number)
2158	})
2159}
2160
2161// resolveSupersededBy validates a --superseded-by/--by value against the
2162// merge request it would be set on: it must parse, name another merge
2163// request in the same repository (never itself), and that request must
2164// exist. -1 as the returned code means the value is good to use.
2165func resolveSupersededBy(c *Ctx, repo store.Repo, number int64, v string) (int64, int) {
2166	m, err := strconv.ParseInt(v, 10, 64)
2167	if err != nil {
2168		return 0, c.fail(protocol.ExitUsage, "bad MR number %q", v)
2169	}
2170	if m == number {
2171		return 0, c.fail(protocol.ExitUsage, "a merge request cannot supersede itself")
2172	}
2173	if _, err := c.Store.MRByNumber(repo.ID, m); errors.Is(err, store.ErrNotFound) {
2174		return 0, c.fail(protocol.ExitNotFound, "no merge request !%d on %s", m, repo.Path())
2175	} else if err != nil {
2176		return 0, c.fail(protocol.ExitFailure, "%v", err)
2177	}
2178	return m, -1
2179}
2180
2181// reviewAction is what a review notification says it was. A verdict with
2182// a batch behind it is a different thing from a bare verdict, and the
2183// person reading the mail is deciding whether to open it.
2184func reviewAction(number int64, verdict string, published int64) string {
2185	if published > 0 {
2186		return fmt.Sprintf("reviewed !%d: %s, with %d comment(s)", number, verdict, published)
2187	}
2188	return fmt.Sprintf("reviewed !%d: %s", number, verdict)
2189}
2190
2191// RevisionOut is one head a merge request has had.
2192type RevisionOut struct {
2193	N         int    `json:"n"` // 1 is the first push
2194	SHA       string `json:"sha"`
2195	BaseSHA   string `json:"base_sha,omitempty"`
2196	CreatedAt string `json:"created_at"`
2197	Current   bool   `json:"current,omitempty"`
2198}
2199
2200func mrRevisions(c *Ctx, mr store.MR) ([]RevisionOut, error) {
2201	heads, err := c.Store.MRHeads(mr.ID)
2202	if err != nil {
2203		return nil, err
2204	}
2205	out := make([]RevisionOut, 0, len(heads))
2206	for i, h := range heads {
2207		out = append(out, RevisionOut{N: i + 1, SHA: h.SHA, BaseSHA: h.BaseSHA,
2208			CreatedAt: h.CreatedAt, Current: h.SHA == mr.HeadSHA})
2209	}
2210	return out, nil
2211}
2212
2213func runMRRevisions(c *Ctx, args []string) int {
2214	repo, mr, code := mrRef(c, args, policy.CanRead)
2215	if code >= 0 {
2216		return code
2217	}
2218	if len(args) != 2 {
2219		return c.usage()
2220	}
2221	revs, err := mrRevisions(c, mr)
2222	if err != nil {
2223		return c.fail(protocol.ExitFailure, "%v", err)
2224	}
2225	return c.emitView(revs, func(w io.Writer) {
2226		tb := c.table(w, "REV", "SHA", "WHEN")
2227		for _, r := range revs {
2228			mark := " "
2229			if r.Current {
2230				mark = "*"
2231			}
2232			tb.row(cRef(fmt.Sprintf("%s v%d", mark, r.N)), cRef(fmt.Sprintf("%.10s", r.SHA)), cAge(r.CreatedAt))
2233		}
2234		tb.flush()
2235		if len(revs) < 2 {
2236			fmt.Fprintf(c.Stderr, "only one revision; %s!%d has not been pushed to since it was opened\n",
2237				repo.Path(), mr.Number)
2238		}
2239	}, func() screen {
2240		rows := make([]row, len(revs))
2241		for i, r := range revs {
2242			lead := cell{kind: kindGlyph}
2243			if r.Current {
2244				lead = cell{kind: kindGlyph, s: "●"}
2245			}
2246			rows[i] = rowOf(cRef(fmt.Sprintf("v%d", r.N)), lead, cRef(fmt.Sprintf("%.10s", r.SHA)), cAge(r.CreatedAt))
2247		}
2248		if len(revs) < 2 {
2249			fmt.Fprintf(c.Stderr, "only one revision; %s!%d has not been pushed to since it was opened\n",
2250				repo.Path(), mr.Number)
2251		}
2252		return listScreen("Revisions", rows,
2253			action{"Compare", []string{"mr", "range-diff", repo.Path(), strconv.FormatInt(mr.Number, 10)}},
2254		)
2255	})
2256}
2257
2258func runMRRangeDiff(c *Ctx, args []string) int {
2259	f, err := c.parseArgs(args, flagSpec{Values: []string{"--from", "--to"}, MaxPos: 2, Usage: c.Cmd.Usage})
2260	if err != nil {
2261		return c.fail(protocol.ExitUsage, "%v", err)
2262	}
2263	repo, mr, code := mrRef(c, f.Pos, policy.CanRead)
2264	if code >= 0 {
2265		return code
2266	}
2267	if len(f.Pos) != 2 {
2268		return c.usage()
2269	}
2270	revs, err := mrRevisions(c, mr)
2271	if err != nil {
2272		return c.fail(protocol.ExitFailure, "%v", err)
2273	}
2274	// One revision is a merge request nobody has pushed to since it was
2275	// opened. The argv was fine and the answer is "nothing changed", so
2276	// this succeeds with an empty patch rather than failing.
2277	if len(revs) < 2 {
2278		fmt.Fprintf(c.Stderr, "%s!%d has one revision; nothing to compare it against\n",
2279			repo.Path(), mr.Number)
2280		return protocol.ExitOK
2281	}
2282	// Default to the two most recent, which is "what changed since the
2283	// last push" — the question a stale review asks.
2284	from, to := revs[len(revs)-2], revs[len(revs)-1]
2285	pick := func(sha string) (RevisionOut, bool) {
2286		for _, r := range revs {
2287			if strings.HasPrefix(r.SHA, sha) {
2288				return r, true
2289			}
2290		}
2291		return RevisionOut{}, false
2292	}
2293	if v := f.Value("--from"); v != "" {
2294		r, ok := pick(v)
2295		if !ok {
2296			return c.fail(protocol.ExitNotFound, "%.12s is not a revision of !%d; see `mr revisions`", v, mr.Number)
2297		}
2298		from = r
2299	}
2300	if v := f.Value("--to"); v != "" {
2301		r, ok := pick(v)
2302		if !ok {
2303			return c.fail(protocol.ExitNotFound, "%.12s is not a revision of !%d; see `mr revisions`", v, mr.Number)
2304		}
2305		to = r
2306	}
2307	if from.SHA == to.SHA {
2308		return c.fail(protocol.ExitUsage, "--from and --to are the same revision")
2309	}
2310
2311	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
2312	// A revision recorded before its base could be worked out, or by a
2313	// migration backfill, falls back to the target's merge base.
2314	baseOf := func(r RevisionOut) string {
2315		if r.BaseSHA != "" {
2316			return r.BaseSHA
2317		}
2318		b, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, r.SHA)
2319		if err != nil {
2320			return r.SHA + "^"
2321		}
2322		return b
2323	}
2324	patch, truncated, err := gitutil.RangeDiff(dir, baseOf(from), from.SHA, baseOf(to), to.SHA, 4<<20)
2325	if err != nil {
2326		return c.fail(protocol.ExitFailure,
2327			"%v (the objects for an older revision may have been garbage-collected)", err)
2328	}
2329	fmt.Fprint(c.Stdout, c.Term.diff(patch))
2330	if truncated {
2331		fmt.Fprintln(c.Stderr, "range-diff truncated at 4 MiB")
2332	}
2333	return protocol.ExitOK
2334}
2335
2336// reviewersWhoCount is the set of reviewers whose verdict decides a merge
2337// gate: those with write access to the repository.
2338//
2339// Write, rather than a separate reviewer role, because it is the same
2340// question the gates already answer — a person who could push this change
2341// themselves is the person whose approval means the repository accepts
2342// it. Someone named in CODEOWNERS without write is a misconfiguration the
2343// owner should fix rather than a case to special-case here: they could
2344// not merge what they approved.
2345// Exported because the web renders the same distinction: a page that
2346// showed an approval the gate ignores would differ from the gate, and the
2347// difference would only surface when a merge was refused.
2348func ReviewersWhoCount(st *store.Store, repo store.Repo, reviews []store.MRReview) map[string]bool {
2349	counts := map[string]bool{}
2350	for _, r := range reviews {
2351		if _, done := counts[r.Reviewer]; done {
2352			continue
2353		}
2354		counts[r.Reviewer] = false
2355		u, err := st.UserByUsername(r.Reviewer)
2356		if err != nil {
2357			continue
2358		}
2359		grant, err := st.AccessRole(repo.ID, u.ID)
2360		if err != nil {
2361			continue
2362		}
2363		counts[r.Reviewer] = policy.CanWrite(u, repo, grant)
2364	}
2365	return counts
2366}
2367
2368// mrShowScreen is mr show at a terminal: where the merge request stands,
2369// its description, its commits, files and discussion, and what can be
2370// done about it now.
2371func mrShowScreen(c *Ctx, repo store.Repo, d MRShow, files []gitutil.NumStat) screen {
2372	n := strconv.FormatInt(d.Number, 10)
2373	path := repo.Path()
2374	state := d.State
2375	if d.Draft {
2376		state = "draft"
2377	}
2378	s := screen{body: d.Body, format: d.BodyFormat}
2379	s.fields = append(s.fields,
2380		field{"Merge", []cell{cLink("!"+n, c.siteURL(path, "mrs", n)), cText(d.Title)}},
2381		field{"State", []cell{cState(state), cMeta(d.Source+" → "+d.TargetRef, d.Author, relAge(d.CreatedAt, termNow()))}},
2382	)
2383	if len(d.Checks) > 0 {
2384		sts := make([]store.CommitStatus, len(d.Checks))
2385		for i, x := range d.Checks {
2386			sts[i] = store.CommitStatus{Context: x.Context, State: x.State}
2387		}
2388		s.fields = append(s.fields, field{"Checks", []cell{checksMark(sts)}})
2389	}
2390	open := d.State == "open" || d.State == "source_gone"
2391	behind := false
2392	if g := d.Gates; g != nil && open {
2393		behind = !g.FastForward
2394		if len(g.Unmet) == 0 {
2395			s.fields = append(s.fields, field{"Gates", []cell{cMark("✓ ready to merge", sgrGreen)}})
2396		} else {
2397			parts := make([]string, len(g.Unmet))
2398			for i, u := range g.Unmet {
2399				parts[i] = "✗ " + u
2400			}
2401			s.fields = append(s.fields, field{"Gates", []cell{cMark(strings.Join(parts, " · "), sgrRed)}})
2402		}
2403	}
2404	if len(d.ReviewRequests) > 0 {
2405		v := cText("requested of " + strings.Join(d.ReviewRequests, ", "))
2406		if slices.Contains(d.ReviewRequests, c.User.Username) {
2407			v.sgr = sgrYellow
2408		}
2409		s.fields = append(s.fields, field{"Review", []cell{v}})
2410	}
2411	if d.Milestone != "" {
2412		s.fields = append(s.fields, field{"Milestone", []cell{cText(d.Milestone)}})
2413	}
2414	if len(d.Labels) > 0 {
2415		s.fields = append(s.fields, field{"Labels", []cell{cText(strings.Join(d.Labels, ", "))}})
2416	}
2417	if !c.Term.Links {
2418		s.fields = append(s.fields, field{"URL", []cell{cText(c.siteURL(path, "mrs", n))}})
2419	}
2420
2421	commits := section{title: "Commits", n: len(d.Commits)}
2422	for _, cm := range d.Commits {
2423		commits.rows = append(commits.rows, rowOf(cRef(fmt.Sprintf("%.7s", cm.SHA)), cFlex(cm.Subject)))
2424	}
2425	fs := section{title: "Files", n: len(files)}
2426	add, del := 0, 0
2427	for _, f := range files {
2428		counts := "binary"
2429		if f.Added >= 0 {
2430			add, del = add+f.Added, del+f.Deleted
2431			counts = fmt.Sprintf("+%d −%d", f.Added, f.Deleted)
2432		}
2433		fs.rows = append(fs.rows, rowOf(cRef(f.Status), cFlex(f.Path), cMeta(counts)))
2434	}
2435	if len(files) > 0 {
2436		fs.note = fmt.Sprintf("+%d −%d", add, del)
2437	}
2438	s.sections = []section{commits, fs, discussion(d.Comments), events(d.Comments)}
2439
2440	if open {
2441		if behind {
2442			s.actions = append(s.actions, action{"Unblock", []string{"mr", "rebase", n}})
2443		}
2444		s.actions = append(s.actions,
2445			action{"Review", []string{"mr", "review", path, n, "--approve"}},
2446			action{"Review", []string{"mr", "comment", path, n}},
2447		)
2448		if d.Gates != nil && len(d.Gates.Unmet) == 0 {
2449			s.actions = append(s.actions, action{"Merge", []string{"mr", "merge", path, n}})
2450		}
2451	}
2452	s.actions = append(s.actions, action{"Read", []string{"mr", "diff", path, n}})
2453	return s
2454}