internal/control/mr.go

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

783 lines · 26273 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	if targets, err := c.Store.RepoNotifyTargets(repo); err == nil {
237		notifyUsers(c, targets, mrSubject(repo, n, title),
238			notifyBody(c, fmt.Sprintf("opened merge request !%d (%s -> %s)", n, source, target), b, fmt.Sprintf("%s/mrs/%d", repo.Path(), n)))
239	}
240	return c.emit(map[string]any{"number": n, "head_sha": headSHA}, func(w io.Writer) {
241		fmt.Fprintf(w, "created %s!%d (%s -> %s)\n", repo.Path(), n, source, target)
242	})
243}
244
245type mrOut struct {
246	Number    int64  `json:"number"`
247	Title     string `json:"title"`
248	State     string `json:"state"`
249	Author    string `json:"author"`
250	Source    string `json:"source"` // owner/name:branch, or branch, "" if gone
251	TargetRef string `json:"target_ref"`
252	HeadSHA   string `json:"head_sha"`
253	Body      string `json:"body,omitempty"`
254	CreatedAt string `json:"created_at"`
255}
256
257func mrToOut(repo store.Repo, m store.MR, withBody bool) mrOut {
258	src := ""
259	if m.SourcePath != "" {
260		if m.SourceRepoID == repo.ID {
261			src = m.SourceRef
262		} else {
263			src = m.SourcePath + ":" + m.SourceRef
264		}
265	}
266	o := mrOut{Number: m.Number, Title: m.Title, State: m.State, Author: m.Author,
267		Source: src, TargetRef: m.TargetRef, HeadSHA: m.HeadSHA, CreatedAt: m.CreatedAt}
268	if withBody {
269		o.Body = m.Body
270	}
271	return o
272}
273
274func runMRList(c *Ctx, args []string) int {
275	state := "open"
276	var path string
277	for i := 0; i < len(args); i++ {
278		switch args[i] {
279		case "--state":
280			if i+1 >= len(args) {
281				return c.fail(protocol.ExitUsage, "--state requires a value")
282			}
283			state = args[i+1]
284			i++
285		default:
286			if path != "" {
287				return c.fail(protocol.ExitUsage, "unexpected argument %q", args[i])
288			}
289			path = args[i]
290		}
291	}
292	valid := map[string]bool{"open": true, "merged": true, "closed": true, "source_gone": true, "all": true}
293	if path == "" || !valid[state] {
294		return c.fail(protocol.ExitUsage, "usage: mr list <owner/name> [--state open|merged|closed|source_gone|all]")
295	}
296	repo, code := resolveRepo(c, path, policy.CanRead)
297	if code >= 0 {
298		return code
299	}
300	mrs, err := c.Store.ListMRs(repo.ID, state)
301	if err != nil {
302		return c.fail(protocol.ExitFailure, "%v", err)
303	}
304	var ds []mrOut
305	for _, m := range mrs {
306		ds = append(ds, mrToOut(repo, m, false))
307	}
308	return c.emit(ds, func(w io.Writer) {
309		for _, d := range ds {
310			fmt.Fprintf(w, "!%d\t%s\t%s\t%s -> %s\n", d.Number, d.State, d.Title, d.Source, d.TargetRef)
311		}
312	})
313}
314
315func runMRShow(c *Ctx, args []string) int {
316	repo, mr, code := mrRef(c, args, policy.CanRead)
317	if code >= 0 {
318		return code
319	}
320	if len(args) != 2 {
321		return c.fail(protocol.ExitUsage, "usage: mr show <owner/name> <n>")
322	}
323	comments, err := c.Store.ListMRComments(mr.ID)
324	if err != nil {
325		return c.fail(protocol.ExitFailure, "%v", err)
326	}
327	reviews, err := c.Store.ListMRReviews(mr.ID)
328	if err != nil {
329		return c.fail(protocol.ExitFailure, "%v", err)
330	}
331	statuses, err := c.Store.ListCommitStatuses(repo.ID, mr.HeadSHA)
332	if err != nil {
333		return c.fail(protocol.ExitFailure, "%v", err)
334	}
335	type commentOut struct {
336		Author    string `json:"author"`
337		Body      string `json:"body"`
338		CreatedAt string `json:"created_at"`
339	}
340	type reviewOut struct {
341		Reviewer string `json:"reviewer"`
342		Verdict  string `json:"verdict"`
343		Stale    bool   `json:"stale"`
344	}
345	type checkOut struct {
346		Context string `json:"context"`
347		State   string `json:"state"`
348		URL     string `json:"url,omitempty"`
349	}
350	var checks []checkOut
351	for _, st := range statuses {
352		checks = append(checks, checkOut{st.Context, st.State, st.TargetURL})
353	}
354	var cs []commentOut
355	for _, cm := range comments {
356		cs = append(cs, commentOut{cm.Author, cm.Body, cm.CreatedAt})
357	}
358	var rs []reviewOut
359	for _, r := range reviews {
360		rs = append(rs, reviewOut{r.Reviewer, r.Verdict, r.Stale})
361	}
362	d := struct {
363		mrOut
364		Checks   []checkOut   `json:"checks,omitempty"`
365		Combined string       `json:"checks_combined,omitempty"`
366		Comments []commentOut `json:"comments,omitempty"`
367		Reviews  []reviewOut  `json:"reviews,omitempty"`
368	}{mrToOut(repo, mr, true), checks, store.CombinedStatus(statuses), cs, rs}
369	return c.emit(d, func(w io.Writer) {
370		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)
371		if d.Body != "" {
372			fmt.Fprintf(w, "\n%s\n", d.Body)
373		}
374		for _, x := range checks {
375			fmt.Fprintf(w, "check: %s %s\n", x.Context, x.State)
376		}
377		for _, r := range rs {
378			stale := ""
379			if r.Stale {
380				stale = " (stale)"
381			}
382			fmt.Fprintf(w, "review: %s %s%s\n", r.Reviewer, r.Verdict, stale)
383		}
384		for _, cm := range cs {
385			fmt.Fprintf(w, "\n--- %s at %s\n%s\n", cm.Author, cm.CreatedAt, cm.Body)
386		}
387	})
388}
389
390func runMRDiff(c *Ctx, args []string) int {
391	repo, mr, code := mrRef(c, args, policy.CanRead)
392	if code >= 0 {
393		return code
394	}
395	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
396	head := mrHeadRef(mr.Number)
397	// After a merge (especially fast-forward) the live merge-base equals
398	// the head and the diff would vanish; use the recorded base instead.
399	base := mr.MergedBase
400	if base == "" {
401		b, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, head)
402		if err != nil {
403			return c.fail(protocol.ExitFailure, "%v", err)
404		}
405		base = b
406	}
407	patch, err := gitutil.Diff(dir, base, head, 4<<20)
408	if err != nil {
409		return c.fail(protocol.ExitFailure, "%v", err)
410	}
411	fmt.Fprint(c.Stdout, patch)
412	return protocol.ExitOK
413}
414
415func runMRComment(c *Ctx, args []string) int {
416	var rest []string
417	var message, file string
418	for i := 0; i < len(args); i++ {
419		switch args[i] {
420		case "--message", "--file":
421			if i+1 >= len(args) {
422				return c.fail(protocol.ExitUsage, "%s requires a value", args[i])
423			}
424			if args[i] == "--message" {
425				message = args[i+1]
426			} else {
427				file = args[i+1]
428			}
429			i++
430		default:
431			rest = append(rest, args[i])
432		}
433	}
434	repo, mr, code := mrRef(c, rest, policy.CanRead)
435	if code >= 0 {
436		return code
437	}
438	body, err := bodyFrom(c, message, file)
439	if err != nil {
440		return c.fail(protocol.ExitUsage, "%v", err)
441	}
442	if strings.TrimSpace(body) == "" {
443		return c.fail(protocol.ExitUsage, "empty comment; use --message or --file -")
444	}
445	if err := c.Store.AddMRComment(mr.ID, c.User.ID, body); err != nil {
446		return c.fail(protocol.ExitFailure, "%v", err)
447	}
448	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
449		notifyUsers(c, parts, mrSubject(repo, mr.Number, mr.Title),
450			notifyBody(c, fmt.Sprintf("commented on !%d", mr.Number), body, fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)))
451	}
452	return c.emit(map[string]any{"number": mr.Number}, func(w io.Writer) {
453		fmt.Fprintf(w, "commented on %s!%d\n", repo.Path(), mr.Number)
454	})
455}
456
457func runMRReview(c *Ctx, args []string) int {
458	verdict := ""
459	var rest []string
460	for _, a := range args {
461		switch a {
462		case "--approve":
463			verdict = "approve"
464		case "--request-changes":
465			verdict = "request_changes"
466		case "--comment":
467			verdict = "comment"
468		default:
469			rest = append(rest, a)
470		}
471	}
472	if verdict == "" {
473		return c.fail(protocol.ExitUsage, "usage: mr review <owner/name> <n> --approve|--request-changes|--comment")
474	}
475	repo, mr, code := mrRef(c, rest, policy.CanRead)
476	if code >= 0 {
477		return code
478	}
479	if mr.State != "open" {
480		return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
481	}
482	if err := c.Store.AddMRReview(mr.ID, c.User.ID, verdict, mr.HeadSHA); err != nil {
483		return c.fail(protocol.ExitFailure, "%v", err)
484	}
485	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
486		notifyUsers(c, parts, mrSubject(repo, mr.Number, mr.Title),
487			notifyBody(c, fmt.Sprintf("reviewed !%d: %s", mr.Number, verdict), "", fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)))
488	}
489	return c.emit(map[string]any{"number": mr.Number, "verdict": verdict}, func(w io.Writer) {
490		fmt.Fprintf(w, "reviewed %s!%d: %s\n", repo.Path(), mr.Number, verdict)
491	})
492}
493
494func runMRMerge(c *Ctx, args []string) int {
495	strategy := ""
496	var rest []string
497	for i := 0; i < len(args); i++ {
498		if args[i] == "--strategy" {
499			if i+1 >= len(args) {
500				return c.fail(protocol.ExitUsage, "--strategy requires ff|merge|squash|rebase")
501			}
502			strategy = args[i+1]
503			i++
504			continue
505		}
506		rest = append(rest, args[i])
507	}
508	valid := map[string]bool{"": true, "ff": true, "merge": true, "squash": true, "rebase": true}
509	if !valid[strategy] {
510		return c.fail(protocol.ExitUsage, "--strategy must be ff, merge, squash, or rebase")
511	}
512	repo, mr, code := mrRef(c, rest, policy.CanWrite)
513	if code >= 0 {
514		return code
515	}
516	if mr.State != "open" && mr.State != "source_gone" {
517		return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
518	}
519
520	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
521	targetRef := "refs/heads/" + mr.TargetRef
522	targetSHA, err := gitutil.ResolveRef(dir, targetRef)
523	if err != nil {
524		return c.fail(protocol.ExitFailure, "target branch %s: %v", mr.TargetRef, err)
525	}
526	headSHA, err := gitutil.ResolveRef(dir, mrHeadRef(mr.Number))
527	if err != nil {
528		return c.fail(protocol.ExitFailure, "MR head ref: %v", err)
529	}
530
531	// Check gate: with require_checks, the MR head must carry statuses
532	// and every one of them must be green.
533	if repo.Settings.RequireChecks {
534		statuses, err := c.Store.ListCommitStatuses(repo.ID, headSHA)
535		if err != nil {
536			return c.fail(protocol.ExitFailure, "%v", err)
537		}
538		switch store.CombinedStatus(statuses) {
539		case "success":
540		case "":
541			return c.fail(protocol.ExitDenied,
542				"%s requires green checks and none were reported on %.10s", repo.Path(), headSHA)
543		default:
544			var bad []string
545			for _, st := range statuses {
546				if st.State != "success" {
547					bad = append(bad, st.Context+"="+st.State)
548				}
549			}
550			return c.fail(protocol.ExitDenied,
551				"%s requires green checks; %.10s has %s", repo.Path(), headSHA, strings.Join(bad, ", "))
552		}
553	}
554
555	upToDate, err := gitutil.IsAncestor(dir, headSHA, targetSHA)
556	if err != nil {
557		return c.fail(protocol.ExitFailure, "%v", err)
558	}
559	if upToDate {
560		return c.fail(protocol.ExitUsage, "target already contains the MR head")
561	}
562	ffPossible, err := gitutil.IsAncestor(dir, targetSHA, headSHA)
563	if err != nil {
564		return c.fail(protocol.ExitFailure, "%v", err)
565	}
566
567	// Signature policy matrix: with require_signed_commits, only
568	// fast-forward is allowed — squash, rebase-replay, and merge commits
569	// are all server-created and unsigned, violating the branch's own
570	// policy — and every landed commit must be verified. An explicit
571	// rebase when fast-forward is already possible IS a fast-forward
572	// (nothing is rewritten), so it stays legal.
573	if repo.Settings.RequireSignedCommits {
574		if strategy == "merge" || strategy == "squash" || !ffPossible {
575			return c.fail(protocol.ExitDenied,
576				"%s requires signed commits, so only fast-forward merges are allowed; rebase %s onto %s locally, re-push, and merge again",
577				repo.Path(), mr.SourceRef, mr.TargetRef)
578		}
579		strategy = "ff"
580		commits, err := gitutil.RevListRange(dir, targetSHA, headSHA)
581		if err != nil {
582			return c.fail(protocol.ExitFailure, "%v", err)
583		}
584		for _, sha := range commits {
585			raw, err := gitutil.ReadCommit(dir, sha)
586			if err != nil {
587				return c.fail(protocol.ExitFailure, "%v", err)
588			}
589			parsed, err := sigParse(raw)
590			if err != nil {
591				return c.fail(protocol.ExitFailure, "%v", err)
592			}
593			res, err := VerifyCommitCached(c.Store, repo, parsed, sha)
594			if err != nil {
595				return c.fail(protocol.ExitFailure, "%v", err)
596			}
597			if res.State != "verified" {
598				return c.fail(protocol.ExitDenied,
599					"%s requires signed commits: %.10s is %s", repo.Path(), sha, res.State)
600			}
601		}
602	}
603	if strategy == "" {
604		if ffPossible {
605			strategy = "ff"
606		} else {
607			strategy = "merge"
608		}
609	}
610	if strategy == "rebase" && ffPossible {
611		// Nothing to rewrite: a rebase onto an ancestor is a fast-forward,
612		// and taking it keeps the original commits and their signatures.
613		strategy = "ff"
614	}
615
616	// Every server-created commit needs the merger's verified identity.
617	mergerEmail := ""
618	if strategy != "ff" {
619		email, err := c.Store.PrimaryVerifiedEmail(c.User.ID)
620		if err != nil {
621			return c.fail(protocol.ExitFailure, "%v", err)
622		}
623		if email == "" {
624			return c.fail(protocol.ExitDenied,
625				"%s merges create commits carrying your identity: verify a primary email first (or use a fast-forward merge)", strategy)
626		}
627		mergerEmail = email
628	}
629
630	var newSHA string
631	switch strategy {
632	case "ff":
633		if !ffPossible {
634			return c.fail(protocol.ExitUsage,
635				"fast-forward not possible: %s has diverged from the MR head; use --strategy merge or rebase and re-push", mr.TargetRef)
636		}
637		newSHA = headSHA
638
639	case "merge":
640		tree, conflict, err := gitutil.MergeTree(dir, targetSHA, headSHA)
641		if err != nil {
642			return c.fail(protocol.ExitFailure, "%v", err)
643		}
644		if conflict {
645			return c.fail(protocol.ExitUsage,
646				"merge conflicts between %s and the MR head; resolve locally and re-push", mr.TargetRef)
647		}
648		msg := fmt.Sprintf("Merge request !%d: %s\n\nMerged %s into %s", mr.Number, mr.Title, mr.SourceRef, mr.TargetRef)
649		newSHA, err = gitutil.CommitTree(dir, tree, []string{targetSHA, headSHA}, c.User.Username, mergerEmail, msg)
650		if err != nil {
651			return c.fail(protocol.ExitFailure, "%v", err)
652		}
653
654	case "squash":
655		// One new commit with the merged tree. Authorship credit goes to
656		// the MR author (their verified identity when they have one); the
657		// committer is the merger.
658		tree := ""
659		if ffPossible {
660			t, err := gitutil.ResolveTree(dir, headSHA)
661			if err != nil {
662				return c.fail(protocol.ExitFailure, "%v", err)
663			}
664			tree = t
665		} else {
666			t, conflict, err := gitutil.MergeTree(dir, targetSHA, headSHA)
667			if err != nil {
668				return c.fail(protocol.ExitFailure, "%v", err)
669			}
670			if conflict {
671				return c.fail(protocol.ExitUsage,
672					"merge conflicts between %s and the MR head; resolve locally and re-push", mr.TargetRef)
673			}
674			tree = t
675		}
676		authorName, authorEmail := c.User.Username, mergerEmail
677		if author, err := c.Store.UserByUsername(mr.Author); err == nil {
678			if ae, err := c.Store.PrimaryVerifiedEmail(author.ID); err == nil && ae != "" {
679				authorName, authorEmail = author.Username, ae
680			}
681		}
682		msg := fmt.Sprintf("%s (!%d)", mr.Title, mr.Number)
683		if mr.Body != "" {
684			msg += "\n\n" + mr.Body
685		}
686		var err error
687		newSHA, err = gitutil.CommitTreeIdent(dir, tree, []string{targetSHA},
688			authorName, authorEmail, "", c.User.Username, mergerEmail, msg)
689		if err != nil {
690			return c.fail(protocol.ExitFailure, "%v", err)
691		}
692
693	case "rebase":
694		commits, err := gitutil.RevListRange(dir, targetSHA, headSHA)
695		if err != nil {
696			return c.fail(protocol.ExitFailure, "%v", err)
697		}
698		// Oldest first.
699		for i, j := 0, len(commits)-1; i < j; i, j = i+1, j-1 {
700			commits[i], commits[j] = commits[j], commits[i]
701		}
702		onto := targetSHA
703		for _, sha := range commits {
704			parents, err := gitutil.CommitParents(dir, sha)
705			if err != nil {
706				return c.fail(protocol.ExitFailure, "%v", err)
707			}
708			if len(parents) > 1 {
709				return c.fail(protocol.ExitUsage,
710					"the MR contains merge commit %.10s; a rebase merge needs linear history — use --strategy merge or squash", sha)
711			}
712			base := onto // root commit: replay against the new tip itself
713			if len(parents) == 1 {
714				base = parents[0]
715			}
716			tree, conflict, err := gitutil.MergeTreeOnto(dir, base, onto, sha)
717			if err != nil {
718				return c.fail(protocol.ExitFailure, "%v", err)
719			}
720			if conflict {
721				return c.fail(protocol.ExitUsage,
722					"commit %.10s does not apply cleanly onto %s; rebase locally and re-push", sha, mr.TargetRef)
723			}
724			aName, aEmail, aDate, err := gitutil.AuthorIdent(dir, sha)
725			if err != nil {
726				return c.fail(protocol.ExitFailure, "%v", err)
727			}
728			msg, err := gitutil.CommitMessage(dir, sha)
729			if err != nil {
730				return c.fail(protocol.ExitFailure, "%v", err)
731			}
732			onto, err = gitutil.CommitTreeIdent(dir, tree, []string{onto},
733				aName, aEmail, aDate, c.User.Username, mergerEmail, msg)
734			if err != nil {
735				return c.fail(protocol.ExitFailure, "%v", err)
736			}
737		}
738		newSHA = onto
739	}
740
741	// CAS so a concurrent push between our read and this write fails the
742	// merge instead of silently discarding the push.
743	if err := gitutil.UpdateRefCAS(dir, targetRef, newSHA, targetSHA); err != nil {
744		return c.fail(protocol.ExitFailure, "target branch moved during merge; retry: %v", err)
745	}
746	if err := c.Store.MarkMerged(mr.ID, targetSHA); err != nil {
747		return c.fail(protocol.ExitFailure, "%v", err)
748	}
749	c.Store.RecordEvent(repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d,"sha":%q}`, mr.Number, newSHA))
750	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
751		notifyUsers(c, parts, mrSubject(repo, mr.Number, mr.Title),
752			notifyBody(c, fmt.Sprintf("merged !%d into %s (%s)", mr.Number, mr.TargetRef, strategy), "", fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)))
753	}
754	return c.emit(map[string]any{"number": mr.Number, "strategy": strategy, "sha": newSHA}, func(w io.Writer) {
755		fmt.Fprintf(w, "merged %s!%d into %s (%s) at %.10s\n", repo.Path(), mr.Number, mr.TargetRef, strategy, newSHA)
756	})
757}
758
759func runMRClose(c *Ctx, args []string) int {
760	repo, mr, code := mrRef(c, args, policy.CanRead)
761	if code >= 0 {
762		return code
763	}
764	if len(args) != 2 {
765		return c.fail(protocol.ExitUsage, "usage: mr close <owner/name> <n>")
766	}
767	grant, err := c.Store.AccessRole(repo.ID, c.User.ID)
768	if err != nil {
769		return c.fail(protocol.ExitFailure, "%v", err)
770	}
771	if mr.Author != c.User.Username && !policy.CanWrite(c.User, repo, grant) {
772		return c.fail(protocol.ExitDenied, "only the author or users with write access can close this MR")
773	}
774	if mr.State == "merged" || mr.State == "closed" {
775		return c.fail(protocol.ExitUsage, "MR !%d is already %s", mr.Number, mr.State)
776	}
777	if err := c.Store.SetMRState(mr.ID, "closed"); err != nil {
778		return c.fail(protocol.ExitFailure, "%v", err)
779	}
780	return c.emit(map[string]any{"number": mr.Number, "state": "closed"}, func(w io.Writer) {
781		fmt.Fprintf(w, "closed %s!%d\n", repo.Path(), mr.Number)
782	})
783}