internal/control/mr.go

d2d650521865a3aa9c2fa64f7452aba32ad46cbb
gitbay/internal/control/mr.go history · blame · raw

767 lines · 25246 bytes

  1package control
  2
  3import (
  4	"errors"
  5	"fmt"
  6	"io"
  7	"strconv"
  8	"strings"
  9
 10	"gitbay.org/gitbay/internal/gitutil"
 11	"gitbay.org/gitbay/internal/policy"
 12	"gitbay.org/gitbay/internal/protocol"
 13	"gitbay.org/gitbay/internal/store"
 14)
 15
 16func init() {
 17	register(Command{Path: []string{"repo", "fork"},
 18		Summary: "fork a repository under your account: repo fork <owner/name> [--name <n>]", Run: runRepoFork})
 19	register(Command{Path: []string{"repo", "settings", "require-checks"},
 20		Summary: "gate merges on green statuses: repo settings require-checks <owner/name> on|off", Run: runRequireChecks})
 21	register(Command{Path: []string{"repo", "settings", "require-signed"},
 22		Summary: "require verified commit signatures: repo settings require-signed <owner/name> on|off", Run: runRequireSigned})
 23	register(Command{Path: []string{"mr", "create"},
 24		Summary:    "open a merge request: mr create <target owner/name> --source [owner/name:]<branch> --target <branch> --title <t> [--body <b> | --file -]",
 25		ReadsStdin: true, Run: runMRCreate})
 26	register(Command{Path: []string{"mr", "list"},
 27		Summary: "list merge requests: mr list <owner/name> [--state open|merged|closed|source_gone|all]", ReadOnly: true, Run: runMRList})
 28	register(Command{Path: []string{"mr", "show"},
 29		Summary: "show a merge request: mr show <owner/name> <n>", ReadOnly: true, Run: runMRShow})
 30	register(Command{Path: []string{"mr", "diff"},
 31		Summary: "show the diff: mr diff <owner/name> <n>", ReadOnly: true, Run: runMRDiff})
 32	register(Command{Path: []string{"mr", "comment"},
 33		Summary:    "comment: mr comment <owner/name> <n> [--message <m> | --file -]",
 34		ReadsStdin: true, Run: runMRComment})
 35	register(Command{Path: []string{"mr", "review"},
 36		Summary: "review: mr review <owner/name> <n> --approve|--request-changes|--comment", Run: runMRReview})
 37	register(Command{Path: []string{"mr", "merge"},
 38		Summary: "merge: mr merge <owner/name> <n> [--strategy ff|merge|squash|rebase]", Run: runMRMerge})
 39	register(Command{Path: []string{"mr", "close"},
 40		Summary: "close without merging: mr close <owner/name> <n>", Run: runMRClose})
 41}
 42
 43func runRepoFork(c *Ctx, args []string) int {
 44	var path, name string
 45	for i := 0; i < len(args); i++ {
 46		switch args[i] {
 47		case "--name":
 48			if i+1 >= len(args) {
 49				return c.fail(protocol.ExitUsage, "--name requires a value")
 50			}
 51			name = args[i+1]
 52			i++
 53		default:
 54			if path != "" {
 55				return c.fail(protocol.ExitUsage, "usage: repo fork <owner/name> [--name <n>]")
 56			}
 57			path = args[i]
 58		}
 59	}
 60	if path == "" {
 61		return c.fail(protocol.ExitUsage, "usage: repo fork <owner/name> [--name <n>]")
 62	}
 63	src, code := resolveRepo(c, path, policy.CanRead)
 64	if code >= 0 {
 65		return code
 66	}
 67	if name == "" {
 68		name = src.Name
 69	}
 70	if err := policy.ValidateName(name); err != nil {
 71		return c.fail(protocol.ExitUsage, "%v", err)
 72	}
 73	id, err := c.Store.CreateRepo("user", c.User.ID, name, src.Visibility)
 74	if err != nil {
 75		return c.fail(protocol.ExitFailure, "%v", err)
 76	}
 77	if err := c.Store.SetForkOf(id, src.ID); err != nil {
 78		return c.fail(protocol.ExitFailure, "%v", err)
 79	}
 80	dstDir := RepoDir(c.Cfg.Server.Root, c.User.Username, name)
 81	srcDir := RepoDir(c.Cfg.Server.Root, src.OwnerName, src.Name)
 82	if err := gitutil.InitBare(dstDir, "main", HooksDir(c.Cfg.Server.Root)); err != nil {
 83		c.Store.DeleteRepo(id)
 84		return c.fail(protocol.ExitFailure, "%v", err)
 85	}
 86	if desc := gitutil.ReadDescription(srcDir); desc != "" {
 87		gitutil.WriteDescription(dstDir, desc)
 88	}
 89	if err := gitutil.FetchInto(dstDir, srcDir, "refs/heads/*", "refs/heads/*"); err != nil {
 90		// Empty source repos have nothing to fetch; that is fine.
 91		if _, rerr := gitutil.ResolveRef(srcDir, src.DefaultBranch); rerr == nil {
 92			c.Store.DeleteRepo(id)
 93			return c.fail(protocol.ExitFailure, "copying refs: %v", err)
 94		}
 95	}
 96	forkPath := c.User.Username + "/" + name
 97	return c.emit(map[string]string{"path": forkPath, "fork_of": src.Path()}, func(w io.Writer) {
 98		fmt.Fprintf(w, "forked %s to %s\n", src.Path(), forkPath)
 99	})
100}
101
102func runRequireChecks(c *Ctx, args []string) int {
103	if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
104		return c.fail(protocol.ExitUsage, "usage: repo settings require-checks <owner/name> on|off")
105	}
106	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
107	if code >= 0 {
108		return code
109	}
110	s := repo.Settings
111	s.RequireChecks = args[1] == "on"
112	if err := c.Store.SetRepoSettings(repo.ID, s); err != nil {
113		return c.fail(protocol.ExitFailure, "%v", err)
114	}
115	return c.emit(s, func(w io.Writer) {
116		fmt.Fprintf(w, "require_checks %s on %s\n", args[1], repo.Path())
117	})
118}
119
120func runRequireSigned(c *Ctx, args []string) int {
121	if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
122		return c.fail(protocol.ExitUsage, "usage: repo settings require-signed <owner/name> on|off")
123	}
124	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
125	if code >= 0 {
126		return code
127	}
128	s := repo.Settings
129	s.RequireSignedCommits = args[1] == "on"
130	if err := c.Store.SetRepoSettings(repo.ID, s); err != nil {
131		return c.fail(protocol.ExitFailure, "%v", err)
132	}
133	return c.emit(s, func(w io.Writer) {
134		fmt.Fprintf(w, "require_signed_commits %s on %s\n", args[1], repo.Path())
135	})
136}
137
138// mrRef parses "<owner/name> <n>" and loads the MR.
139func mrRef(c *Ctx, args []string, perm func(store.User, store.Repo, string) bool) (store.Repo, store.MR, int) {
140	if len(args) < 2 {
141		return store.Repo{}, store.MR{}, c.fail(protocol.ExitUsage, "expected <owner/name> <number>")
142	}
143	repo, code := resolveRepo(c, args[0], perm)
144	if code >= 0 {
145		return repo, store.MR{}, code
146	}
147	n, err := strconv.ParseInt(args[1], 10, 64)
148	if err != nil {
149		return repo, store.MR{}, c.fail(protocol.ExitUsage, "bad MR number %q", args[1])
150	}
151	mr, err := c.Store.MRByNumber(repo.ID, n)
152	if errors.Is(err, store.ErrNotFound) {
153		return repo, mr, c.fail(protocol.ExitNotFound, "MR !%d not found in %s", n, repo.Path())
154	}
155	if err != nil {
156		return repo, mr, c.fail(protocol.ExitFailure, "%v", err)
157	}
158	return repo, mr, -1
159}
160
161func mrHeadRef(n int64) string { return fmt.Sprintf("refs/merge-requests/%d/head", n) }
162
163func runMRCreate(c *Ctx, args []string) int {
164	var path, source, target, title, body, file string
165	for i := 0; i < len(args); i++ {
166		switch args[i] {
167		case "--source", "--target", "--title", "--body", "--file":
168			if i+1 >= len(args) {
169				return c.fail(protocol.ExitUsage, "%s requires a value", args[i])
170			}
171			v := args[i+1]
172			switch args[i] {
173			case "--source":
174				source = v
175			case "--target":
176				target = v
177			case "--title":
178				title = v
179			case "--body":
180				body = v
181			case "--file":
182				file = v
183			}
184			i++
185		default:
186			if path != "" {
187				return c.fail(protocol.ExitUsage, "unexpected argument %q", args[i])
188			}
189			path = args[i]
190		}
191	}
192	if path == "" || source == "" || title == "" {
193		return c.fail(protocol.ExitUsage, "usage: mr create <target owner/name> --source [owner/name:]<branch> --target <branch> --title <t>")
194	}
195	repo, code := resolveRepo(c, path, policy.CanRead)
196	if code >= 0 {
197		return code
198	}
199	if target == "" {
200		target = repo.DefaultBranch
201	}
202
203	// Source is "branch" (same repo) or "owner/name:branch" (a fork).
204	srcRepo := repo
205	srcBranch := source
206	if sp, br, ok := strings.Cut(source, ":"); ok {
207		srcBranch = br
208		var scode int
209		srcRepo, scode = resolveRepo(c, sp, policy.CanRead)
210		if scode >= 0 {
211			return scode
212		}
213		if srcRepo.ForkOf != repo.ID && srcRepo.ID != repo.ID {
214			return c.fail(protocol.ExitUsage, "%s is not a fork of %s", srcRepo.Path(), repo.Path())
215		}
216	}
217	srcDir := RepoDir(c.Cfg.Server.Root, srcRepo.OwnerName, srcRepo.Name)
218	headSHA, err := gitutil.ResolveRef(srcDir, "refs/heads/"+srcBranch)
219	if err != nil {
220		return c.fail(protocol.ExitNotFound, "branch %s not found in %s", srcBranch, srcRepo.Path())
221	}
222	b, err := bodyFrom(c, body, file)
223	if err != nil {
224		return c.fail(protocol.ExitUsage, "%v", err)
225	}
226	n, err := c.Store.CreateMR(repo.ID, c.User.ID, srcRepo.ID, srcBranch, target, title, b, headSHA)
227	if err != nil {
228		return c.fail(protocol.ExitFailure, "%v", err)
229	}
230	// Fetch the head into the target so the target owns the objects.
231	dstDir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
232	if err := gitutil.FetchInto(dstDir, srcDir, headSHA, mrHeadRef(n)); err != nil {
233		return c.fail(protocol.ExitFailure, "recording MR head: %v", err)
234	}
235	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.created", fmt.Sprintf(`{"number":%d}`, n))
236	return c.emit(map[string]any{"number": n, "head_sha": headSHA}, func(w io.Writer) {
237		fmt.Fprintf(w, "created %s!%d (%s -> %s)\n", repo.Path(), n, source, target)
238	})
239}
240
241type mrOut struct {
242	Number    int64  `json:"number"`
243	Title     string `json:"title"`
244	State     string `json:"state"`
245	Author    string `json:"author"`
246	Source    string `json:"source"` // owner/name:branch, or branch, "" if gone
247	TargetRef string `json:"target_ref"`
248	HeadSHA   string `json:"head_sha"`
249	Body      string `json:"body,omitempty"`
250	CreatedAt string `json:"created_at"`
251}
252
253func mrToOut(repo store.Repo, m store.MR, withBody bool) mrOut {
254	src := ""
255	if m.SourcePath != "" {
256		if m.SourceRepoID == repo.ID {
257			src = m.SourceRef
258		} else {
259			src = m.SourcePath + ":" + m.SourceRef
260		}
261	}
262	o := mrOut{Number: m.Number, Title: m.Title, State: m.State, Author: m.Author,
263		Source: src, TargetRef: m.TargetRef, HeadSHA: m.HeadSHA, CreatedAt: m.CreatedAt}
264	if withBody {
265		o.Body = m.Body
266	}
267	return o
268}
269
270func runMRList(c *Ctx, args []string) int {
271	state := "open"
272	var path string
273	for i := 0; i < len(args); i++ {
274		switch args[i] {
275		case "--state":
276			if i+1 >= len(args) {
277				return c.fail(protocol.ExitUsage, "--state requires a value")
278			}
279			state = args[i+1]
280			i++
281		default:
282			if path != "" {
283				return c.fail(protocol.ExitUsage, "unexpected argument %q", args[i])
284			}
285			path = args[i]
286		}
287	}
288	valid := map[string]bool{"open": true, "merged": true, "closed": true, "source_gone": true, "all": true}
289	if path == "" || !valid[state] {
290		return c.fail(protocol.ExitUsage, "usage: mr list <owner/name> [--state open|merged|closed|source_gone|all]")
291	}
292	repo, code := resolveRepo(c, path, policy.CanRead)
293	if code >= 0 {
294		return code
295	}
296	mrs, err := c.Store.ListMRs(repo.ID, state)
297	if err != nil {
298		return c.fail(protocol.ExitFailure, "%v", err)
299	}
300	var ds []mrOut
301	for _, m := range mrs {
302		ds = append(ds, mrToOut(repo, m, false))
303	}
304	return c.emit(ds, func(w io.Writer) {
305		for _, d := range ds {
306			fmt.Fprintf(w, "!%d\t%s\t%s\t%s -> %s\n", d.Number, d.State, d.Title, d.Source, d.TargetRef)
307		}
308	})
309}
310
311func runMRShow(c *Ctx, args []string) int {
312	repo, mr, code := mrRef(c, args, policy.CanRead)
313	if code >= 0 {
314		return code
315	}
316	if len(args) != 2 {
317		return c.fail(protocol.ExitUsage, "usage: mr show <owner/name> <n>")
318	}
319	comments, err := c.Store.ListMRComments(mr.ID)
320	if err != nil {
321		return c.fail(protocol.ExitFailure, "%v", err)
322	}
323	reviews, err := c.Store.ListMRReviews(mr.ID)
324	if err != nil {
325		return c.fail(protocol.ExitFailure, "%v", err)
326	}
327	statuses, err := c.Store.ListCommitStatuses(repo.ID, mr.HeadSHA)
328	if err != nil {
329		return c.fail(protocol.ExitFailure, "%v", err)
330	}
331	type commentOut struct {
332		Author    string `json:"author"`
333		Body      string `json:"body"`
334		CreatedAt string `json:"created_at"`
335	}
336	type reviewOut struct {
337		Reviewer string `json:"reviewer"`
338		Verdict  string `json:"verdict"`
339		Stale    bool   `json:"stale"`
340	}
341	type checkOut struct {
342		Context string `json:"context"`
343		State   string `json:"state"`
344		URL     string `json:"url,omitempty"`
345	}
346	var checks []checkOut
347	for _, st := range statuses {
348		checks = append(checks, checkOut{st.Context, st.State, st.TargetURL})
349	}
350	var cs []commentOut
351	for _, cm := range comments {
352		cs = append(cs, commentOut{cm.Author, cm.Body, cm.CreatedAt})
353	}
354	var rs []reviewOut
355	for _, r := range reviews {
356		rs = append(rs, reviewOut{r.Reviewer, r.Verdict, r.Stale})
357	}
358	d := struct {
359		mrOut
360		Checks   []checkOut   `json:"checks,omitempty"`
361		Combined string       `json:"checks_combined,omitempty"`
362		Comments []commentOut `json:"comments,omitempty"`
363		Reviews  []reviewOut  `json:"reviews,omitempty"`
364	}{mrToOut(repo, mr, true), checks, store.CombinedStatus(statuses), cs, rs}
365	return c.emit(d, func(w io.Writer) {
366		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)
367		if d.Body != "" {
368			fmt.Fprintf(w, "\n%s\n", d.Body)
369		}
370		for _, x := range checks {
371			fmt.Fprintf(w, "check: %s %s\n", x.Context, x.State)
372		}
373		for _, r := range rs {
374			stale := ""
375			if r.Stale {
376				stale = " (stale)"
377			}
378			fmt.Fprintf(w, "review: %s %s%s\n", r.Reviewer, r.Verdict, stale)
379		}
380		for _, cm := range cs {
381			fmt.Fprintf(w, "\n--- %s at %s\n%s\n", cm.Author, cm.CreatedAt, cm.Body)
382		}
383	})
384}
385
386func runMRDiff(c *Ctx, args []string) int {
387	repo, mr, code := mrRef(c, args, policy.CanRead)
388	if code >= 0 {
389		return code
390	}
391	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
392	head := mrHeadRef(mr.Number)
393	// After a merge (especially fast-forward) the live merge-base equals
394	// the head and the diff would vanish; use the recorded base instead.
395	base := mr.MergedBase
396	if base == "" {
397		b, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, head)
398		if err != nil {
399			return c.fail(protocol.ExitFailure, "%v", err)
400		}
401		base = b
402	}
403	patch, err := gitutil.Diff(dir, base, head, 4<<20)
404	if err != nil {
405		return c.fail(protocol.ExitFailure, "%v", err)
406	}
407	fmt.Fprint(c.Stdout, patch)
408	return protocol.ExitOK
409}
410
411func runMRComment(c *Ctx, args []string) int {
412	var rest []string
413	var message, file string
414	for i := 0; i < len(args); i++ {
415		switch args[i] {
416		case "--message", "--file":
417			if i+1 >= len(args) {
418				return c.fail(protocol.ExitUsage, "%s requires a value", args[i])
419			}
420			if args[i] == "--message" {
421				message = args[i+1]
422			} else {
423				file = args[i+1]
424			}
425			i++
426		default:
427			rest = append(rest, args[i])
428		}
429	}
430	repo, mr, code := mrRef(c, rest, policy.CanRead)
431	if code >= 0 {
432		return code
433	}
434	body, err := bodyFrom(c, message, file)
435	if err != nil {
436		return c.fail(protocol.ExitUsage, "%v", err)
437	}
438	if strings.TrimSpace(body) == "" {
439		return c.fail(protocol.ExitUsage, "empty comment; use --message or --file -")
440	}
441	if err := c.Store.AddMRComment(mr.ID, c.User.ID, body); err != nil {
442		return c.fail(protocol.ExitFailure, "%v", err)
443	}
444	return c.emit(map[string]any{"number": mr.Number}, func(w io.Writer) {
445		fmt.Fprintf(w, "commented on %s!%d\n", repo.Path(), mr.Number)
446	})
447}
448
449func runMRReview(c *Ctx, args []string) int {
450	verdict := ""
451	var rest []string
452	for _, a := range args {
453		switch a {
454		case "--approve":
455			verdict = "approve"
456		case "--request-changes":
457			verdict = "request_changes"
458		case "--comment":
459			verdict = "comment"
460		default:
461			rest = append(rest, a)
462		}
463	}
464	if verdict == "" {
465		return c.fail(protocol.ExitUsage, "usage: mr review <owner/name> <n> --approve|--request-changes|--comment")
466	}
467	repo, mr, code := mrRef(c, rest, policy.CanRead)
468	if code >= 0 {
469		return code
470	}
471	if mr.State != "open" {
472		return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
473	}
474	if err := c.Store.AddMRReview(mr.ID, c.User.ID, verdict, mr.HeadSHA); err != nil {
475		return c.fail(protocol.ExitFailure, "%v", err)
476	}
477	return c.emit(map[string]any{"number": mr.Number, "verdict": verdict}, func(w io.Writer) {
478		fmt.Fprintf(w, "reviewed %s!%d: %s\n", repo.Path(), mr.Number, verdict)
479	})
480}
481
482func runMRMerge(c *Ctx, args []string) int {
483	strategy := ""
484	var rest []string
485	for i := 0; i < len(args); i++ {
486		if args[i] == "--strategy" {
487			if i+1 >= len(args) {
488				return c.fail(protocol.ExitUsage, "--strategy requires ff|merge|squash|rebase")
489			}
490			strategy = args[i+1]
491			i++
492			continue
493		}
494		rest = append(rest, args[i])
495	}
496	valid := map[string]bool{"": true, "ff": true, "merge": true, "squash": true, "rebase": true}
497	if !valid[strategy] {
498		return c.fail(protocol.ExitUsage, "--strategy must be ff, merge, squash, or rebase")
499	}
500	repo, mr, code := mrRef(c, rest, policy.CanWrite)
501	if code >= 0 {
502		return code
503	}
504	if mr.State != "open" && mr.State != "source_gone" {
505		return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
506	}
507
508	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
509	targetRef := "refs/heads/" + mr.TargetRef
510	targetSHA, err := gitutil.ResolveRef(dir, targetRef)
511	if err != nil {
512		return c.fail(protocol.ExitFailure, "target branch %s: %v", mr.TargetRef, err)
513	}
514	headSHA, err := gitutil.ResolveRef(dir, mrHeadRef(mr.Number))
515	if err != nil {
516		return c.fail(protocol.ExitFailure, "MR head ref: %v", err)
517	}
518
519	// Check gate: with require_checks, the MR head must carry statuses
520	// and every one of them must be green.
521	if repo.Settings.RequireChecks {
522		statuses, err := c.Store.ListCommitStatuses(repo.ID, headSHA)
523		if err != nil {
524			return c.fail(protocol.ExitFailure, "%v", err)
525		}
526		switch store.CombinedStatus(statuses) {
527		case "success":
528		case "":
529			return c.fail(protocol.ExitDenied,
530				"%s requires green checks and none were reported on %.10s", repo.Path(), headSHA)
531		default:
532			var bad []string
533			for _, st := range statuses {
534				if st.State != "success" {
535					bad = append(bad, st.Context+"="+st.State)
536				}
537			}
538			return c.fail(protocol.ExitDenied,
539				"%s requires green checks; %.10s has %s", repo.Path(), headSHA, strings.Join(bad, ", "))
540		}
541	}
542
543	upToDate, err := gitutil.IsAncestor(dir, headSHA, targetSHA)
544	if err != nil {
545		return c.fail(protocol.ExitFailure, "%v", err)
546	}
547	if upToDate {
548		return c.fail(protocol.ExitUsage, "target already contains the MR head")
549	}
550	ffPossible, err := gitutil.IsAncestor(dir, targetSHA, headSHA)
551	if err != nil {
552		return c.fail(protocol.ExitFailure, "%v", err)
553	}
554
555	// Signature policy matrix: with require_signed_commits, only
556	// fast-forward is allowed — squash, rebase-replay, and merge commits
557	// are all server-created and unsigned, violating the branch's own
558	// policy — and every landed commit must be verified. An explicit
559	// rebase when fast-forward is already possible IS a fast-forward
560	// (nothing is rewritten), so it stays legal.
561	if repo.Settings.RequireSignedCommits {
562		if strategy == "merge" || strategy == "squash" || !ffPossible {
563			return c.fail(protocol.ExitDenied,
564				"%s requires signed commits, so only fast-forward merges are allowed; rebase %s onto %s locally, re-push, and merge again",
565				repo.Path(), mr.SourceRef, mr.TargetRef)
566		}
567		strategy = "ff"
568		commits, err := gitutil.RevListRange(dir, targetSHA, headSHA)
569		if err != nil {
570			return c.fail(protocol.ExitFailure, "%v", err)
571		}
572		for _, sha := range commits {
573			raw, err := gitutil.ReadCommit(dir, sha)
574			if err != nil {
575				return c.fail(protocol.ExitFailure, "%v", err)
576			}
577			parsed, err := sigParse(raw)
578			if err != nil {
579				return c.fail(protocol.ExitFailure, "%v", err)
580			}
581			res, err := VerifyCommitCached(c.Store, repo, parsed, sha)
582			if err != nil {
583				return c.fail(protocol.ExitFailure, "%v", err)
584			}
585			if res.State != "verified" {
586				return c.fail(protocol.ExitDenied,
587					"%s requires signed commits: %.10s is %s", repo.Path(), sha, res.State)
588			}
589		}
590	}
591	if strategy == "" {
592		if ffPossible {
593			strategy = "ff"
594		} else {
595			strategy = "merge"
596		}
597	}
598	if strategy == "rebase" && ffPossible {
599		// Nothing to rewrite: a rebase onto an ancestor is a fast-forward,
600		// and taking it keeps the original commits and their signatures.
601		strategy = "ff"
602	}
603
604	// Every server-created commit needs the merger's verified identity.
605	mergerEmail := ""
606	if strategy != "ff" {
607		email, err := c.Store.PrimaryVerifiedEmail(c.User.ID)
608		if err != nil {
609			return c.fail(protocol.ExitFailure, "%v", err)
610		}
611		if email == "" {
612			return c.fail(protocol.ExitDenied,
613				"%s merges create commits carrying your identity: verify a primary email first (or use a fast-forward merge)", strategy)
614		}
615		mergerEmail = email
616	}
617
618	var newSHA string
619	switch strategy {
620	case "ff":
621		if !ffPossible {
622			return c.fail(protocol.ExitUsage,
623				"fast-forward not possible: %s has diverged from the MR head; use --strategy merge or rebase and re-push", mr.TargetRef)
624		}
625		newSHA = headSHA
626
627	case "merge":
628		tree, conflict, err := gitutil.MergeTree(dir, targetSHA, headSHA)
629		if err != nil {
630			return c.fail(protocol.ExitFailure, "%v", err)
631		}
632		if conflict {
633			return c.fail(protocol.ExitUsage,
634				"merge conflicts between %s and the MR head; resolve locally and re-push", mr.TargetRef)
635		}
636		msg := fmt.Sprintf("Merge request !%d: %s\n\nMerged %s into %s", mr.Number, mr.Title, mr.SourceRef, mr.TargetRef)
637		newSHA, err = gitutil.CommitTree(dir, tree, []string{targetSHA, headSHA}, c.User.Username, mergerEmail, msg)
638		if err != nil {
639			return c.fail(protocol.ExitFailure, "%v", err)
640		}
641
642	case "squash":
643		// One new commit with the merged tree. Authorship credit goes to
644		// the MR author (their verified identity when they have one); the
645		// committer is the merger.
646		tree := ""
647		if ffPossible {
648			t, err := gitutil.ResolveTree(dir, headSHA)
649			if err != nil {
650				return c.fail(protocol.ExitFailure, "%v", err)
651			}
652			tree = t
653		} else {
654			t, conflict, err := gitutil.MergeTree(dir, targetSHA, headSHA)
655			if err != nil {
656				return c.fail(protocol.ExitFailure, "%v", err)
657			}
658			if conflict {
659				return c.fail(protocol.ExitUsage,
660					"merge conflicts between %s and the MR head; resolve locally and re-push", mr.TargetRef)
661			}
662			tree = t
663		}
664		authorName, authorEmail := c.User.Username, mergerEmail
665		if author, err := c.Store.UserByUsername(mr.Author); err == nil {
666			if ae, err := c.Store.PrimaryVerifiedEmail(author.ID); err == nil && ae != "" {
667				authorName, authorEmail = author.Username, ae
668			}
669		}
670		msg := fmt.Sprintf("%s (!%d)", mr.Title, mr.Number)
671		if mr.Body != "" {
672			msg += "\n\n" + mr.Body
673		}
674		var err error
675		newSHA, err = gitutil.CommitTreeIdent(dir, tree, []string{targetSHA},
676			authorName, authorEmail, "", c.User.Username, mergerEmail, msg)
677		if err != nil {
678			return c.fail(protocol.ExitFailure, "%v", err)
679		}
680
681	case "rebase":
682		commits, err := gitutil.RevListRange(dir, targetSHA, headSHA)
683		if err != nil {
684			return c.fail(protocol.ExitFailure, "%v", err)
685		}
686		// Oldest first.
687		for i, j := 0, len(commits)-1; i < j; i, j = i+1, j-1 {
688			commits[i], commits[j] = commits[j], commits[i]
689		}
690		onto := targetSHA
691		for _, sha := range commits {
692			parents, err := gitutil.CommitParents(dir, sha)
693			if err != nil {
694				return c.fail(protocol.ExitFailure, "%v", err)
695			}
696			if len(parents) > 1 {
697				return c.fail(protocol.ExitUsage,
698					"the MR contains merge commit %.10s; a rebase merge needs linear history — use --strategy merge or squash", sha)
699			}
700			base := onto // root commit: replay against the new tip itself
701			if len(parents) == 1 {
702				base = parents[0]
703			}
704			tree, conflict, err := gitutil.MergeTreeOnto(dir, base, onto, sha)
705			if err != nil {
706				return c.fail(protocol.ExitFailure, "%v", err)
707			}
708			if conflict {
709				return c.fail(protocol.ExitUsage,
710					"commit %.10s does not apply cleanly onto %s; rebase locally and re-push", sha, mr.TargetRef)
711			}
712			aName, aEmail, aDate, err := gitutil.AuthorIdent(dir, sha)
713			if err != nil {
714				return c.fail(protocol.ExitFailure, "%v", err)
715			}
716			msg, err := gitutil.CommitMessage(dir, sha)
717			if err != nil {
718				return c.fail(protocol.ExitFailure, "%v", err)
719			}
720			onto, err = gitutil.CommitTreeIdent(dir, tree, []string{onto},
721				aName, aEmail, aDate, c.User.Username, mergerEmail, msg)
722			if err != nil {
723				return c.fail(protocol.ExitFailure, "%v", err)
724			}
725		}
726		newSHA = onto
727	}
728
729	// CAS so a concurrent push between our read and this write fails the
730	// merge instead of silently discarding the push.
731	if err := gitutil.UpdateRefCAS(dir, targetRef, newSHA, targetSHA); err != nil {
732		return c.fail(protocol.ExitFailure, "target branch moved during merge; retry: %v", err)
733	}
734	if err := c.Store.MarkMerged(mr.ID, targetSHA); err != nil {
735		return c.fail(protocol.ExitFailure, "%v", err)
736	}
737	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d,"sha":%q}`, mr.Number, newSHA))
738	return c.emit(map[string]any{"number": mr.Number, "strategy": strategy, "sha": newSHA}, func(w io.Writer) {
739		fmt.Fprintf(w, "merged %s!%d into %s (%s) at %.10s\n", repo.Path(), mr.Number, mr.TargetRef, strategy, newSHA)
740	})
741}
742
743func runMRClose(c *Ctx, args []string) int {
744	repo, mr, code := mrRef(c, args, policy.CanRead)
745	if code >= 0 {
746		return code
747	}
748	if len(args) != 2 {
749		return c.fail(protocol.ExitUsage, "usage: mr close <owner/name> <n>")
750	}
751	grant, err := c.Store.AccessRole(repo.ID, c.User.ID)
752	if err != nil {
753		return c.fail(protocol.ExitFailure, "%v", err)
754	}
755	if mr.Author != c.User.Username && !policy.CanWrite(c.User, repo, grant) {
756		return c.fail(protocol.ExitDenied, "only the author or users with write access can close this MR")
757	}
758	if mr.State == "merged" || mr.State == "closed" {
759		return c.fail(protocol.ExitUsage, "MR !%d is already %s", mr.Number, mr.State)
760	}
761	if err := c.Store.SetMRState(mr.ID, "closed"); err != nil {
762		return c.fail(protocol.ExitFailure, "%v", err)
763	}
764	return c.emit(map[string]any{"number": mr.Number, "state": "closed"}, func(w io.Writer) {
765		fmt.Fprintf(w, "closed %s!%d\n", repo.Path(), mr.Number)
766	})
767}