internal/control/mr.go

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