internal/control/mr.go

46a896187ab1b8bc7f1540f455a311dfdcc6b5ed
gitbay/internal/control/mr.go

1308 lines · 48083 bytes

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