internal/control/mr.go

2e62f52baae22d14056deefc922dc1b9ec9b7bc5
gitbay/internal/control/mr.go history · blame · raw

1032 lines · 34523 bytes

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