internal/control/mr.go

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