internal/control/mr.go

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

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