internal/control/mr.go

1487 lines · 54188 bytes

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