internal/control/mr.go

f8f4f38f310dd34f689e38911772719bccde59c4
gitbay/internal/control/mr.go

1271 lines · 46564 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", 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 := ""
 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		default:
 704			rest = append(rest, a)
 705		}
 706	}
 707	if verdict == "" {
 708		return c.fail(protocol.ExitUsage, "usage: mr review <owner/name> <n> --approve|--request-changes|--comment")
 709	}
 710	repo, mr, code := mrRef(c, rest, policy.CanRead)
 711	if code >= 0 {
 712		return code
 713	}
 714	if code := refuseArchived(c, repo); code >= 0 {
 715		return code
 716	}
 717	if mr.State != "open" {
 718		return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
 719	}
 720	if err := c.Store.AddMRReview(mr.ID, c.User.ID, verdict, mr.HeadSHA); err != nil {
 721		return c.fail(protocol.ExitFailure, "%v", err)
 722	}
 723	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.reviewed",
 724		fmt.Sprintf(`{"number":%d,"verdict":%q}`, mr.Number, verdict))
 725	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
 726		notify(c, parts, notice{repo: repo, kind: "mr",
 727			subject: mrSubject(repo, mr.Number, mr.Title),
 728			action:  fmt.Sprintf("reviewed !%d: %s", mr.Number, verdict),
 729			path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
 730	}
 731	return c.emit(map[string]any{"number": mr.Number, "verdict": verdict}, func(w io.Writer) {
 732		fmt.Fprintf(w, "reviewed %s!%d: %s\n", repo.Path(), mr.Number, verdict)
 733	})
 734}
 735
 736func runMRMerge(c *Ctx, args []string) int {
 737	f, err := parseFlags(args, flagSpec{Values: []string{"--strategy"}, MaxPos: -1, Usage: "mr merge <owner/name> <n> [--strategy ff|merge|squash|rebase]"})
 738	if err != nil {
 739		return c.fail(protocol.ExitUsage, "%v", err)
 740	}
 741	strategy, rest := f.Value("--strategy"), f.Pos
 742	valid := map[string]bool{"": true, "ff": true, "merge": true, "squash": true, "rebase": true}
 743	if !valid[strategy] {
 744		return c.fail(protocol.ExitUsage, "--strategy must be ff, merge, squash, or rebase")
 745	}
 746	repo, mr, code := mrRef(c, rest, policy.CanWrite)
 747	if code >= 0 {
 748		return code
 749	}
 750	if code := refuseArchived(c, repo); code >= 0 {
 751		return code
 752	}
 753	if mr.State != "open" && mr.State != "source_gone" {
 754		return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
 755	}
 756
 757	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
 758	targetRef := "refs/heads/" + mr.TargetRef
 759	targetSHA, err := gitutil.ResolveRef(dir, targetRef)
 760	if err != nil {
 761		return c.fail(protocol.ExitFailure, "target branch %s: %v", mr.TargetRef, err)
 762	}
 763	headSHA, err := gitutil.ResolveRef(dir, mrHeadRef(mr.Number))
 764	if err != nil {
 765		return c.fail(protocol.ExitFailure, "MR head ref: %v", err)
 766	}
 767
 768	// Check gate: with require_checks, the MR head must carry statuses
 769	// and every one of them must be green.
 770	if repo.Settings.RequireChecks {
 771		statuses, err := c.Store.ListCommitStatuses(repo.ID, headSHA)
 772		if err != nil {
 773			return c.fail(protocol.ExitFailure, "%v", err)
 774		}
 775		switch store.CombinedStatus(statuses) {
 776		case "success":
 777		case "":
 778			return c.fail(protocol.ExitDenied,
 779				"%s requires green checks and none were reported on %.10s", repo.Path(), headSHA)
 780		default:
 781			var bad []string
 782			for _, st := range statuses {
 783				if st.State != "success" {
 784					bad = append(bad, st.Context+"="+st.State)
 785				}
 786			}
 787			return c.fail(protocol.ExitDenied,
 788				"%s requires green checks; %.10s has %s", repo.Path(), headSHA, strings.Join(bad, ", "))
 789		}
 790	}
 791
 792	// Review gates: approvals, CODEOWNERS, resolved threads.
 793	if code := c.reviewGates(repo, mr, dir, targetSHA, headSHA); code >= 0 {
 794		return code
 795	}
 796
 797	upToDate, err := gitutil.IsAncestor(dir, headSHA, targetSHA)
 798	if err != nil {
 799		return c.fail(protocol.ExitFailure, "%v", err)
 800	}
 801	if upToDate {
 802		// The head is already on the target: merged by hand and pushed, or
 803		// a merge whose ref update landed and whose record did not. Record
 804		// it rather than refuse, so a merge request cannot be stuck open
 805		// with no way to close it as merged (#108).
 806		if err := c.Store.MarkMerged(mr.ID, targetSHA, c.User.ID, ""); err != nil {
 807			return c.fail(protocol.ExitFailure, "%v", err)
 808		}
 809		c.Store.RecordEvent(repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d}`, mr.Number))
 810		return c.emit(map[string]any{"number": mr.Number, "strategy": "recorded", "sha": headSHA}, func(w io.Writer) {
 811			fmt.Fprintf(w, "%s already contains !%d; recorded as merged at %.10s\n", mr.TargetRef, mr.Number, headSHA)
 812		})
 813	}
 814	ffPossible, err := gitutil.IsAncestor(dir, targetSHA, headSHA)
 815	if err != nil {
 816		return c.fail(protocol.ExitFailure, "%v", err)
 817	}
 818
 819	// Signature policy matrix: with require_signed_commits, only
 820	// fast-forward is allowed — squash, rebase-replay, and merge commits
 821	// are all server-created and unsigned, violating the branch's own
 822	// policy — and every landed commit must be verified. An explicit
 823	// rebase when fast-forward is already possible IS a fast-forward
 824	// (nothing is rewritten), so it stays legal.
 825	if repo.Settings.RequireSignedCommits {
 826		if strategy == "merge" || strategy == "squash" || !ffPossible {
 827			return c.fail(protocol.ExitDenied,
 828				"%s requires signed commits, so only fast-forward merges are allowed; rebase %s onto %s locally, re-push, and merge again",
 829				repo.Path(), mr.SourceRef, mr.TargetRef)
 830		}
 831		strategy = "ff"
 832		commits, err := gitutil.RevListRange(dir, targetSHA, headSHA)
 833		if err != nil {
 834			return c.fail(protocol.ExitFailure, "%v", err)
 835		}
 836		for _, sha := range commits {
 837			raw, err := gitutil.ReadCommit(dir, sha)
 838			if err != nil {
 839				return c.fail(protocol.ExitFailure, "%v", err)
 840			}
 841			parsed, err := sigParse(raw)
 842			if err != nil {
 843				return c.fail(protocol.ExitFailure, "%v", err)
 844			}
 845			res, err := VerifyCommitCached(c.Store, repo, parsed, sha)
 846			if err != nil {
 847				return c.fail(protocol.ExitFailure, "%v", err)
 848			}
 849			if res.State != "verified" {
 850				return c.fail(protocol.ExitDenied,
 851					"%s requires signed commits: %.10s is %s", repo.Path(), sha, res.State)
 852			}
 853		}
 854	}
 855	if strategy == "" {
 856		if ffPossible {
 857			strategy = "ff"
 858		} else {
 859			strategy = "merge"
 860		}
 861	}
 862	if strategy == "rebase" && ffPossible {
 863		// Nothing to rewrite: a rebase onto an ancestor is a fast-forward,
 864		// and taking it keeps the original commits and their signatures.
 865		strategy = "ff"
 866	}
 867
 868	// Every server-created commit needs the merger's verified identity.
 869	mergerEmail := ""
 870	if strategy != "ff" {
 871		email, err := c.Store.PrimaryVerifiedEmail(c.User.ID)
 872		if err != nil {
 873			return c.fail(protocol.ExitFailure, "%v", err)
 874		}
 875		if email == "" {
 876			return c.fail(protocol.ExitDenied,
 877				"%s merges create commits carrying your identity: verify a primary email first (or use a fast-forward merge)", strategy)
 878		}
 879		mergerEmail = email
 880	}
 881
 882	var newSHA string
 883	switch strategy {
 884	case "ff":
 885		if !ffPossible {
 886			return c.fail(protocol.ExitUsage,
 887				"fast-forward not possible: %s has diverged from the MR head; use --strategy merge or rebase and re-push", mr.TargetRef)
 888		}
 889		newSHA = headSHA
 890
 891	case "merge":
 892		tree, conflict, err := gitutil.MergeTree(dir, targetSHA, headSHA)
 893		if err != nil {
 894			return c.fail(protocol.ExitFailure, "%v", err)
 895		}
 896		if conflict {
 897			return c.fail(protocol.ExitUsage,
 898				"merge conflicts between %s and the MR head; resolve locally and re-push", mr.TargetRef)
 899		}
 900		msg := fmt.Sprintf("Merge request !%d: %s\n\nMerged %s into %s", mr.Number, mr.Title, mr.SourceRef, mr.TargetRef)
 901		newSHA, err = gitutil.CommitTree(dir, tree, []string{targetSHA, headSHA}, c.User.Username, mergerEmail, msg)
 902		if err != nil {
 903			return c.fail(protocol.ExitFailure, "%v", err)
 904		}
 905
 906	case "squash":
 907		// One new commit with the merged tree. Authorship credit goes to
 908		// the MR author (their verified identity when they have one); the
 909		// committer is the merger.
 910		tree := ""
 911		if ffPossible {
 912			t, err := gitutil.ResolveTree(dir, headSHA)
 913			if err != nil {
 914				return c.fail(protocol.ExitFailure, "%v", err)
 915			}
 916			tree = t
 917		} else {
 918			t, conflict, err := gitutil.MergeTree(dir, targetSHA, headSHA)
 919			if err != nil {
 920				return c.fail(protocol.ExitFailure, "%v", err)
 921			}
 922			if conflict {
 923				return c.fail(protocol.ExitUsage,
 924					"merge conflicts between %s and the MR head; resolve locally and re-push", mr.TargetRef)
 925			}
 926			tree = t
 927		}
 928		authorName, authorEmail := c.User.Username, mergerEmail
 929		if author, err := c.Store.UserByUsername(mr.Author); err == nil {
 930			if ae, err := c.Store.PrimaryVerifiedEmail(author.ID); err == nil && ae != "" {
 931				authorName, authorEmail = author.Username, ae
 932			}
 933		}
 934		msg := fmt.Sprintf("%s (!%d)", mr.Title, mr.Number)
 935		if mr.Body != "" {
 936			msg += "\n\n" + mr.Body
 937		}
 938		var err error
 939		newSHA, err = gitutil.CommitTreeIdent(dir, tree, []string{targetSHA},
 940			authorName, authorEmail, "", c.User.Username, mergerEmail, msg)
 941		if err != nil {
 942			return c.fail(protocol.ExitFailure, "%v", err)
 943		}
 944
 945	case "rebase":
 946		commits, err := gitutil.RevListRange(dir, targetSHA, headSHA)
 947		if err != nil {
 948			return c.fail(protocol.ExitFailure, "%v", err)
 949		}
 950		// Oldest first.
 951		for i, j := 0, len(commits)-1; i < j; i, j = i+1, j-1 {
 952			commits[i], commits[j] = commits[j], commits[i]
 953		}
 954		onto := targetSHA
 955		for _, sha := range commits {
 956			parents, err := gitutil.CommitParents(dir, sha)
 957			if err != nil {
 958				return c.fail(protocol.ExitFailure, "%v", err)
 959			}
 960			if len(parents) > 1 {
 961				return c.fail(protocol.ExitUsage,
 962					"the MR contains merge commit %.10s; a rebase merge needs linear history — use --strategy merge or squash", sha)
 963			}
 964			base := onto // root commit: replay against the new tip itself
 965			if len(parents) == 1 {
 966				base = parents[0]
 967			}
 968			tree, conflict, err := gitutil.MergeTreeOnto(dir, base, onto, sha)
 969			if err != nil {
 970				return c.fail(protocol.ExitFailure, "%v", err)
 971			}
 972			if conflict {
 973				return c.fail(protocol.ExitUsage,
 974					"commit %.10s does not apply cleanly onto %s; rebase locally and re-push", sha, mr.TargetRef)
 975			}
 976			aName, aEmail, aDate, err := gitutil.AuthorIdent(dir, sha)
 977			if err != nil {
 978				return c.fail(protocol.ExitFailure, "%v", err)
 979			}
 980			msg, err := gitutil.CommitMessage(dir, sha)
 981			if err != nil {
 982				return c.fail(protocol.ExitFailure, "%v", err)
 983			}
 984			onto, err = gitutil.CommitTreeIdent(dir, tree, []string{onto},
 985				aName, aEmail, aDate, c.User.Username, mergerEmail, msg)
 986			if err != nil {
 987				return c.fail(protocol.ExitFailure, "%v", err)
 988			}
 989		}
 990		newSHA = onto
 991	}
 992
 993	// A stacked merge request's diff is against this branch. After a
 994	// fast-forward or merge commit the same commits are on the target and
 995	// its diff is unchanged there; after a squash or rebase they are not,
 996	// and the stack would carry this merge request's changes a second
 997	// time. Refuse rather than leave the stack wrong.
 998	var stack []store.MR
 999	if mr.SourceRepoID == repo.ID {
1000		stack, _ = c.Store.OpenMRsByTarget(repo.ID, mr.SourceRef)
1001	}
1002	if len(stack) > 0 && (strategy == "squash" || strategy == "rebase") {
1003		var nums []string
1004		for _, k := range stack {
1005			nums = append(nums, fmt.Sprintf("!%d", k.Number))
1006		}
1007		return c.fail(protocol.ExitUsage,
1008			"%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",
1009			fmt.Sprintf("!%d", mr.Number), strings.Join(nums, ", "), strategy, mr.SourceRef)
1010	}
1011
1012	// CAS so a concurrent push between our read and this write fails the
1013	// merge instead of silently discarding the push.
1014	if err := gitutil.UpdateRefCAS(dir, targetRef, newSHA, targetSHA); err != nil {
1015		return c.fail(protocol.ExitFailure, "target branch moved during merge; retry: %v", err)
1016	}
1017	if err := c.Store.MarkMerged(mr.ID, targetSHA, c.User.ID, ""); err != nil {
1018		return c.fail(protocol.ExitFailure, "%v", err)
1019	}
1020	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d,"sha":%q}`, mr.Number, newSHA))
1021	// The stack moves up: whatever targeted this branch now targets what
1022	// it merged into, reviews intact, since that diff is the one they
1023	// were of.
1024	for _, k := range stack {
1025		if err := c.Store.RetargetKeepingReviews(k.ID, mr.TargetRef); err != nil {
1026			continue
1027		}
1028		c.Store.AddMRSystemComment(k.ID, c.User.ID, fmt.Sprintf("retargeted from %s to %s: !%d merged", mr.SourceRef, mr.TargetRef, mr.Number))
1029		if parts, err := c.Store.MRParticipants(k.ID); err == nil {
1030			notify(c, parts, notice{repo: repo, kind: "mr",
1031				subject: mrSubject(repo, k.Number, k.Title),
1032				action:  fmt.Sprintf("retargeted !%d from %s to %s: !%d merged", k.Number, mr.SourceRef, mr.TargetRef, mr.Number),
1033				path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), k.Number)})
1034		}
1035	}
1036	// Merges bypass receive-pack, so the commit-message issue actions
1037	// (closes #N, references) run here for the newly landed commits. The
1038	// description is scanned after them, so a commit wins the attribution
1039	// when both name the same issue.
1040	if mr.TargetRef == repo.DefaultBranch {
1041		ProcessCommitMessages(c.Store, dir, repo, c.User.ID, targetSHA, newSHA)
1042		ProcessMRDescription(c.Store, repo, mr, c.User.ID)
1043		RecordLandedCommits(c.Store, dir, repo, targetSHA, newSHA)
1044	}
1045	// A merge moves the ref directly, so it never reaches post-receive and
1046	// none of the ref-update work fires on its own. The event webhooks
1047	// subscribe to, and the branch's CI jobs, happen here instead.
1048	c.Store.RecordEvent(repo.ID, c.User.ID, "push", fmt.Sprintf(
1049		`{"ref":%q,"old":%q,"new":%q,"forced":false,"deleted":false}`,
1050		targetRef, targetSHA, newSHA))
1051	QueueBranchBuilds(c.Store, c.Cfg.Server.Root, c.Cfg.Server.SiteURL,
1052		repo, c.User.ID, mr.TargetRef, newSHA, time.Now())
1053	c.Store.MarkMirrorsDirty(repo.ID, "push")
1054	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
1055		notify(c, parts, notice{repo: repo, kind: "mr",
1056			subject: mrSubject(repo, mr.Number, mr.Title),
1057			action:  fmt.Sprintf("merged !%d into %s (%s)", mr.Number, mr.TargetRef, strategy),
1058			path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
1059	}
1060	return c.emit(map[string]any{"number": mr.Number, "strategy": strategy, "sha": newSHA}, func(w io.Writer) {
1061		fmt.Fprintf(w, "merged %s!%d into %s (%s) at %.10s\n", repo.Path(), mr.Number, mr.TargetRef, strategy, newSHA)
1062	})
1063}
1064
1065// reviewGates enforces require_approvals (fresh, non-author, latest review
1066// per reviewer; a fresh request-changes blocks), require_codeowners, and
1067// require_resolved. Returns -1 to proceed.
1068func (c *Ctx) reviewGates(repo store.Repo, mr store.MR, dir, targetSHA, headSHA string) int {
1069	// A draft is open but not asking. This gate is unconditional — no
1070	// setting turns it off — because the author said so themselves.
1071	if mr.Draft {
1072		return c.fail(protocol.ExitDenied,
1073			"!%d is a draft; `gitbay mr ready %s %d` first", mr.Number, repo.Path(), mr.Number)
1074	}
1075	set := repo.Settings
1076	reviews, err := c.Store.ListMRReviews(mr.ID)
1077	if err != nil {
1078		return c.fail(protocol.ExitFailure, "%v", err)
1079	}
1080	// Latest fresh review per reviewer decides their stance.
1081	latest := map[string]string{}
1082	for _, r := range reviews {
1083		if r.Stale || r.Reviewer == mr.Author {
1084			continue
1085		}
1086		latest[r.Reviewer] = r.Verdict
1087	}
1088	var approvers []string
1089	var blockers []string
1090	for who, verdict := range latest {
1091		switch verdict {
1092		case "approve":
1093			approvers = append(approvers, who)
1094		case "request_changes":
1095			blockers = append(blockers, who)
1096		}
1097	}
1098
1099	if set.RequireApprovals > 0 {
1100		if len(blockers) > 0 {
1101			slices.Sort(blockers)
1102			return c.fail(protocol.ExitDenied,
1103				"%s requested changes on !%d; resolve their review before merging", strings.Join(blockers, ", "), mr.Number)
1104		}
1105		if len(approvers) < set.RequireApprovals {
1106			return c.fail(protocol.ExitDenied,
1107				"%s requires %d fresh approval(s); !%d has %d", repo.Path(), set.RequireApprovals, mr.Number, len(approvers))
1108		}
1109	}
1110
1111	// CODEOWNERS: every owned changed file needs an approval from one of
1112	// its owners. require_codeowners is the opt-in — a repository can
1113	// carry the file as documentation of who to ask without it gating
1114	// merges — and it does not wait on require_approvals (#99).
1115	if set.RequireCodeowners {
1116		content, err := gitutil.ReadBlob(dir, "refs/heads/"+mr.TargetRef, "CODEOWNERS", 1<<20)
1117		if err != nil {
1118			content, err = gitutil.ReadBlob(dir, "refs/heads/"+mr.TargetRef, ".gitbay/CODEOWNERS", 1<<20)
1119		}
1120		if err != nil || len(content) == 0 {
1121			return c.fail(protocol.ExitDenied,
1122				"%s requires CODEOWNERS approval but %s carries no CODEOWNERS file",
1123				repo.Path(), mr.TargetRef)
1124		}
1125		rules := policy.ParseCodeowners(string(content))
1126		base, err := gitutil.MergeBase(dir, targetSHA, headSHA)
1127		if err != nil {
1128			return c.fail(protocol.ExitFailure, "%v", err)
1129		}
1130		files, err := gitutil.DiffFiles(dir, base, headSHA)
1131		if err != nil {
1132			return c.fail(protocol.ExitFailure, "%v", err)
1133		}
1134		approved := map[string]bool{}
1135		for _, a := range approvers {
1136			approved[a] = true
1137		}
1138		missing := map[string][]string{} // owner-set key -> example paths
1139		for _, f := range files {
1140			owners := policy.OwnersFor(rules, f)
1141			if owners == nil {
1142				continue
1143			}
1144			ok := false
1145			for _, o := range owners {
1146				if approved[o] {
1147					ok = true
1148					break
1149				}
1150			}
1151			if !ok {
1152				key := strings.Join(owners, ",")
1153				if len(missing[key]) < 3 {
1154					missing[key] = append(missing[key], f)
1155				}
1156			}
1157		}
1158		if len(missing) > 0 {
1159			var parts []string
1160			for owners, paths := range missing {
1161				parts = append(parts, fmt.Sprintf("%s (owned by %s)", strings.Join(paths, ", "), owners))
1162			}
1163			slices.Sort(parts)
1164			return c.fail(protocol.ExitDenied,
1165				"CODEOWNERS approval missing for: %s", strings.Join(parts, "; "))
1166		}
1167	}
1168
1169	if set.RequireResolved {
1170		n, err := c.Store.UnresolvedThreadCount(mr.ID)
1171		if err != nil {
1172			return c.fail(protocol.ExitFailure, "%v", err)
1173		}
1174		if n > 0 {
1175			return c.fail(protocol.ExitDenied,
1176				"%s requires review threads resolved; !%d has %d open (mr threads %s %d)", repo.Path(), mr.Number, n, repo.Path(), mr.Number)
1177		}
1178	}
1179	return -1
1180}
1181
1182func runMRDraft(c *Ctx, args []string) int { return setMRDraft(c, args, true) }
1183func runMRReady(c *Ctx, args []string) int { return setMRDraft(c, args, false) }
1184
1185func setMRDraft(c *Ctx, args []string, draft bool) int {
1186	verb := "ready"
1187	if draft {
1188		verb = "draft"
1189	}
1190	repo, mr, code := mrRef(c, args, policy.CanRead)
1191	if code >= 0 {
1192		return code
1193	}
1194	if code := refuseArchived(c, repo); code >= 0 {
1195		return code
1196	}
1197	if len(args) != 2 {
1198		return c.fail(protocol.ExitUsage, "usage: mr %s <owner/name> <n>", verb)
1199	}
1200	if code := authorOrWrite(c, repo, mr.Author, "change this merge request"); code >= 0 {
1201		return code
1202	}
1203	if mr.State != "open" && mr.State != "source_gone" {
1204		return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
1205	}
1206	if mr.Draft == draft {
1207		state := "already ready"
1208		if draft {
1209			state = "already a draft"
1210		}
1211		return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, state)
1212	}
1213	if err := c.Store.SetMRDraft(mr.ID, draft); err != nil {
1214		return c.fail(protocol.ExitFailure, "%v", err)
1215	}
1216	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.draft",
1217		fmt.Sprintf(`{"number":%d,"draft":%t}`, mr.Number, draft))
1218	// Marking ready is the request for review; going back to draft
1219	// withdraws it and is not worth anyone's inbox.
1220	//
1221	// The targets are the repository's, not the thread's participants.
1222	// Until someone comments or reviews, the only participant is the
1223	// author, who is the actor and excluded — so notifying participants
1224	// here reaches nobody, which is exactly what opening it as a draft
1225	// and then marking it ready would do. Opening a merge request tells
1226	// the repository; so does saying it is finally asking.
1227	if !draft {
1228		if targets, err := c.Store.RepoNotifyTargets(repo); err == nil {
1229			parts, _ := c.Store.MRParticipants(mr.ID)
1230			notify(c, append(targets, parts...), notice{repo: repo, kind: "mr",
1231				subject: mrSubject(repo, mr.Number, mr.Title),
1232				action:  fmt.Sprintf("marked !%d ready for review", mr.Number),
1233				path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
1234		}
1235	}
1236	return c.emit(map[string]any{"number": mr.Number, "draft": draft}, func(w io.Writer) {
1237		fmt.Fprintf(w, "%s!%d is %s\n", repo.Path(), mr.Number, map[bool]string{true: "a draft", false: "ready"}[draft])
1238	})
1239}
1240
1241func runMRClose(c *Ctx, args []string) int {
1242	repo, mr, code := mrRef(c, args, policy.CanRead)
1243	if code >= 0 {
1244		return code
1245	}
1246	if code := refuseArchived(c, repo); code >= 0 {
1247		return code
1248	}
1249	if len(args) != 2 {
1250		return c.fail(protocol.ExitUsage, "usage: mr close <owner/name> <n>")
1251	}
1252	if code := authorOrWrite(c, repo, mr.Author, "close this merge request"); code >= 0 {
1253		return code
1254	}
1255	if mr.State == "merged" || mr.State == "closed" {
1256		return c.fail(protocol.ExitUsage, "MR !%d is already %s", mr.Number, mr.State)
1257	}
1258	if err := c.Store.MarkClosed(mr.ID, c.User.ID, ""); err != nil {
1259		return c.fail(protocol.ExitFailure, "%v", err)
1260	}
1261	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.closed", fmt.Sprintf(`{"number":%d}`, mr.Number))
1262	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
1263		notify(c, parts, notice{repo: repo, kind: "mr",
1264			subject: mrSubject(repo, mr.Number, mr.Title),
1265			action:  fmt.Sprintf("closed !%d", mr.Number),
1266			path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
1267	}
1268	return c.emit(map[string]any{"number": mr.Number, "state": "closed"}, func(w io.Writer) {
1269		fmt.Fprintf(w, "closed %s!%d\n", repo.Path(), mr.Number)
1270	})
1271}