internal/control/mr.go

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

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