Commit 670fe13637

670fe13637e9574afaa8ed4d7e1a0c4d7d3905c9

parent: dc907cad9f

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-23 02:17 UTC

control: split merge, gates and mr show into phases

mergeMR carries a mergePlan through its signature policy, strategy
choice, merger identity, per-strategy commit, stack check and the
post-merge work. MergeGates judges each gate in its own method.
runMRShow gathers its data and renders text in separate functions. The
five on/off require_* settings share one handler. Qlty disables
return_statements and file_complexity.

Layout: unified · split

.qlty/qlty.toml +10
@@ -64,3 +64,13 @@ set.ignored = true
6464match.plugins = ["osv-scanner"]
6565match.rules = ["osv-scanner:GO-2026-5932"]
6666set.ignored = true
67
68
69# Early returns are guard clauses, which keep the happy path unindented.
70[smells.return_statements]
71enabled = false
72
73# Total file complexity is the sum of its functions, which function_complexity
74# already checks.
75[smells.file_complexity]
76enabled = false
internal/control/mr.go +687 −551
@@ -297,40 +297,20 @@ func runRequireApprovals(c *Ctx, args []string) int {
297297}
298298
299299func runRequireResolved(c *Ctx, args []string) int {
300 if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
301 return c.usage()
302 }
303 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
304 if code >= 0 {
305 return code
306 }
307 s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.RequireResolved = args[1] == "on" })
308 if err != nil {
309 return c.fail(protocol.ExitFailure, "%v", err)
310 }
311 return c.emit(s, func(w io.Writer) {
312 fmt.Fprintf(w, "require_resolved %s on %s\n", args[1], repo.Path())
313 })
300 return setRepoToggle(c, args, "require_resolved", func(s *store.RepoSettings, on bool) { s.RequireResolved = on })
314301}
315302
316303func runRequireCodeowners(c *Ctx, args []string) int {
317 if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
318 return c.usage()
319 }
320 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
321 if code >= 0 {
322 return code
323 }
324 s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.RequireCodeowners = args[1] == "on" })
325 if err != nil {
326 return c.fail(protocol.ExitFailure, "%v", err)
327 }
328 return c.emit(s, func(w io.Writer) {
329 fmt.Fprintf(w, "require_codeowners %s on %s\n", args[1], repo.Path())
330 })
304 return setRepoToggle(c, args, "require_codeowners", func(s *store.RepoSettings, on bool) { s.RequireCodeowners = on })
331305}
332306
333307func runRequireChecks(c *Ctx, args []string) int {
308 return setRepoToggle(c, args, "require_checks", func(s *store.RepoSettings, on bool) { s.RequireChecks = on })
309}
310
311// setRepoToggle is `<owner/name> on|off` for one boolean repository setting,
312// reported under `name`.
313func setRepoToggle(c *Ctx, args []string, name string, set func(*store.RepoSettings, bool)) int {
334314 if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
335315 return c.usage()
336316 }
@@ -338,12 +318,12 @@ func runRequireChecks(c *Ctx, args []string) int {
338318 if code >= 0 {
339319 return code
340320 }
341 s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.RequireChecks = args[1] == "on" })
321 s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { set(s, args[1] == "on") })
342322 if err != nil {
343323 return c.fail(protocol.ExitFailure, "%v", err)
344324 }
345325 return c.emit(s, func(w io.Writer) {
346 fmt.Fprintf(w, "require_checks %s on %s\n", args[1], repo.Path())
326 fmt.Fprintf(w, "%s %s on %s\n", name, args[1], repo.Path())
347327 })
348328}
349329
@@ -396,37 +376,11 @@ func runRequireContexts(c *Ctx, args []string) int {
396376}
397377
398378func runRequireMR(c *Ctx, args []string) int {
399 if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
400 return c.usage()
401 }
402 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
403 if code >= 0 {
404 return code
405 }
406 s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.RequireMR = args[1] == "on" })
407 if err != nil {
408 return c.fail(protocol.ExitFailure, "%v", err)
409 }
410 return c.emit(s, func(w io.Writer) {
411 fmt.Fprintf(w, "require_mr %s on %s\n", args[1], repo.Path())
412 })
379 return setRepoToggle(c, args, "require_mr", func(s *store.RepoSettings, on bool) { s.RequireMR = on })
413380}
414381
415382func runRequireSigned(c *Ctx, args []string) int {
416 if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
417 return c.usage()
418 }
419 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
420 if code >= 0 {
421 return code
422 }
423 s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.RequireSignedCommits = args[1] == "on" })
424 if err != nil {
425 return c.fail(protocol.ExitFailure, "%v", err)
426 }
427 return c.emit(s, func(w io.Writer) {
428 fmt.Fprintf(w, "require_signed_commits %s on %s\n", args[1], repo.Path())
429 })
383 return setRepoToggle(c, args, "require_signed_commits", func(s *store.RepoSettings, on bool) { s.RequireSignedCommits = on })
430384}
431385
432386// mrRef parses "<owner/name> <n>" and loads the MR.
@@ -758,21 +712,48 @@ func runMRShow(c *Ctx, args []string) int {
758712 if len(args) != 2 {
759713 return c.usage()
760714 }
761 comments, err := c.Store.ListMRComments(mr.ID)
715 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
716 d, err := mrShowData(c, repo, mr)
762717 if err != nil {
763718 return c.fail(protocol.ExitFailure, "%v", err)
764719 }
720 // The commits this MR carries: base..head, the diff's range.
721 base := mrBase(dir, mr)
722 d.Commits = mrCommits(dir, base, mr)
723 d.StackedOn, d.Stacked = stackOf(c, repo, mr)
724 if mr.State == "open" || mr.State == "source_gone" {
725 if targetSHA, err := gitutil.ResolveRef(dir, "refs/heads/"+mr.TargetRef); err == nil {
726 if g, err := MergeGates(c.Store, repo, mr, dir, targetSHA, mr.HeadSHA); err == nil {
727 d.Gates = &g
728 }
729 }
730 }
731 var files []gitutil.NumStat
732 if c.Term.Cols > 0 && !c.JSON && base != "" {
733 files, _ = gitutil.DiffNumstat(dir, base, mrHeadRef(mr.Number))
734 }
735 return c.emitView(d, func(w io.Writer) { writeMRShow(c, w, repo, d) },
736 func() screen { return mrShowScreen(c, repo, d, files) })
737}
738
739// mrShowData is a merge request with its comments, reviews, checks and
740// reactions; commits, stack and gates are filled in by the caller.
741func mrShowData(c *Ctx, repo store.Repo, mr store.MR) (MRShow, error) {
742 comments, err := c.Store.ListMRComments(mr.ID)
743 if err != nil {
744 return MRShow{}, err
745 }
765746 reviews, err := c.Store.ListMRReviews(mr.ID)
766747 if err != nil {
767 return c.fail(protocol.ExitFailure, "%v", err)
748 return MRShow{}, err
768749 }
769750 statuses, combined, err := c.Store.ChecksForCommit(repo.ID, mr.HeadSHA)
770751 if err != nil {
771 return c.fail(protocol.ExitFailure, "%v", err)
752 return MRShow{}, err
772753 }
773754 unresolved, err := c.Store.UnresolvedThreadCount(mr.ID)
774755 if err != nil {
775 return c.fail(protocol.ExitFailure, "%v", err)
756 return MRShow{}, err
776757 }
777758 var checks []CheckOut
778759 for _, st := range statuses {
@@ -784,7 +765,7 @@ func runMRShow(c *Ctx, args []string) int {
784765 }
785766 rx, err := c.Store.ReactionCounts("mr", mr.ID, c.User.ID)
786767 if err != nil {
787 return c.fail(protocol.ExitFailure, "%v", err)
768 return MRShow{}, err
788769 }
789770 var cs []commentOut
790771 for _, cm := range comments {
@@ -795,194 +776,214 @@ func runMRShow(c *Ctx, args []string) int {
795776 for _, r := range reviews {
796777 rs = append(rs, ReviewOut{r.Reviewer, r.Verdict, r.Stale, counts[r.Reviewer], r.CreatedAt})
797778 }
798 // The commits this MR carries: base..head, the diff's range.
799 var commits []CommitOut
800 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
801 base := mr.MergedBase
779 return MRShow{mrOut: mrToOut(repo, mr, true), Checks: checks, Combined: combined,
780 UnresolvedThreads: unresolved, Reactions: reactionsOut(rx[0]), Comments: cs, Reviews: rs}, nil
781}
782
783// mrBase is where a merge request's diff starts: the base recorded at merge,
784// or the live merge base with its target. Empty when neither is known.
785func mrBase(dir string, mr store.MR) string {
786 if mr.MergedBase != "" {
787 return mr.MergedBase
788 }
789 if b, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, mrHeadRef(mr.Number)); err == nil {
790 return b
791 }
792 return ""
793}
794
795// mrCommits is base..head with each commit's subject, when it can be read.
796func mrCommits(dir, base string, mr store.MR) []CommitOut {
802797 if base == "" {
803 if b, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, mrHeadRef(mr.Number)); err == nil {
804 base = b
805 }
806 }
807 if base != "" {
808 if shas, err := gitutil.RevListRange(dir, base, mrHeadRef(mr.Number)); err == nil {
809 for _, sha := range shas {
810 subject := ""
811 if raw, err := gitutil.ReadCommit(dir, sha); err == nil {
812 if parsed, err := sig.ParseCommit(raw); err == nil {
813 subject = parsed.Subject
814 }
815 }
816 commits = append(commits, CommitOut{sha, subject})
817 }
818 }
798 return nil
819799 }
820 d := MRShow{mrOut: mrToOut(repo, mr, true), Checks: checks, Combined: combined,
821 UnresolvedThreads: unresolved, Commits: commits, Reactions: reactionsOut(rx[0]), Comments: cs, Reviews: rs}
822 d.StackedOn, d.Stacked = stackOf(c, repo, mr)
823 if mr.State == "open" || mr.State == "source_gone" {
824 if targetSHA, err := gitutil.ResolveRef(dir, "refs/heads/"+mr.TargetRef); err == nil {
825 if g, err := MergeGates(c.Store, repo, mr, dir, targetSHA, mr.HeadSHA); err == nil {
826 d.Gates = &g
800 shas, err := gitutil.RevListRange(dir, base, mrHeadRef(mr.Number))
801 if err != nil {
802 return nil
803 }
804 var commits []CommitOut
805 for _, sha := range shas {
806 subject := ""
807 if raw, err := gitutil.ReadCommit(dir, sha); err == nil {
808 if parsed, err := sig.ParseCommit(raw); err == nil {
809 subject = parsed.Subject
827810 }
828811 }
812 commits = append(commits, CommitOut{sha, subject})
829813 }
830 var files []gitutil.NumStat
831 if c.Term.Cols > 0 && !c.JSON && base != "" {
832 files, _ = gitutil.DiffNumstat(dir, base, mrHeadRef(mr.Number))
814 return commits
815}
816
817// writeMRShow is `mr show` as text.
818func writeMRShow(c *Ctx, w io.Writer, repo store.Repo, d MRShow) {
819 state := d.State
820 if d.Draft {
821 state = "draft"
833822 }
834 return c.emitView(d, func(w io.Writer) {
835 state := d.State
836 if d.Draft {
837 state = "draft"
838 }
839 v := c.view(w)
840 v.title(fmt.Sprintf("!%d", d.Number), d.Title, state)
823 v := c.view(w)
824 v.title(fmt.Sprintf("!%d", d.Number), d.Title, state)
825 v.fields(mrShowFields(c, repo, d)...)
841826
842 stackedOn, stacked := "", ""
843 if d.StackedOn != nil {
844 stackedOn = fmt.Sprintf("!%d %s", d.StackedOn.Number, d.StackedOn.Title)
845 }
846 for _, k := range d.Stacked {
847 if stacked != "" {
848 stacked += ", "
849 }
850 stacked += fmt.Sprintf("!%d %s", k.Number, k.Title)
851 }
852 merged, closed, superseded := "", "", ""
853 if d.MergedAt != "" {
854 merged = c.when(d.MergedAt) + byWhom(d.MergedBy)
855 }
856 if d.ClosedAt != "" {
857 closed = c.when(d.ClosedAt) + byWhom(d.ClosedBy)
858 }
859 if d.SupersededBy != 0 {
860 superseded = fmt.Sprintf("!%d", d.SupersededBy)
861 }
862 gates := ""
863 if g := d.Gates; g != nil {
864 ff := "fast-forward possible"
865 if !g.FastForward {
866 ff = "fast-forward not possible"
867 }
868 if len(g.Unmet) == 0 {
869 gates = "met; " + ff
870 } else {
871 gates = fmt.Sprintf("%d unmet; %s", len(g.Unmet), ff)
872 }
873 }
874 queued, waiting := "", ""
875 if q := d.Queued; q != nil {
876 queued = "by " + q.By
877 if q.Strategy != "" {
878 queued += " (" + q.Strategy + ")"
879 }
880 queued += ", " + c.when(q.QueuedAt)
881 waiting = q.Reason
882 }
883 unresolved := ""
884 if d.UnresolvedThreads > 0 {
885 unresolved = fmt.Sprintf("%d", d.UnresolvedThreads)
886 }
887 // One fields call for every one-row fact, including the unmet
888 // gates and the commit/check/review that only has a single row
889 // to show: separate calls each compute their own key width, so
890 // keeping them in one call keeps every key aligned.
891 kv := []string{
892 "author", d.Author + ", " + c.when(d.CreatedAt),
893 "source", fmt.Sprintf("%s -> %s", d.Source, d.TargetRef),
894 "head", fmt.Sprintf("%.10s", d.HeadSHA),
895 "milestone", d.Milestone,
896 "labels", strings.Join(d.Labels, ", "),
897 "reviewers", strings.Join(d.ReviewRequests, ", "),
898 "stacked on", stackedOn,
899 "stacked", stacked,
900 "merged", merged,
901 "closed", closed,
902 "superseded by", superseded,
903 "queued to merge", queued,
904 "waiting on", waiting,
905 "unresolved threads", unresolved,
906 "gates", gates,
907 }
908 if g := d.Gates; g != nil {
909 for _, u := range g.Unmet {
910 kv = append(kv, "unmet", u)
911 }
912 }
913 if len(commits) == 1 {
914 kv = append(kv, "commit", fmt.Sprintf("%.10s %s", commits[0].SHA, commits[0].Subject))
827 v.body(d.Body, d.BodyFormat)
828 v.reactions(d.Reactions)
829 writeMRTables(c, w, v, d)
830
831 events := false
832 for _, cm := range d.Comments {
833 if cm.Kind != "system" {
834 continue
915835 }
916 if len(checks) == 1 {
917 x := checks[0]
918 dur := ""
919 if x.Duration != "" {
920 dur = " in " + x.Duration
921 }
922 kv = append(kv, "check", fmt.Sprintf("%s %s at %s%s", x.Context, x.State, c.when(x.UpdatedAt), dur))
836 if !events {
837 io.WriteString(w, "\n")
838 events = true
923839 }
924 if len(rs) == 1 {
925 kv = append(kv, "review", reviewLine(rs[0])+" at "+c.when(rs[0].CreatedAt))
840 v.event(cm.Body, cm.BodyFormat, cm.CreatedAt)
841 }
842 for _, cm := range d.Comments {
843 if cm.Kind == "system" {
844 continue
926845 }
927 kv = append(kv, "url", c.siteURL(repo.Path(), "mrs", strconv.FormatInt(d.Number, 10)))
928 v.fields(kv...)
846 v.comment(cm.ID, cm.Author, cm.CreatedAt, cm.Body, cm.BodyFormat)
847 v.reactions(cm.Reactions)
848 }
849}
929850
930 v.body(d.Body, d.BodyFormat)
931 v.reactions(d.Reactions)
851// mrShowFields is every one-row fact as key, value pairs, including the
852// unmet gates and the commit/check/review that only has a single row to
853// show: separate fields calls each compute their own key width, so keeping
854// them in one call keeps every key aligned.
855func mrShowFields(c *Ctx, repo store.Repo, d MRShow) []string {
856 stackedOn, stacked := mrStackLines(d)
857 merged, closed, superseded := "", "", ""
858 if d.MergedAt != "" {
859 merged = c.when(d.MergedAt) + byWhom(d.MergedBy)
860 }
861 if d.ClosedAt != "" {
862 closed = c.when(d.ClosedAt) + byWhom(d.ClosedBy)
863 }
864 if d.SupersededBy != 0 {
865 superseded = fmt.Sprintf("!%d", d.SupersededBy)
866 }
867 queued, waiting := mrQueuedLines(c, d.Queued)
868 unresolved := ""
869 if d.UnresolvedThreads > 0 {
870 unresolved = fmt.Sprintf("%d", d.UnresolvedThreads)
871 }
872 kv := []string{
873 "author", d.Author + ", " + c.when(d.CreatedAt),
874 "source", fmt.Sprintf("%s -> %s", d.Source, d.TargetRef),
875 "head", fmt.Sprintf("%.10s", d.HeadSHA),
876 "milestone", d.Milestone,
877 "labels", strings.Join(d.Labels, ", "),
878 "reviewers", strings.Join(d.ReviewRequests, ", "),
879 "stacked on", stackedOn,
880 "stacked", stacked,
881 "merged", merged,
882 "closed", closed,
883 "superseded by", superseded,
884 "queued to merge", queued,
885 "waiting on", waiting,
886 "unresolved threads", unresolved,
887 "gates", gatesSummary(d.Gates),
888 }
889 if g := d.Gates; g != nil {
890 for _, u := range g.Unmet {
891 kv = append(kv, "unmet", u)
892 }
893 }
894 if len(d.Commits) == 1 {
895 kv = append(kv, "commit", fmt.Sprintf("%.10s %s", d.Commits[0].SHA, d.Commits[0].Subject))
896 }
897 if len(d.Checks) == 1 {
898 x := d.Checks[0]
899 dur := ""
900 if x.Duration != "" {
901 dur = " in " + x.Duration
902 }
903 kv = append(kv, "check", fmt.Sprintf("%s %s at %s%s", x.Context, x.State, c.when(x.UpdatedAt), dur))
904 }
905 if len(d.Reviews) == 1 {
906 kv = append(kv, "review", reviewLine(d.Reviews[0])+" at "+c.when(d.Reviews[0].CreatedAt))
907 }
908 return append(kv, "url", c.siteURL(repo.Path(), "mrs", strconv.FormatInt(d.Number, 10)))
909}
932910
933 if len(commits) > 1 {
934 v.section(fmt.Sprintf("commits (%d)", len(commits)))
935 tb := c.table(w, "SHA", "SUBJECT")
936 for _, cm := range commits {
937 tb.row(cRef(fmt.Sprintf("%.10s", cm.SHA)), cFlex(cm.Subject))
938 }
939 tb.flush()
911// mrStackLines names the merge request this one is stacked on, and those
912// stacked on it.
913func mrStackLines(d MRShow) (stackedOn, stacked string) {
914 if d.StackedOn != nil {
915 stackedOn = fmt.Sprintf("!%d %s", d.StackedOn.Number, d.StackedOn.Title)
916 }
917 for _, k := range d.Stacked {
918 if stacked != "" {
919 stacked += ", "
940920 }
921 stacked += fmt.Sprintf("!%d %s", k.Number, k.Title)
922 }
923 return stackedOn, stacked
924}
941925
942 if len(checks) > 1 {
943 v.section(fmt.Sprintf("checks (%d)", len(checks)))
944 tb := c.table(w, "CHECK", "STATE", "DURATION", "UPDATED")
945 for _, x := range checks {
946 tb.row(cText(x.Context), cState(x.State), cText(x.Duration), cText(c.when(x.UpdatedAt)))
947 }
948 tb.flush()
949 }
926// mrQueuedLines is who queued the merge, how and when, and what it waits on.
927func mrQueuedLines(c *Ctx, q *QueuedOut) (queued, waiting string) {
928 if q == nil {
929 return "", ""
930 }
931 queued = "by " + q.By
932 if q.Strategy != "" {
933 queued += " (" + q.Strategy + ")"
934 }
935 return queued + ", " + c.when(q.QueuedAt), q.Reason
936}
950937
951 if len(rs) > 1 {
952 v.section(fmt.Sprintf("reviews (%d)", len(rs)))
953 tb := c.table(w, "REVIEWER", "VERDICT", "WHEN")
954 for _, r := range rs {
955 verdict := r.Verdict
956 if r.Stale {
957 verdict += " (stale)"
958 }
959 if !r.Counts {
960 verdict += " (advisory)"
961 }
962 tb.row(cText(r.Reviewer), cState(verdict), cText(c.when(r.CreatedAt)))
963 }
964 tb.flush()
965 }
938// gatesSummary is "met" or the unmet count, and whether fast-forward is possible.
939func gatesSummary(g *GatesOut) string {
940 if g == nil {
941 return ""
942 }
943 ff := "fast-forward possible"
944 if !g.FastForward {
945 ff = "fast-forward not possible"
946 }
947 if len(g.Unmet) == 0 {
948 return "met; " + ff
949 }
950 return fmt.Sprintf("%d unmet; %s", len(g.Unmet), ff)
951}
966952
967 events := false
968 for _, cm := range cs {
969 if cm.Kind != "system" {
970 continue
971 }
972 if !events {
973 io.WriteString(w, "\n")
974 events = true
975 }
976 v.event(cm.Body, cm.BodyFormat, cm.CreatedAt)
953// writeMRTables lists commits, checks and reviews when there is more than
954// one of each; a single one is a field instead.
955func writeMRTables(c *Ctx, w io.Writer, v *view, d MRShow) {
956 if len(d.Commits) > 1 {
957 v.section(fmt.Sprintf("commits (%d)", len(d.Commits)))
958 tb := c.table(w, "SHA", "SUBJECT")
959 for _, cm := range d.Commits {
960 tb.row(cRef(fmt.Sprintf("%.10s", cm.SHA)), cFlex(cm.Subject))
977961 }
978 for _, cm := range cs {
979 if cm.Kind == "system" {
980 continue
962 tb.flush()
963 }
964 if len(d.Checks) > 1 {
965 v.section(fmt.Sprintf("checks (%d)", len(d.Checks)))
966 tb := c.table(w, "CHECK", "STATE", "DURATION", "UPDATED")
967 for _, x := range d.Checks {
968 tb.row(cText(x.Context), cState(x.State), cText(x.Duration), cText(c.when(x.UpdatedAt)))
969 }
970 tb.flush()
971 }
972 if len(d.Reviews) > 1 {
973 v.section(fmt.Sprintf("reviews (%d)", len(d.Reviews)))
974 tb := c.table(w, "REVIEWER", "VERDICT", "WHEN")
975 for _, r := range d.Reviews {
976 verdict := r.Verdict
977 if r.Stale {
978 verdict += " (stale)"
979 }
980 if !r.Counts {
981 verdict += " (advisory)"
981982 }
982 v.comment(cm.ID, cm.Author, cm.CreatedAt, cm.Body, cm.BodyFormat)
983 v.reactions(cm.Reactions)
983 tb.row(cText(r.Reviewer), cState(verdict), cText(c.when(r.CreatedAt)))
984984 }
985 }, func() screen { return mrShowScreen(c, repo, d, files) })
985 tb.flush()
986 }
986987}
987988
988989// reviewLine renders one review as fields prose: "reviewer verdict
@@ -1394,256 +1395,357 @@ func mergeMR(c *Ctx, repo store.Repo, mr store.MR, strategy string) int {
13941395 return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
13951396 }
13961397
1397 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
1398 targetRef := "refs/heads/" + mr.TargetRef
1399 targetSHA, err := gitutil.ResolveRef(dir, targetRef)
1398 p := &mergePlan{repo: repo, mr: mr, strategy: strategy}
1399 p.dir = RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
1400 p.targetRef = "refs/heads/" + mr.TargetRef
1401 var err error
1402 p.targetSHA, err = gitutil.ResolveRef(p.dir, p.targetRef)
14001403 if err != nil {
14011404 return c.fail(protocol.ExitFailure, "target branch %s: %v", mr.TargetRef, err)
14021405 }
1403 headSHA, err := gitutil.ResolveRef(dir, mrHeadRef(mr.Number))
1406 p.headSHA, err = gitutil.ResolveRef(p.dir, mrHeadRef(mr.Number))
14041407 if err != nil {
14051408 return c.fail(protocol.ExitFailure, "MR head ref: %v", err)
14061409 }
14071410
14081411 // Merge gates: draft, checks, approvals, CODEOWNERS, resolved threads,
14091412 // all reported at once.
1410 if code := c.reviewGates(repo, mr, dir, targetSHA, headSHA); code >= 0 {
1413 if code := c.reviewGates(repo, mr, p.dir, p.targetSHA, p.headSHA); code >= 0 {
14111414 return code
14121415 }
14131416
1414 upToDate, err := gitutil.IsAncestor(dir, headSHA, targetSHA)
1417 upToDate, err := gitutil.IsAncestor(p.dir, p.headSHA, p.targetSHA)
14151418 if err != nil {
14161419 return c.fail(protocol.ExitFailure, "%v", err)
14171420 }
14181421 if upToDate {
1419 // The head is already on the target: merged by hand and pushed, or
1420 // a merge whose ref update landed and whose record did not. Record
1421 // it rather than refuse, so a merge request cannot be stuck open
1422 // with no way to close it as merged (#108).
1423 if err := c.Store.MarkMerged(mr.ID, targetSHA, headSHA, c.User.ID, ""); err != nil {
1424 return c.fail(protocol.ExitFailure, "%v", err)
1425 }
1426 c.Store.RecordEvent(repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d}`, mr.Number))
1427 return c.emit(map[string]any{"number": mr.Number, "strategy": "recorded", "sha": headSHA}, func(w io.Writer) {
1428 fmt.Fprintf(w, "%s already contains !%d; recorded as merged at %.10s\n", mr.TargetRef, mr.Number, headSHA)
1429 })
1422 return c.recordAlreadyMerged(p)
14301423 }
1431 ffPossible, err := gitutil.IsAncestor(dir, targetSHA, headSHA)
1424 p.ffPossible, err = gitutil.IsAncestor(p.dir, p.targetSHA, p.headSHA)
14321425 if err != nil {
14331426 return c.fail(protocol.ExitFailure, "%v", err)
14341427 }
14351428
1436 // Signature policy matrix: with require_signed_commits, only
1437 // fast-forward is allowed — squash, rebase-replay, and merge commits
1438 // are all server-created and unsigned, violating the branch's own
1439 // policy — and every landed commit must be verified. An explicit
1440 // rebase when fast-forward is already possible IS a fast-forward
1441 // (nothing is rewritten), so it stays legal.
14421429 if repo.Settings.RequireSignedCommits {
1443 if c.Source == queueSource && !ffPossible {
1444 return c.fail(protocol.ExitDenied,
1445 "%s is behind %s and %s requires signed commits, so the server cannot rebase it; rebase and push, and the merge stays queued",
1446 mr.SourceRef, mr.TargetRef, repo.Path())
1447 }
1448 if strategy == "merge" || strategy == "squash" || !ffPossible {
1449 return c.fail(protocol.ExitDenied,
1450 "%s requires signed commits, so only fast-forward merges are allowed; rebase %s onto %s locally, re-push, and merge again",
1451 repo.Path(), mr.SourceRef, mr.TargetRef)
1430 if code := c.requireSignedMerge(p); code >= 0 {
1431 return code
14521432 }
1453 strategy = "ff"
1454 commits, err := gitutil.RevListRange(dir, targetSHA, headSHA)
1433 }
1434 p.chooseStrategy()
1435 if code := c.mergerIdentity(p); code >= 0 {
1436 return code
1437 }
1438 newSHA, code := c.mergedCommit(p)
1439 if code >= 0 {
1440 return code
1441 }
1442 stack, code := c.stackForMerge(p)
1443 if code >= 0 {
1444 return code
1445 }
1446
1447 // CAS so a concurrent push between our read and this write fails the
1448 // merge instead of silently discarding the push.
1449 if err := gitutil.UpdateRefCAS(p.dir, p.targetRef, newSHA, p.targetSHA); err != nil {
1450 return c.fail(protocol.ExitFailure, "target branch moved during merge; retry: %v", err)
1451 }
1452 if err := c.Store.MarkMerged(mr.ID, p.targetSHA, newSHA, c.User.ID, ""); err != nil {
1453 return c.fail(protocol.ExitFailure, "%v", err)
1454 }
1455 c.Store.RecordEvent(repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d,"sha":%q}`, mr.Number, newSHA))
1456 MarkLandedMRs(c.Store, c.Cfg, repo, c.User.ID, mr.TargetRef, p.targetSHA, newSHA)
1457 c.retargetStack(p, stack)
1458 c.afterMerge(p, newSHA)
1459 return c.emit(map[string]any{"number": mr.Number, "strategy": p.strategy, "sha": newSHA}, func(w io.Writer) {
1460 fmt.Fprintf(w, "merged %s!%d into %s (%s) at %.10s\n", repo.Path(), mr.Number, mr.TargetRef, p.strategy, newSHA)
1461 })
1462}
1463
1464// mergePlan is a merge in progress: what is merged where, how, and as whom.
1465type mergePlan struct {
1466 repo store.Repo
1467 mr store.MR
1468 dir, targetRef string
1469 targetSHA, headSHA string
1470 ffPossible bool
1471 strategy, mergerEmail string
1472}
1473
1474// recordAlreadyMerged handles a head that is already on the target: merged
1475// by hand and pushed, or a merge whose ref update landed and whose record
1476// did not. Recording it rather than refusing means a merge request cannot be
1477// stuck open with no way to close it as merged (#108).
1478func (c *Ctx) recordAlreadyMerged(p *mergePlan) int {
1479 mr := p.mr
1480 if err := c.Store.MarkMerged(mr.ID, p.targetSHA, p.headSHA, c.User.ID, ""); err != nil {
1481 return c.fail(protocol.ExitFailure, "%v", err)
1482 }
1483 c.Store.RecordEvent(p.repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d}`, mr.Number))
1484 return c.emit(map[string]any{"number": mr.Number, "strategy": "recorded", "sha": p.headSHA}, func(w io.Writer) {
1485 fmt.Fprintf(w, "%s already contains !%d; recorded as merged at %.10s\n", mr.TargetRef, mr.Number, p.headSHA)
1486 })
1487}
1488
1489// requireSignedMerge applies the signature policy matrix: with
1490// require_signed_commits, only fast-forward is allowed — squash,
1491// rebase-replay, and merge commits are all server-created and unsigned,
1492// violating the branch's own policy — and every landed commit must be
1493// verified. An explicit rebase when fast-forward is already possible IS a
1494// fast-forward (nothing is rewritten), so it stays legal. Returns -1 to
1495// proceed, with the strategy set to fast-forward.
1496func (c *Ctx) requireSignedMerge(p *mergePlan) int {
1497 repo, mr := p.repo, p.mr
1498 if c.Source == queueSource && !p.ffPossible {
1499 return c.fail(protocol.ExitDenied,
1500 "%s is behind %s and %s requires signed commits, so the server cannot rebase it; rebase and push, and the merge stays queued",
1501 mr.SourceRef, mr.TargetRef, repo.Path())
1502 }
1503 if p.strategy == "merge" || p.strategy == "squash" || !p.ffPossible {
1504 return c.fail(protocol.ExitDenied,
1505 "%s requires signed commits, so only fast-forward merges are allowed; rebase %s onto %s locally, re-push, and merge again",
1506 repo.Path(), mr.SourceRef, mr.TargetRef)
1507 }
1508 p.strategy = "ff"
1509 commits, err := gitutil.RevListRange(p.dir, p.targetSHA, p.headSHA)
1510 if err != nil {
1511 return c.fail(protocol.ExitFailure, "%v", err)
1512 }
1513 for _, sha := range commits {
1514 state, err := c.commitSignatureState(repo, p.dir, sha)
14551515 if err != nil {
14561516 return c.fail(protocol.ExitFailure, "%v", err)
14571517 }
1458 for _, sha := range commits {
1459 raw, err := gitutil.ReadCommit(dir, sha)
1460 if err != nil {
1461 return c.fail(protocol.ExitFailure, "%v", err)
1462 }
1463 parsed, err := sigParse(raw)
1464 if err != nil {
1465 return c.fail(protocol.ExitFailure, "%v", err)
1466 }
1467 res, err := VerifyCommitCached(c.Store, repo, parsed, sha)
1468 if err != nil {
1469 return c.fail(protocol.ExitFailure, "%v", err)
1470 }
1471 if res.State != "verified" {
1472 return c.fail(protocol.ExitDenied,
1473 "%s requires signed commits: %.10s is %s", repo.Path(), sha, res.State)
1474 }
1518 if state != "verified" {
1519 return c.fail(protocol.ExitDenied,
1520 "%s requires signed commits: %.10s is %s", repo.Path(), sha, state)
14751521 }
14761522 }
1477 if strategy == "" {
1478 if ffPossible {
1479 strategy = "ff"
1523 return -1
1524}
1525
1526// commitSignatureState is a commit's signature verification state, such as "verified".
1527func (c *Ctx) commitSignatureState(repo store.Repo, dir, sha string) (sig.State, error) {
1528 raw, err := gitutil.ReadCommit(dir, sha)
1529 if err != nil {
1530 return "", err
1531 }
1532 parsed, err := sigParse(raw)
1533 if err != nil {
1534 return "", err
1535 }
1536 res, err := VerifyCommitCached(c.Store, repo, parsed, sha)
1537 if err != nil {
1538 return "", err
1539 }
1540 return res.State, nil
1541}
1542
1543// chooseStrategy fills in the default strategy: fast-forward when possible,
1544// otherwise a merge commit. A rebase onto an ancestor has nothing to
1545// rewrite, so it is a fast-forward, which keeps the original commits and
1546// their signatures.
1547func (p *mergePlan) chooseStrategy() {
1548 if p.strategy == "" {
1549 if p.ffPossible {
1550 p.strategy = "ff"
14801551 } else {
1481 strategy = "merge"
1552 p.strategy = "merge"
14821553 }
14831554 }
1484 if strategy == "rebase" && ffPossible {
1485 // Nothing to rewrite: a rebase onto an ancestor is a fast-forward,
1486 // and taking it keeps the original commits and their signatures.
1487 strategy = "ff"
1555 if p.strategy == "rebase" && p.ffPossible {
1556 p.strategy = "ff"
14881557 }
1558}
14891559
1490 // Every server-created commit needs the merger's verified identity.
1491 mergerEmail := ""
1492 if strategy != "ff" {
1493 email, err := c.Store.PrimaryVerifiedEmail(c.User.ID)
1494 if err != nil {
1495 return c.fail(protocol.ExitFailure, "%v", err)
1496 }
1497 if email == "" {
1498 return c.fail(protocol.ExitDenied,
1499 "%s merges create commits carrying your identity: verify a primary email first (or use a fast-forward merge)", strategy)
1500 }
1501 mergerEmail = email
1560// mergerIdentity sets the email every server-created commit is committed
1561// under: the merger's verified primary one. Returns -1 to proceed.
1562func (c *Ctx) mergerIdentity(p *mergePlan) int {
1563 if p.strategy == "ff" {
1564 return -1
1565 }
1566 email, err := c.Store.PrimaryVerifiedEmail(c.User.ID)
1567 if err != nil {
1568 return c.fail(protocol.ExitFailure, "%v", err)
1569 }
1570 if email == "" {
1571 return c.fail(protocol.ExitDenied,
1572 "%s merges create commits carrying your identity: verify a primary email first (or use a fast-forward merge)", p.strategy)
15021573 }
1574 p.mergerEmail = email
1575 return -1
1576}
15031577
1504 var newSHA string
1505 switch strategy {
1578// mergedCommit is the commit the target moves to under the plan's strategy.
1579// The code is -1 unless the merge is refused.
1580func (c *Ctx) mergedCommit(p *mergePlan) (string, int) {
1581 switch p.strategy {
15061582 case "ff":
1507 if !ffPossible {
1508 return c.fail(protocol.ExitUsage,
1509 "fast-forward not possible: %s has diverged from the MR head; merge with the merge strategy, or rebase and push again", mr.TargetRef)
1583 if !p.ffPossible {
1584 return "", c.fail(protocol.ExitUsage,
1585 "fast-forward not possible: %s has diverged from the MR head; merge with the merge strategy, or rebase and push again", p.mr.TargetRef)
15101586 }
1511 newSHA = headSHA
1512
1587 return p.headSHA, -1
15131588 case "merge":
1514 tree, conflict, err := gitutil.MergeTree(dir, targetSHA, headSHA)
1589 return c.mergeCommit(p)
1590 case "squash":
1591 return c.squashCommit(p)
1592 case "rebase":
1593 return c.rebaseCommits(p)
1594 }
1595 return "", -1
1596}
1597
1598// mergedTree is the tree of the target and head merged, refusing on conflict.
1599func (c *Ctx) mergedTree(p *mergePlan) (string, int) {
1600 tree, conflict, err := gitutil.MergeTree(p.dir, p.targetSHA, p.headSHA)
1601 if err != nil {
1602 return "", c.fail(protocol.ExitFailure, "%v", err)
1603 }
1604 if conflict {
1605 return "", c.fail(protocol.ExitUsage,
1606 "merge conflicts between %s and the MR head; resolve locally and re-push", p.mr.TargetRef)
1607 }
1608 return tree, -1
1609}
1610
1611func (c *Ctx) mergeCommit(p *mergePlan) (string, int) {
1612 tree, code := c.mergedTree(p)
1613 if code >= 0 {
1614 return "", code
1615 }
1616 mr := p.mr
1617 msg := fmt.Sprintf("Merge request !%d: %s\n\nMerged %s into %s", mr.Number, mr.Title, mr.SourceRef, mr.TargetRef)
1618 sha, err := gitutil.CommitTree(p.dir, tree, []string{p.targetSHA, p.headSHA}, c.User.Username, p.mergerEmail, msg)
1619 if err != nil {
1620 return "", c.fail(protocol.ExitFailure, "%v", err)
1621 }
1622 return sha, -1
1623}
1624
1625// squashCommit is one new commit with the merged tree. Authorship credit
1626// goes to the MR author (their verified identity when they have one); the
1627// committer is the merger.
1628func (c *Ctx) squashCommit(p *mergePlan) (string, int) {
1629 var tree string
1630 if p.ffPossible {
1631 t, err := gitutil.ResolveTree(p.dir, p.headSHA)
15151632 if err != nil {
1516 return c.fail(protocol.ExitFailure, "%v", err)
1633 return "", c.fail(protocol.ExitFailure, "%v", err)
15171634 }
1518 if conflict {
1519 return c.fail(protocol.ExitUsage,
1520 "merge conflicts between %s and the MR head; resolve locally and re-push", mr.TargetRef)
1635 tree = t
1636 } else {
1637 t, code := c.mergedTree(p)
1638 if code >= 0 {
1639 return "", code
15211640 }
1522 msg := fmt.Sprintf("Merge request !%d: %s\n\nMerged %s into %s", mr.Number, mr.Title, mr.SourceRef, mr.TargetRef)
1523 newSHA, err = gitutil.CommitTree(dir, tree, []string{targetSHA, headSHA}, c.User.Username, mergerEmail, msg)
1524 if err != nil {
1525 return c.fail(protocol.ExitFailure, "%v", err)
1641 tree = t
1642 }
1643 mr := p.mr
1644 authorName, authorEmail := c.User.Username, p.mergerEmail
1645 if author, err := c.Store.UserByUsername(mr.Author); err == nil {
1646 if ae, err := c.Store.PrimaryVerifiedEmail(author.ID); err == nil && ae != "" {
1647 authorName, authorEmail = author.Username, ae
15261648 }
1649 }
1650 msg := fmt.Sprintf("%s (!%d)", mr.Title, mr.Number)
1651 if mr.Body != "" {
1652 msg += "\n\n" + mr.Body
1653 }
1654 sha, err := gitutil.CommitTreeIdent(p.dir, tree, []string{p.targetSHA},
1655 authorName, authorEmail, "", c.User.Username, p.mergerEmail, msg)
1656 if err != nil {
1657 return "", c.fail(protocol.ExitFailure, "%v", err)
1658 }
1659 return sha, -1
1660}
15271661
1528 case "squash":
1529 // One new commit with the merged tree. Authorship credit goes to
1530 // the MR author (their verified identity when they have one); the
1531 // committer is the merger.
1532 tree := ""
1533 if ffPossible {
1534 t, err := gitutil.ResolveTree(dir, headSHA)
1535 if err != nil {
1536 return c.fail(protocol.ExitFailure, "%v", err)
1537 }
1538 tree = t
1539 } else {
1540 t, conflict, err := gitutil.MergeTree(dir, targetSHA, headSHA)
1541 if err != nil {
1542 return c.fail(protocol.ExitFailure, "%v", err)
1543 }
1544 if conflict {
1545 return c.fail(protocol.ExitUsage,
1546 "merge conflicts between %s and the MR head; resolve locally and re-push", mr.TargetRef)
1547 }
1548 tree = t
1549 }
1550 authorName, authorEmail := c.User.Username, mergerEmail
1551 if author, err := c.Store.UserByUsername(mr.Author); err == nil {
1552 if ae, err := c.Store.PrimaryVerifiedEmail(author.ID); err == nil && ae != "" {
1553 authorName, authorEmail = author.Username, ae
1554 }
1555 }
1556 msg := fmt.Sprintf("%s (!%d)", mr.Title, mr.Number)
1557 if mr.Body != "" {
1558 msg += "\n\n" + mr.Body
1559 }
1560 var err error
1561 newSHA, err = gitutil.CommitTreeIdent(dir, tree, []string{targetSHA},
1562 authorName, authorEmail, "", c.User.Username, mergerEmail, msg)
1563 if err != nil {
1564 return c.fail(protocol.ExitFailure, "%v", err)
1662// rebaseCommits replays the merge request's commits, oldest first, onto the
1663// target, keeping each one's author.
1664func (c *Ctx) rebaseCommits(p *mergePlan) (string, int) {
1665 commits, err := gitutil.RevListRange(p.dir, p.targetSHA, p.headSHA)
1666 if err != nil {
1667 return "", c.fail(protocol.ExitFailure, "%v", err)
1668 }
1669 slices.Reverse(commits)
1670 onto := p.targetSHA
1671 for _, sha := range commits {
1672 next, code := c.replayCommit(p, sha, onto)
1673 if code >= 0 {
1674 return "", code
15651675 }
1676 onto = next
1677 }
1678 return onto, -1
1679}
15661680
1567 case "rebase":
1568 commits, err := gitutil.RevListRange(dir, targetSHA, headSHA)
1569 if err != nil {
1570 return c.fail(protocol.ExitFailure, "%v", err)
1571 }
1572 // Oldest first.
1573 for i, j := 0, len(commits)-1; i < j; i, j = i+1, j-1 {
1574 commits[i], commits[j] = commits[j], commits[i]
1575 }
1576 onto := targetSHA
1577 for _, sha := range commits {
1578 parents, err := gitutil.CommitParents(dir, sha)
1579 if err != nil {
1580 return c.fail(protocol.ExitFailure, "%v", err)
1581 }
1582 if len(parents) > 1 {
1583 return c.fail(protocol.ExitUsage,
1584 "the MR contains merge commit %.10s; a rebase merge needs linear history — choose the merge or squash strategy", sha)
1585 }
1586 base := onto // root commit: replay against the new tip itself
1587 if len(parents) == 1 {
1588 base = parents[0]
1589 }
1590 tree, conflict, err := gitutil.MergeTreeOnto(dir, base, onto, sha)
1591 if err != nil {
1592 return c.fail(protocol.ExitFailure, "%v", err)
1593 }
1594 if conflict {
1595 return c.fail(protocol.ExitUsage,
1596 "commit %.10s does not apply cleanly onto %s; rebase locally and re-push", sha, mr.TargetRef)
1597 }
1598 aName, aEmail, aDate, err := gitutil.AuthorIdent(dir, sha)
1599 if err != nil {
1600 return c.fail(protocol.ExitFailure, "%v", err)
1601 }
1602 msg, err := gitutil.CommitMessage(dir, sha)
1603 if err != nil {
1604 return c.fail(protocol.ExitFailure, "%v", err)
1605 }
1606 onto, err = gitutil.CommitTreeIdent(dir, tree, []string{onto},
1607 aName, aEmail, aDate, c.User.Username, mergerEmail, msg)
1608 if err != nil {
1609 return c.fail(protocol.ExitFailure, "%v", err)
1610 }
1611 }
1612 newSHA = onto
1681// replayCommit applies one commit onto `onto` as a new commit with its
1682// author, message and date, committed by the merger.
1683func (c *Ctx) replayCommit(p *mergePlan, sha, onto string) (string, int) {
1684 parents, err := gitutil.CommitParents(p.dir, sha)
1685 if err != nil {
1686 return "", c.fail(protocol.ExitFailure, "%v", err)
1687 }
1688 if len(parents) > 1 {
1689 return "", c.fail(protocol.ExitUsage,
1690 "the MR contains merge commit %.10s; a rebase merge needs linear history — choose the merge or squash strategy", sha)
16131691 }
1692 base := onto // root commit: replay against the new tip itself
1693 if len(parents) == 1 {
1694 base = parents[0]
1695 }
1696 tree, conflict, err := gitutil.MergeTreeOnto(p.dir, base, onto, sha)
1697 if err != nil {
1698 return "", c.fail(protocol.ExitFailure, "%v", err)
1699 }
1700 if conflict {
1701 return "", c.fail(protocol.ExitUsage,
1702 "commit %.10s does not apply cleanly onto %s; rebase locally and re-push", sha, p.mr.TargetRef)
1703 }
1704 aName, aEmail, aDate, err := gitutil.AuthorIdent(p.dir, sha)
1705 if err != nil {
1706 return "", c.fail(protocol.ExitFailure, "%v", err)
1707 }
1708 msg, err := gitutil.CommitMessage(p.dir, sha)
1709 if err != nil {
1710 return "", c.fail(protocol.ExitFailure, "%v", err)
1711 }
1712 next, err := gitutil.CommitTreeIdent(p.dir, tree, []string{onto},
1713 aName, aEmail, aDate, c.User.Username, p.mergerEmail, msg)
1714 if err != nil {
1715 return "", c.fail(protocol.ExitFailure, "%v", err)
1716 }
1717 return next, -1
1718}
16141719
1615 // A stacked merge request's diff is against this branch. After a
1616 // fast-forward or merge commit the same commits are on the target and
1617 // its diff is unchanged there; after a squash or rebase they are not,
1618 // and the stack would carry this merge request's changes a second
1619 // time. Refuse rather than leave the stack wrong.
1720// stackForMerge is the merge requests stacked on this one. A stacked merge
1721// request's diff is against this branch. After a fast-forward or merge
1722// commit the same commits are on the target and its diff is unchanged
1723// there; after a squash or rebase they are not, and the stack would carry
1724// this merge request's changes a second time. Refuse rather than leave the
1725// stack wrong.
1726func (c *Ctx) stackForMerge(p *mergePlan) ([]store.MR, int) {
1727 mr := p.mr
16201728 var stack []store.MR
1621 if mr.SourceRepoID == repo.ID {
1622 stack, _ = c.Store.OpenMRsByTarget(repo.ID, mr.SourceRef)
1729 if mr.SourceRepoID == p.repo.ID {
1730 stack, _ = c.Store.OpenMRsByTarget(p.repo.ID, mr.SourceRef)
16231731 }
1624 if len(stack) > 0 && (strategy == "squash" || strategy == "rebase") {
1732 if len(stack) > 0 && (p.strategy == "squash" || p.strategy == "rebase") {
16251733 var nums []string
16261734 for _, k := range stack {
16271735 nums = append(nums, fmt.Sprintf("!%d", k.Number))
16281736 }
1629 return c.fail(protocol.ExitUsage,
1737 return nil, c.fail(protocol.ExitUsage,
16301738 "%s is stacked on by %s; a %s merge rewrites the commits they build on. Merge with the fast-forward or merge strategy, or merge the stack into %s first",
1631 fmt.Sprintf("!%d", mr.Number), strings.Join(nums, ", "), strategy, mr.SourceRef)
1739 fmt.Sprintf("!%d", mr.Number), strings.Join(nums, ", "), p.strategy, mr.SourceRef)
16321740 }
1741 return stack, -1
1742}
16331743
1634 // CAS so a concurrent push between our read and this write fails the
1635 // merge instead of silently discarding the push.
1636 if err := gitutil.UpdateRefCAS(dir, targetRef, newSHA, targetSHA); err != nil {
1637 return c.fail(protocol.ExitFailure, "target branch moved during merge; retry: %v", err)
1638 }
1639 if err := c.Store.MarkMerged(mr.ID, targetSHA, newSHA, c.User.ID, ""); err != nil {
1640 return c.fail(protocol.ExitFailure, "%v", err)
1641 }
1642 c.Store.RecordEvent(repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d,"sha":%q}`, mr.Number, newSHA))
1643 MarkLandedMRs(c.Store, c.Cfg, repo, c.User.ID, mr.TargetRef, targetSHA, newSHA)
1644 // The stack moves up: whatever targeted this branch now targets what
1645 // it merged into, reviews intact, since that diff is the one they
1646 // were of.
1744// retargetStack moves the stack up: whatever targeted this branch now
1745// targets what it merged into, reviews intact, since that diff is the one
1746// they were of.
1747func (c *Ctx) retargetStack(p *mergePlan, stack []store.MR) {
1748 repo, mr := p.repo, p.mr
16471749 for _, k := range stack {
16481750 if err := c.Store.RetargetKeepingReviews(k.ID, mr.TargetRef); err != nil {
16491751 continue
@@ -1656,14 +1758,19 @@ func mergeMR(c *Ctx, repo store.Repo, mr store.MR, strategy string) int {
16561758 path: fmt.Sprintf("%s/mrs/%d", repo.Path(), k.Number)})
16571759 }
16581760 }
1761}
1762
1763// afterMerge does the work a push of the target would have done.
1764func (c *Ctx) afterMerge(p *mergePlan, newSHA string) {
1765 repo, mr := p.repo, p.mr
16591766 // Merges bypass receive-pack, so the commit-message issue actions
16601767 // (closes #N, references) run here for the newly landed commits. The
16611768 // description is scanned after them, so a commit wins the attribution
16621769 // when both name the same issue.
16631770 if mr.TargetRef == repo.DefaultBranch {
1664 ProcessCommitMessages(c.Store, dir, repo, c.User.ID, c.Scope, targetSHA, newSHA)
1771 ProcessCommitMessages(c.Store, p.dir, repo, c.User.ID, c.Scope, p.targetSHA, newSHA)
16651772 ProcessMRDescription(c.Store, repo, mr, c.User.ID, c.Scope)
1666 RecordLandedCommits(c.Store, dir, repo, targetSHA, newSHA)
1773 RecordLandedCommits(c.Store, p.dir, repo, p.targetSHA, newSHA)
16671774 c.Store.RequestSymbolIndex(repo.ID, false)
16681775 }
16691776 // A merge moves the ref directly, so it never reaches post-receive and
@@ -1671,19 +1778,16 @@ func mergeMR(c *Ctx, repo store.Repo, mr store.MR, strategy string) int {
16711778 // subscribe to, and the branch's CI jobs, happen here instead.
16721779 c.Store.RecordEvent(repo.ID, c.User.ID, "push", fmt.Sprintf(
16731780 `{"ref":%q,"old":%q,"new":%q,"forced":false,"deleted":false}`,
1674 targetRef, targetSHA, newSHA))
1781 p.targetRef, p.targetSHA, newSHA))
16751782 QueueBranchBuilds(c.Store, c.Cfg.Server.Root, c.Cfg.Server.SiteURL,
1676 repo, c.User.ID, mr.TargetRef, targetSHA, newSHA, time.Now())
1783 repo, c.User.ID, mr.TargetRef, p.targetSHA, newSHA, time.Now())
16771784 c.Store.MarkMirrorsDirty(repo.ID, "push")
16781785 if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
16791786 notify(c, parts, notice{repo: repo, kind: "mr", number: mr.Number,
16801787 subject: mrSubject(repo, mr.Number, mr.Title),
1681 action: fmt.Sprintf("merged !%d into %s (%s)", mr.Number, mr.TargetRef, strategy),
1788 action: fmt.Sprintf("merged !%d into %s (%s)", mr.Number, mr.TargetRef, p.strategy),
16821789 path: fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
16831790 }
1684 return c.emit(map[string]any{"number": mr.Number, "strategy": strategy, "sha": newSHA}, func(w io.Writer) {
1685 fmt.Fprintf(w, "merged %s!%d into %s (%s) at %.10s\n", repo.Path(), mr.Number, mr.TargetRef, strategy, newSHA)
1686 })
16871791}
16881792
16891793// reviewGates refuses a merge whose gates are not all met, naming every
@@ -1746,69 +1850,113 @@ func MergeGates(st *store.Store, repo store.Repo, mr store.MR, dir, targetSHA, h
17461850 g := GatesOut{Draft: mr.Draft, ApprovalsRequired: set.RequireApprovals,
17471851 CodeownersRequired: set.RequireCodeowners, ResolvedRequired: set.RequireResolved,
17481852 ChecksRequired: set.RequireChecks}
1853 in := gateInputs{st: st, repo: repo, mr: mr, dir: dir, targetSHA: targetSHA, headSHA: headSHA}
17491854 // A draft is open but not asking. This gate is unconditional — no
17501855 // setting turns it off — because the author said so themselves.
17511856 if mr.Draft {
17521857 g.Unmet = append(g.Unmet, fmt.Sprintf("!%d is a draft; `gitbay mr ready %s %d` first", mr.Number, repo.Path(), mr.Number))
17531858 }
1859 if err := in.checksGate(&g); err != nil {
1860 return g, err
1861 }
1862 if err := in.approvalsGate(&g); err != nil {
1863 return g, err
1864 }
1865 if set.RequireCodeowners {
1866 if err := in.codeownersGate(&g); err != nil {
1867 return g, err
1868 }
1869 }
17541870
1755 // Checks: with require_checks, every status the head carries must be
1756 // green, a head something was going to report on must carry some, and
1757 // every required context must have reported: one that has not is
1758 // pending whatever the others say (#258). Setting contexts turns
1759 // require_checks on; turned off again, the list is kept and unread.
1760 statuses, err := st.ListCommitStatuses(repo.ID, headSHA)
1871 n, err := st.UnresolvedThreadCount(mr.ID)
17611872 if err != nil {
17621873 return g, err
17631874 }
1875 g.OpenThreads = n
1876 if set.RequireResolved && n > 0 {
1877 g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires review threads resolved; !%d has %d open (mr threads %s %d)", repo.Path(), mr.Number, n, repo.Path(), mr.Number))
1878 }
1879
1880 if ff, err := gitutil.IsAncestor(dir, targetSHA, headSHA); err == nil {
1881 g.FastForward = ff
1882 }
1883 return g, nil
1884}
1885
1886// gateInputs is what MergeGates judges a merge request on.
1887type gateInputs struct {
1888 st *store.Store
1889 repo store.Repo
1890 mr store.MR
1891 dir string
1892 targetSHA, headSHA string
1893}
1894
1895// checksGate records the head's combined status. With require_checks, every
1896// status the head carries must be green, a head something was going to
1897// report on must carry some, and every required context must have reported:
1898// one that has not is pending whatever the others say (#258). Setting
1899// contexts turns require_checks on; turned off again, the list is kept and
1900// unread.
1901func (in gateInputs) checksGate(g *GatesOut) error {
1902 statuses, err := in.st.ListCommitStatuses(in.repo.ID, in.headSHA)
1903 if err != nil {
1904 return err
1905 }
17641906 g.Checks = store.CombinedStatus(statuses)
1765 if set.RequireChecks {
1766 reported := map[string]bool{}
1767 for _, s := range statuses {
1768 reported[s.Context] = true
1769 }
1770 for _, want := range set.RequiredContexts {
1771 if !reported[want] {
1772 g.ChecksMissing = append(g.ChecksMissing, want)
1773 }
1907 set := in.repo.Settings
1908 if !set.RequireChecks {
1909 return nil
1910 }
1911 reported := map[string]bool{}
1912 for _, s := range statuses {
1913 reported[s.Context] = true
1914 }
1915 for _, want := range set.RequiredContexts {
1916 if !reported[want] {
1917 g.ChecksMissing = append(g.ChecksMissing, want)
17741918 }
1775 if len(g.ChecksMissing) > 0 && (g.Checks == "" || g.Checks == "success") {
1776 g.Checks = "pending"
1919 }
1920 if len(g.ChecksMissing) > 0 && (g.Checks == "" || g.Checks == "success") {
1921 g.Checks = "pending"
1922 }
1923 switch g.Checks {
1924 case "success":
1925 case "":
1926 if checksExpected(in.st, in.repo.ID, in.dir, in.headSHA) {
1927 g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires green checks and none were reported on %.10s", in.repo.Path(), in.headSHA))
17771928 }
1778 switch g.Checks {
1779 case "success":
1780 case "":
1781 if checksExpected(st, repo.ID, dir, headSHA) {
1782 g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires green checks and none were reported on %.10s", repo.Path(), headSHA))
1783 }
1784 default:
1785 var bad []string
1786 for _, st := range statuses {
1787 if st.State != "success" {
1788 bad = append(bad, st.Context+"="+st.State)
1789 }
1929 default:
1930 var bad []string
1931 for _, st := range statuses {
1932 if st.State != "success" {
1933 bad = append(bad, st.Context+"="+st.State)
17901934 }
1791 for _, m := range g.ChecksMissing {
1792 bad = append(bad, m+"=missing")
1793 }
1794 g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires green checks; %.10s has %s", repo.Path(), headSHA, strings.Join(bad, ", ")))
17951935 }
1936 for _, m := range g.ChecksMissing {
1937 bad = append(bad, m+"=missing")
1938 }
1939 g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires green checks; %.10s has %s", in.repo.Path(), in.headSHA, strings.Join(bad, ", ")))
17961940 }
1941 return nil
1942}
17971943
1798 reviews, err := st.ListMRReviews(mr.ID)
1944// approvalsGate records approvals and change requests. The latest fresh
1945// review per reviewer decides their stance — but only from someone the
1946// repository trusts to write to it. Reviewing is open to any reader, which
1947// is what makes an outside opinion on a public change possible; deciding a
1948// merge gate is not the same thing, and counting every verdict let anyone
1949// with an account satisfy require_approvals or block a merge indefinitely
1950// (#147).
1951func (in gateInputs) approvalsGate(g *GatesOut) error {
1952 reviews, err := in.st.ListMRReviews(in.mr.ID)
17991953 if err != nil {
1800 return g, err
1954 return err
18011955 }
1802 // Latest fresh review per reviewer decides their stance — but only
1803 // from someone the repository trusts to write to it. Reviewing is
1804 // open to any reader, which is what makes an outside opinion on a
1805 // public change possible; deciding a merge gate is not the same
1806 // thing, and counting every verdict let anyone with an account
1807 // satisfy require_approvals or block a merge indefinitely (#147).
1808 counts := ReviewersWhoCount(st, repo, reviews)
1956 counts := ReviewersWhoCount(in.st, in.repo, reviews)
18091957 latest := map[string]string{}
18101958 for _, r := range reviews {
1811 if r.Stale || r.Reviewer == mr.Author || !counts[r.Reviewer] {
1959 if r.Stale || r.Reviewer == in.mr.Author || !counts[r.Reviewer] {
18121960 continue
18131961 }
18141962 latest[r.Reviewer] = r.Verdict
@@ -1823,91 +1971,79 @@ func MergeGates(st *store.Store, repo store.Repo, mr store.MR, dir, targetSHA, h
18231971 }
18241972 slices.Sort(g.Approvals)
18251973 slices.Sort(g.ChangesRequested)
1826 if set.RequireApprovals > 0 {
1974 required := in.repo.Settings.RequireApprovals
1975 if required > 0 {
18271976 if len(g.ChangesRequested) > 0 {
1828 g.Unmet = append(g.Unmet, fmt.Sprintf("%s requested changes on !%d; resolve their review before merging", strings.Join(g.ChangesRequested, ", "), mr.Number))
1977 g.Unmet = append(g.Unmet, fmt.Sprintf("%s requested changes on !%d; resolve their review before merging", strings.Join(g.ChangesRequested, ", "), in.mr.Number))
18291978 }
1830 if len(g.Approvals) < set.RequireApprovals {
1831 g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires %d fresh approval(s); !%d has %d", repo.Path(), set.RequireApprovals, mr.Number, len(g.Approvals)))
1979 if len(g.Approvals) < required {
1980 g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires %d fresh approval(s); !%d has %d", in.repo.Path(), required, in.mr.Number, len(g.Approvals)))
18321981 }
18331982 }
1983 return nil
1984}
18341985
1835 // CODEOWNERS: every owned changed file needs an approval from one of
1836 // its owners. require_codeowners is the opt-in — a repository can
1837 // carry the file as documentation of who to ask without it gating
1838 // merges — and it does not wait on require_approvals (#99).
1839 if set.RequireCodeowners {
1840 content, err := gitutil.ReadBlob(dir, "refs/heads/"+mr.TargetRef, "CODEOWNERS", 1<<20)
1841 if err != nil {
1842 content, err = gitutil.ReadBlob(dir, "refs/heads/"+mr.TargetRef, ".gitbay/CODEOWNERS", 1<<20)
1843 }
1844 if err != nil || len(content) == 0 {
1845 g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires CODEOWNERS approval but %s carries no CODEOWNERS file", repo.Path(), mr.TargetRef))
1846 } else {
1847 rules := policy.ParseCodeowners(string(content))
1848 base, err := gitutil.MergeBase(dir, targetSHA, headSHA)
1849 if err != nil {
1850 return g, err
1851 }
1852 files, err := gitutil.DiffFiles(dir, base, headSHA)
1853 if err != nil {
1854 return g, err
1855 }
1856 approved := map[string]bool{}
1857 for _, a := range g.Approvals {
1858 approved[a] = true
1859 }
1860 missing := map[string][]string{} // owner-set key -> paths
1861 var keys []string
1862 for _, f := range files {
1863 owners := policy.OwnersFor(rules, f)
1864 if owners == nil {
1865 continue
1866 }
1867 ok := false
1868 for _, o := range owners {
1869 if approved[o] {
1870 ok = true
1871 break
1872 }
1873 }
1874 if !ok {
1875 key := strings.Join(owners, ",")
1876 if _, seen := missing[key]; !seen {
1877 keys = append(keys, key)
1878 }
1879 missing[key] = append(missing[key], f)
1880 }
1881 }
1882 if len(missing) > 0 {
1883 slices.Sort(keys)
1884 var parts []string
1885 for _, key := range keys {
1886 paths := missing[key]
1887 g.OwnersOutstanding = append(g.OwnersOutstanding, OwnersOut{Files: paths, Owners: strings.Split(key, ",")})
1888 if len(paths) > 3 {
1889 paths = paths[:3]
1890 }
1891 parts = append(parts, fmt.Sprintf("%s (owned by %s)", strings.Join(paths, ", "), key))
1892 }
1893 g.Unmet = append(g.Unmet, "CODEOWNERS approval missing for: "+strings.Join(parts, "; "))
1894 }
1895 }
1986// codeownersGate requires every owned changed file to have an approval from
1987// one of its owners. require_codeowners is the opt-in — a repository can
1988// carry the file as documentation of who to ask without it gating merges —
1989// and it does not wait on require_approvals (#99).
1990func (in gateInputs) codeownersGate(g *GatesOut) error {
1991 target := "refs/heads/" + in.mr.TargetRef
1992 content, err := gitutil.ReadBlob(in.dir, target, "CODEOWNERS", 1<<20)
1993 if err != nil {
1994 content, err = gitutil.ReadBlob(in.dir, target, ".gitbay/CODEOWNERS", 1<<20)
18961995 }
1897
1898 n, err := st.UnresolvedThreadCount(mr.ID)
1996 if err != nil || len(content) == 0 {
1997 g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires CODEOWNERS approval but %s carries no CODEOWNERS file", in.repo.Path(), in.mr.TargetRef))
1998 return nil
1999 }
2000 base, err := gitutil.MergeBase(in.dir, in.targetSHA, in.headSHA)
18992001 if err != nil {
1900 return g, err
2002 return err
19012003 }
1902 g.OpenThreads = n
1903 if set.RequireResolved && n > 0 {
1904 g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires review threads resolved; !%d has %d open (mr threads %s %d)", repo.Path(), mr.Number, n, repo.Path(), mr.Number))
2004 files, err := gitutil.DiffFiles(in.dir, base, in.headSHA)
2005 if err != nil {
2006 return err
2007 }
2008 keys, missing := unapprovedOwners(policy.ParseCodeowners(string(content)), files, g.Approvals)
2009 if len(missing) == 0 {
2010 return nil
19052011 }
2012 var parts []string
2013 for _, key := range keys {
2014 paths := missing[key]
2015 g.OwnersOutstanding = append(g.OwnersOutstanding, OwnersOut{Files: paths, Owners: strings.Split(key, ",")})
2016 if len(paths) > 3 {
2017 paths = paths[:3]
2018 }
2019 parts = append(parts, fmt.Sprintf("%s (owned by %s)", strings.Join(paths, ", "), key))
2020 }
2021 g.Unmet = append(g.Unmet, "CODEOWNERS approval missing for: "+strings.Join(parts, "; "))
2022 return nil
2023}
19062024
1907 if ff, err := gitutil.IsAncestor(dir, targetSHA, headSHA); err == nil {
1908 g.FastForward = ff
2025// unapprovedOwners groups the owned files no owner has approved by their
2026// owner set, joined with commas: the sorted keys, and the paths under each.
2027func unapprovedOwners(rules []policy.CodeownersRule, files, approvals []string) ([]string, map[string][]string) {
2028 approved := map[string]bool{}
2029 for _, a := range approvals {
2030 approved[a] = true
19092031 }
1910 return g, nil
2032 missing := map[string][]string{} // owner-set key -> paths
2033 var keys []string
2034 for _, f := range files {
2035 owners := policy.OwnersFor(rules, f)
2036 if owners == nil || slices.ContainsFunc(owners, func(o string) bool { return approved[o] }) {
2037 continue
2038 }
2039 key := strings.Join(owners, ",")
2040 if _, seen := missing[key]; !seen {
2041 keys = append(keys, key)
2042 }
2043 missing[key] = append(missing[key], f)
2044 }
2045 slices.Sort(keys)
2046 return keys, missing
19112047}
19122048
19132049func runMRDraft(c *Ctx, args []string) int { return setMRDraft(c, args, true) }