internal/control/mr.go

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

1817 lines · 65611 bytes

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