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
64match.plugins = ["osv-scanner"] 64match.plugins = ["osv-scanner"]
65match.rules = ["osv-scanner:GO-2026-5932"] 65match.rules = ["osv-scanner:GO-2026-5932"]
66set.ignored = true 66set.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 {
297} 297}
298 298
299func runRequireResolved(c *Ctx, args []string) int { 299func runRequireResolved(c *Ctx, args []string) int {
300 if len(args) != 2 || (args[1] != "on" && args[1] != "off") { 300 return setRepoToggle(c, args, "require_resolved", func(s *store.RepoSettings, on bool) { s.RequireResolved = on })
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 })
314} 301}
315 302
316func runRequireCodeowners(c *Ctx, args []string) int { 303func runRequireCodeowners(c *Ctx, args []string) int {
317 if len(args) != 2 || (args[1] != "on" && args[1] != "off") { 304 return setRepoToggle(c, args, "require_codeowners", func(s *store.RepoSettings, on bool) { s.RequireCodeowners = on })
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 })
331} 305}
332 306
333func runRequireChecks(c *Ctx, args []string) int { 307func 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 {
334 if len(args) != 2 || (args[1] != "on" && args[1] != "off") { 314 if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
335 return c.usage() 315 return c.usage()
336 } 316 }
@@ -338,12 +318,12 @@ func runRequireChecks(c *Ctx, args []string) int {
338 if code >= 0 { 318 if code >= 0 {
339 return code 319 return code
340 } 320 }
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") })
342 if err != nil { 322 if err != nil {
343 return c.fail(protocol.ExitFailure, "%v", err) 323 return c.fail(protocol.ExitFailure, "%v", err)
344 } 324 }
345 return c.emit(s, func(w io.Writer) { 325 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())
347 }) 327 })
348} 328}
349 329
@@ -396,37 +376,11 @@ func runRequireContexts(c *Ctx, args []string) int {
396} 376}
397 377
398func runRequireMR(c *Ctx, args []string) int { 378func runRequireMR(c *Ctx, args []string) int {
399 if len(args) != 2 || (args[1] != "on" && args[1] != "off") { 379 return setRepoToggle(c, args, "require_mr", func(s *store.RepoSettings, on bool) { s.RequireMR = on })
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 })
413} 380}
414 381
415func runRequireSigned(c *Ctx, args []string) int { 382func runRequireSigned(c *Ctx, args []string) int {
416 if len(args) != 2 || (args[1] != "on" && args[1] != "off") { 383 return setRepoToggle(c, args, "require_signed_commits", func(s *store.RepoSettings, on bool) { s.RequireSignedCommits = on })
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 })
430} 384}
431 385
432// mrRef parses "<owner/name> <n>" and loads the MR. 386// mrRef parses "<owner/name> <n>" and loads the MR.
@@ -758,21 +712,48 @@ func runMRShow(c *Ctx, args []string) int {
758 if len(args) != 2 { 712 if len(args) != 2 {
759 return c.usage() 713 return c.usage()
760 } 714 }
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)
762 if err != nil { 717 if err != nil {
763 return c.fail(protocol.ExitFailure, "%v", err) 718 return c.fail(protocol.ExitFailure, "%v", err)
764 } 719 }
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 }
765 reviews, err := c.Store.ListMRReviews(mr.ID) 746 reviews, err := c.Store.ListMRReviews(mr.ID)
766 if err != nil { 747 if err != nil {
767 return c.fail(protocol.ExitFailure, "%v", err) 748 return MRShow{}, err
768 } 749 }
769 statuses, combined, err := c.Store.ChecksForCommit(repo.ID, mr.HeadSHA) 750 statuses, combined, err := c.Store.ChecksForCommit(repo.ID, mr.HeadSHA)
770 if err != nil { 751 if err != nil {
771 return c.fail(protocol.ExitFailure, "%v", err) 752 return MRShow{}, err
772 } 753 }
773 unresolved, err := c.Store.UnresolvedThreadCount(mr.ID) 754 unresolved, err := c.Store.UnresolvedThreadCount(mr.ID)
774 if err != nil { 755 if err != nil {
775 return c.fail(protocol.ExitFailure, "%v", err) 756 return MRShow{}, err
776 } 757 }
777 var checks []CheckOut 758 var checks []CheckOut
778 for _, st := range statuses { 759 for _, st := range statuses {
@@ -784,7 +765,7 @@ func runMRShow(c *Ctx, args []string) int {
784 } 765 }
785 rx, err := c.Store.ReactionCounts("mr", mr.ID, c.User.ID) 766 rx, err := c.Store.ReactionCounts("mr", mr.ID, c.User.ID)
786 if err != nil { 767 if err != nil {
787 return c.fail(protocol.ExitFailure, "%v", err) 768 return MRShow{}, err
788 } 769 }
789 var cs []commentOut 770 var cs []commentOut
790 for _, cm := range comments { 771 for _, cm := range comments {
@@ -795,194 +776,214 @@ func runMRShow(c *Ctx, args []string) int {
795 for _, r := range reviews { 776 for _, r := range reviews {
796 rs = append(rs, ReviewOut{r.Reviewer, r.Verdict, r.Stale, counts[r.Reviewer], r.CreatedAt}) 777 rs = append(rs, ReviewOut{r.Reviewer, r.Verdict, r.Stale, counts[r.Reviewer], r.CreatedAt})
797 } 778 }
798 // The commits this MR carries: base..head, the diff's range. 779 return MRShow{mrOut: mrToOut(repo, mr, true), Checks: checks, Combined: combined,
799 var commits []CommitOut 780 UnresolvedThreads: unresolved, Reactions: reactionsOut(rx[0]), Comments: cs, Reviews: rs}, nil
800 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name) 781}
801 base := mr.MergedBase 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 {
802 if base == "" { 797 if base == "" {
803 if b, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, mrHeadRef(mr.Number)); err == nil { 798 return 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 }
819 } 799 }
820 d := MRShow{mrOut: mrToOut(repo, mr, true), Checks: checks, Combined: combined, 800 shas, err := gitutil.RevListRange(dir, base, mrHeadRef(mr.Number))
821 UnresolvedThreads: unresolved, Commits: commits, Reactions: reactionsOut(rx[0]), Comments: cs, Reviews: rs} 801 if err != nil {
822 d.StackedOn, d.Stacked = stackOf(c, repo, mr) 802 return nil
823 if mr.State == "open" || mr.State == "source_gone" { 803 }
824 if targetSHA, err := gitutil.ResolveRef(dir, "refs/heads/"+mr.TargetRef); err == nil { 804 var commits []CommitOut
825 if g, err := MergeGates(c.Store, repo, mr, dir, targetSHA, mr.HeadSHA); err == nil { 805 for _, sha := range shas {
826 d.Gates = &g 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
827 } 810 }
828 } 811 }
812 commits = append(commits, CommitOut{sha, subject})
829 } 813 }
830 var files []gitutil.NumStat 814 return commits
831 if c.Term.Cols > 0 && !c.JSON && base != "" { 815}
832 files, _ = gitutil.DiffNumstat(dir, base, mrHeadRef(mr.Number)) 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"
833 } 822 }
834 return c.emitView(d, func(w io.Writer) { 823 v := c.view(w)
835 state := d.State 824 v.title(fmt.Sprintf("!%d", d.Number), d.Title, state)
836 if d.Draft { 825 v.fields(mrShowFields(c, repo, d)...)
837 state = "draft"
838 }
839 v := c.view(w)
840 v.title(fmt.Sprintf("!%d", d.Number), d.Title, state)
841 826
842 stackedOn, stacked := "", "" 827 v.body(d.Body, d.BodyFormat)
843 if d.StackedOn != nil { 828 v.reactions(d.Reactions)
844 stackedOn = fmt.Sprintf("!%d %s", d.StackedOn.Number, d.StackedOn.Title) 829 writeMRTables(c, w, v, d)
845 } 830
846 for _, k := range d.Stacked { 831 events := false
847 if stacked != "" { 832 for _, cm := range d.Comments {
848 stacked += ", " 833 if cm.Kind != "system" {
849 } 834 continue
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))
915 } 835 }
916 if len(checks) == 1 { 836 if !events {
917 x := checks[0] 837 io.WriteString(w, "\n")
918 dur := "" 838 events = true
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))
923 } 839 }
924 if len(rs) == 1 { 840 v.event(cm.Body, cm.BodyFormat, cm.CreatedAt)
925 kv = append(kv, "review", reviewLine(rs[0])+" at "+c.when(rs[0].CreatedAt)) 841 }
842 for _, cm := range d.Comments {
843 if cm.Kind == "system" {
844 continue
926 } 845 }
927 kv = append(kv, "url", c.siteURL(repo.Path(), "mrs", strconv.FormatInt(d.Number, 10))) 846 v.comment(cm.ID, cm.Author, cm.CreatedAt, cm.Body, cm.BodyFormat)
928 v.fields(kv...) 847 v.reactions(cm.Reactions)
848 }
849}
929 850
930 v.body(d.Body, d.BodyFormat) 851// mrShowFields is every one-row fact as key, value pairs, including the
931 v.reactions(d.Reactions) 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}
932 910
933 if len(commits) > 1 { 911// mrStackLines names the merge request this one is stacked on, and those
934 v.section(fmt.Sprintf("commits (%d)", len(commits))) 912// stacked on it.
935 tb := c.table(w, "SHA", "SUBJECT") 913func mrStackLines(d MRShow) (stackedOn, stacked string) {
936 for _, cm := range commits { 914 if d.StackedOn != nil {
937 tb.row(cRef(fmt.Sprintf("%.10s", cm.SHA)), cFlex(cm.Subject)) 915 stackedOn = fmt.Sprintf("!%d %s", d.StackedOn.Number, d.StackedOn.Title)
938 } 916 }
939 tb.flush() 917 for _, k := range d.Stacked {
918 if stacked != "" {
919 stacked += ", "
940 } 920 }
921 stacked += fmt.Sprintf("!%d %s", k.Number, k.Title)
922 }
923 return stackedOn, stacked
924}
941 925
942 if len(checks) > 1 { 926// mrQueuedLines is who queued the merge, how and when, and what it waits on.
943 v.section(fmt.Sprintf("checks (%d)", len(checks))) 927func mrQueuedLines(c *Ctx, q *QueuedOut) (queued, waiting string) {
944 tb := c.table(w, "CHECK", "STATE", "DURATION", "UPDATED") 928 if q == nil {
945 for _, x := range checks { 929 return "", ""
946 tb.row(cText(x.Context), cState(x.State), cText(x.Duration), cText(c.when(x.UpdatedAt))) 930 }
947 } 931 queued = "by " + q.By
948 tb.flush() 932 if q.Strategy != "" {
949 } 933 queued += " (" + q.Strategy + ")"
934 }
935 return queued + ", " + c.when(q.QueuedAt), q.Reason
936}
950 937
951 if len(rs) > 1 { 938// gatesSummary is "met" or the unmet count, and whether fast-forward is possible.
952 v.section(fmt.Sprintf("reviews (%d)", len(rs))) 939func gatesSummary(g *GatesOut) string {
953 tb := c.table(w, "REVIEWER", "VERDICT", "WHEN") 940 if g == nil {
954 for _, r := range rs { 941 return ""
955 verdict := r.Verdict 942 }
956 if r.Stale { 943 ff := "fast-forward possible"
957 verdict += " (stale)" 944 if !g.FastForward {
958 } 945 ff = "fast-forward not possible"
959 if !r.Counts { 946 }
960 verdict += " (advisory)" 947 if len(g.Unmet) == 0 {
961 } 948 return "met; " + ff
962 tb.row(cText(r.Reviewer), cState(verdict), cText(c.when(r.CreatedAt))) 949 }
963 } 950 return fmt.Sprintf("%d unmet; %s", len(g.Unmet), ff)
964 tb.flush() 951}
965 }
966 952
967 events := false 953// writeMRTables lists commits, checks and reviews when there is more than
968 for _, cm := range cs { 954// one of each; a single one is a field instead.
969 if cm.Kind != "system" { 955func writeMRTables(c *Ctx, w io.Writer, v *view, d MRShow) {
970 continue 956 if len(d.Commits) > 1 {
971 } 957 v.section(fmt.Sprintf("commits (%d)", len(d.Commits)))
972 if !events { 958 tb := c.table(w, "SHA", "SUBJECT")
973 io.WriteString(w, "\n") 959 for _, cm := range d.Commits {
974 events = true 960 tb.row(cRef(fmt.Sprintf("%.10s", cm.SHA)), cFlex(cm.Subject))
975 }
976 v.event(cm.Body, cm.BodyFormat, cm.CreatedAt)
977 } 961 }
978 for _, cm := range cs { 962 tb.flush()
979 if cm.Kind == "system" { 963 }
980 continue 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)"
981 } 982 }
982 v.comment(cm.ID, cm.Author, cm.CreatedAt, cm.Body, cm.BodyFormat) 983 tb.row(cText(r.Reviewer), cState(verdict), cText(c.when(r.CreatedAt)))
983 v.reactions(cm.Reactions)
984 } 984 }
985 }, func() screen { return mrShowScreen(c, repo, d, files) }) 985 tb.flush()
986 }
986} 987}
987 988
988// reviewLine renders one review as fields prose: "reviewer verdict 989// 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 {
1394 return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State) 1395 return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State)
1395 } 1396 }
1396 1397
1397 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name) 1398 p := &mergePlan{repo: repo, mr: mr, strategy: strategy}
1398 targetRef := "refs/heads/" + mr.TargetRef 1399 p.dir = RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
1399 targetSHA, err := gitutil.ResolveRef(dir, targetRef) 1400 p.targetRef = "refs/heads/" + mr.TargetRef
1401 var err error
1402 p.targetSHA, err = gitutil.ResolveRef(p.dir, p.targetRef)
1400 if err != nil { 1403 if err != nil {
1401 return c.fail(protocol.ExitFailure, "target branch %s: %v", mr.TargetRef, err) 1404 return c.fail(protocol.ExitFailure, "target branch %s: %v", mr.TargetRef, err)
1402 } 1405 }
1403 headSHA, err := gitutil.ResolveRef(dir, mrHeadRef(mr.Number)) 1406 p.headSHA, err = gitutil.ResolveRef(p.dir, mrHeadRef(mr.Number))
1404 if err != nil { 1407 if err != nil {
1405 return c.fail(protocol.ExitFailure, "MR head ref: %v", err) 1408 return c.fail(protocol.ExitFailure, "MR head ref: %v", err)
1406 } 1409 }
1407 1410
1408 // Merge gates: draft, checks, approvals, CODEOWNERS, resolved threads, 1411 // Merge gates: draft, checks, approvals, CODEOWNERS, resolved threads,
1409 // all reported at once. 1412 // 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 {
1411 return code 1414 return code
1412 } 1415 }
1413 1416
1414 upToDate, err := gitutil.IsAncestor(dir, headSHA, targetSHA) 1417 upToDate, err := gitutil.IsAncestor(p.dir, p.headSHA, p.targetSHA)
1415 if err != nil { 1418 if err != nil {
1416 return c.fail(protocol.ExitFailure, "%v", err) 1419 return c.fail(protocol.ExitFailure, "%v", err)
1417 } 1420 }
1418 if upToDate { 1421 if upToDate {
1419 // The head is already on the target: merged by hand and pushed, or 1422 return c.recordAlreadyMerged(p)
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 })
1430 } 1423 }
1431 ffPossible, err := gitutil.IsAncestor(dir, targetSHA, headSHA) 1424 p.ffPossible, err = gitutil.IsAncestor(p.dir, p.targetSHA, p.headSHA)
1432 if err != nil { 1425 if err != nil {
1433 return c.fail(protocol.ExitFailure, "%v", err) 1426 return c.fail(protocol.ExitFailure, "%v", err)
1434 } 1427 }
1435 1428
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.
1442 if repo.Settings.RequireSignedCommits { 1429 if repo.Settings.RequireSignedCommits {
1443 if c.Source == queueSource && !ffPossible { 1430 if code := c.requireSignedMerge(p); code >= 0 {
1444 return c.fail(protocol.ExitDenied, 1431 return code
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)
1452 } 1432 }
1453 strategy = "ff" 1433 }
1454 commits, err := gitutil.RevListRange(dir, targetSHA, headSHA) 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)
1455 if err != nil { 1515 if err != nil {
1456 return c.fail(protocol.ExitFailure, "%v", err) 1516 return c.fail(protocol.ExitFailure, "%v", err)
1457 } 1517 }
1458 for _, sha := range commits { 1518 if state != "verified" {
1459 raw, err := gitutil.ReadCommit(dir, sha) 1519 return c.fail(protocol.ExitDenied,
1460 if err != nil { 1520 "%s requires signed commits: %.10s is %s", repo.Path(), sha, state)
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 }
1475 } 1521 }
1476 } 1522 }
1477 if strategy == "" { 1523 return -1
1478 if ffPossible { 1524}
1479 strategy = "ff" 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"
1480 } else { 1551 } else {
1481 strategy = "merge" 1552 p.strategy = "merge"
1482 } 1553 }
1483 } 1554 }
1484 if strategy == "rebase" && ffPossible { 1555 if p.strategy == "rebase" && p.ffPossible {
1485 // Nothing to rewrite: a rebase onto an ancestor is a fast-forward, 1556 p.strategy = "ff"
1486 // and taking it keeps the original commits and their signatures.
1487 strategy = "ff"
1488 } 1557 }
1558}
1489 1559
1490 // Every server-created commit needs the merger's verified identity. 1560// mergerIdentity sets the email every server-created commit is committed
1491 mergerEmail := "" 1561// under: the merger's verified primary one. Returns -1 to proceed.
1492 if strategy != "ff" { 1562func (c *Ctx) mergerIdentity(p *mergePlan) int {
1493 email, err := c.Store.PrimaryVerifiedEmail(c.User.ID) 1563 if p.strategy == "ff" {
1494 if err != nil { 1564 return -1
1495 return c.fail(protocol.ExitFailure, "%v", err) 1565 }
1496 } 1566 email, err := c.Store.PrimaryVerifiedEmail(c.User.ID)
1497 if email == "" { 1567 if err != nil {
1498 return c.fail(protocol.ExitDenied, 1568 return c.fail(protocol.ExitFailure, "%v", err)
1499 "%s merges create commits carrying your identity: verify a primary email first (or use a fast-forward merge)", strategy) 1569 }
1500 } 1570 if email == "" {
1501 mergerEmail = 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)
1502 } 1573 }
1574 p.mergerEmail = email
1575 return -1
1576}
1503 1577
1504 var newSHA string 1578// mergedCommit is the commit the target moves to under the plan's strategy.
1505 switch strategy { 1579// The code is -1 unless the merge is refused.
1580func (c *Ctx) mergedCommit(p *mergePlan) (string, int) {
1581 switch p.strategy {
1506 case "ff": 1582 case "ff":
1507 if !ffPossible { 1583 if !p.ffPossible {
1508 return c.fail(protocol.ExitUsage, 1584 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) 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)
1510 } 1586 }
1511 newSHA = headSHA 1587 return p.headSHA, -1
1512
1513 case "merge": 1588 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)
1515 if err != nil { 1632 if err != nil {
1516 return c.fail(protocol.ExitFailure, "%v", err) 1633 return "", c.fail(protocol.ExitFailure, "%v", err)
1517 } 1634 }
1518 if conflict { 1635 tree = t
1519 return c.fail(protocol.ExitUsage, 1636 } else {
1520 "merge conflicts between %s and the MR head; resolve locally and re-push", mr.TargetRef) 1637 t, code := c.mergedTree(p)
1638 if code >= 0 {
1639 return "", code
1521 } 1640 }
1522 msg := fmt.Sprintf("Merge request !%d: %s\n\nMerged %s into %s", mr.Number, mr.Title, mr.SourceRef, mr.TargetRef) 1641 tree = t
1523 newSHA, err = gitutil.CommitTree(dir, tree, []string{targetSHA, headSHA}, c.User.Username, mergerEmail, msg) 1642 }
1524 if err != nil { 1643 mr := p.mr
1525 return c.fail(protocol.ExitFailure, "%v", err) 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
1526 } 1648 }
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}
1527 1661
1528 case "squash": 1662// rebaseCommits replays the merge request's commits, oldest first, onto the
1529 // One new commit with the merged tree. Authorship credit goes to 1663// target, keeping each one's author.
1530 // the MR author (their verified identity when they have one); the 1664func (c *Ctx) rebaseCommits(p *mergePlan) (string, int) {
1531 // committer is the merger. 1665 commits, err := gitutil.RevListRange(p.dir, p.targetSHA, p.headSHA)
1532 tree := "" 1666 if err != nil {
1533 if ffPossible { 1667 return "", c.fail(protocol.ExitFailure, "%v", err)
1534 t, err := gitutil.ResolveTree(dir, headSHA) 1668 }
1535 if err != nil { 1669 slices.Reverse(commits)
1536 return c.fail(protocol.ExitFailure, "%v", err) 1670 onto := p.targetSHA
1537 } 1671 for _, sha := range commits {
1538 tree = t 1672 next, code := c.replayCommit(p, sha, onto)
1539 } else { 1673 if code >= 0 {
1540 t, conflict, err := gitutil.MergeTree(dir, targetSHA, headSHA) 1674 return "", code
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)
1565 } 1675 }
1676 onto = next
1677 }
1678 return onto, -1
1679}
1566 1680
1567 case "rebase": 1681// replayCommit applies one commit onto `onto` as a new commit with its
1568 commits, err := gitutil.RevListRange(dir, targetSHA, headSHA) 1682// author, message and date, committed by the merger.
1569 if err != nil { 1683func (c *Ctx) replayCommit(p *mergePlan, sha, onto string) (string, int) {
1570 return c.fail(protocol.ExitFailure, "%v", err) 1684 parents, err := gitutil.CommitParents(p.dir, sha)
1571 } 1685 if err != nil {
1572 // Oldest first. 1686 return "", c.fail(protocol.ExitFailure, "%v", err)
1573 for i, j := 0, len(commits)-1; i < j; i, j = i+1, j-1 { 1687 }
1574 commits[i], commits[j] = commits[j], commits[i] 1688 if len(parents) > 1 {
1575 } 1689 return "", c.fail(protocol.ExitUsage,
1576 onto := targetSHA 1690 "the MR contains merge commit %.10s; a rebase merge needs linear history — choose the merge or squash strategy", sha)
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
1613 } 1691 }
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}
1614 1719
1615 // A stacked merge request's diff is against this branch. After a 1720// stackForMerge is the merge requests stacked on this one. A stacked merge
1616 // fast-forward or merge commit the same commits are on the target and 1721// request's diff is against this branch. After a fast-forward or merge
1617 // its diff is unchanged there; after a squash or rebase they are not, 1722// commit the same commits are on the target and its diff is unchanged
1618 // and the stack would carry this merge request's changes a second 1723// there; after a squash or rebase they are not, and the stack would carry
1619 // time. Refuse rather than leave the stack wrong. 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
1620 var stack []store.MR 1728 var stack []store.MR
1621 if mr.SourceRepoID == repo.ID { 1729 if mr.SourceRepoID == p.repo.ID {
1622 stack, _ = c.Store.OpenMRsByTarget(repo.ID, mr.SourceRef) 1730 stack, _ = c.Store.OpenMRsByTarget(p.repo.ID, mr.SourceRef)
1623 } 1731 }
1624 if len(stack) > 0 && (strategy == "squash" || strategy == "rebase") { 1732 if len(stack) > 0 && (p.strategy == "squash" || p.strategy == "rebase") {
1625 var nums []string 1733 var nums []string
1626 for _, k := range stack { 1734 for _, k := range stack {
1627 nums = append(nums, fmt.Sprintf("!%d", k.Number)) 1735 nums = append(nums, fmt.Sprintf("!%d", k.Number))
1628 } 1736 }
1629 return c.fail(protocol.ExitUsage, 1737 return nil, c.fail(protocol.ExitUsage,
1630 "%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", 1738 "%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)
1632 } 1740 }
1741 return stack, -1
1742}
1633 1743
1634 // CAS so a concurrent push between our read and this write fails the 1744// retargetStack moves the stack up: whatever targeted this branch now
1635 // merge instead of silently discarding the push. 1745// targets what it merged into, reviews intact, since that diff is the one
1636 if err := gitutil.UpdateRefCAS(dir, targetRef, newSHA, targetSHA); err != nil { 1746// they were of.
1637 return c.fail(protocol.ExitFailure, "target branch moved during merge; retry: %v", err) 1747func (c *Ctx) retargetStack(p *mergePlan, stack []store.MR) {
1638 } 1748 repo, mr := p.repo, p.mr
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.
1647 for _, k := range stack { 1749 for _, k := range stack {
1648 if err := c.Store.RetargetKeepingReviews(k.ID, mr.TargetRef); err != nil { 1750 if err := c.Store.RetargetKeepingReviews(k.ID, mr.TargetRef); err != nil {
1649 continue 1751 continue
@@ -1656,14 +1758,19 @@ func mergeMR(c *Ctx, repo store.Repo, mr store.MR, strategy string) int {
1656 path: fmt.Sprintf("%s/mrs/%d", repo.Path(), k.Number)}) 1758 path: fmt.Sprintf("%s/mrs/%d", repo.Path(), k.Number)})
1657 } 1759 }
1658 } 1760 }
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
1659 // Merges bypass receive-pack, so the commit-message issue actions 1766 // Merges bypass receive-pack, so the commit-message issue actions
1660 // (closes #N, references) run here for the newly landed commits. The 1767 // (closes #N, references) run here for the newly landed commits. The
1661 // description is scanned after them, so a commit wins the attribution 1768 // description is scanned after them, so a commit wins the attribution
1662 // when both name the same issue. 1769 // when both name the same issue.
1663 if mr.TargetRef == repo.DefaultBranch { 1770 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)
1665 ProcessMRDescription(c.Store, repo, mr, c.User.ID, c.Scope) 1772 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)
1667 c.Store.RequestSymbolIndex(repo.ID, false) 1774 c.Store.RequestSymbolIndex(repo.ID, false)
1668 } 1775 }
1669 // A merge moves the ref directly, so it never reaches post-receive and 1776 // 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 {
1671 // subscribe to, and the branch's CI jobs, happen here instead. 1778 // subscribe to, and the branch's CI jobs, happen here instead.
1672 c.Store.RecordEvent(repo.ID, c.User.ID, "push", fmt.Sprintf( 1779 c.Store.RecordEvent(repo.ID, c.User.ID, "push", fmt.Sprintf(
1673 `{"ref":%q,"old":%q,"new":%q,"forced":false,"deleted":false}`, 1780 `{"ref":%q,"old":%q,"new":%q,"forced":false,"deleted":false}`,
1674 targetRef, targetSHA, newSHA)) 1781 p.targetRef, p.targetSHA, newSHA))
1675 QueueBranchBuilds(c.Store, c.Cfg.Server.Root, c.Cfg.Server.SiteURL, 1782 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())
1677 c.Store.MarkMirrorsDirty(repo.ID, "push") 1784 c.Store.MarkMirrorsDirty(repo.ID, "push")
1678 if parts, err := c.Store.MRParticipants(mr.ID); err == nil { 1785 if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
1679 notify(c, parts, notice{repo: repo, kind: "mr", number: mr.Number, 1786 notify(c, parts, notice{repo: repo, kind: "mr", number: mr.Number,
1680 subject: mrSubject(repo, mr.Number, mr.Title), 1787 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),
1682 path: fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)}) 1789 path: fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
1683 } 1790 }
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 })
1687} 1791}
1688 1792
1689// reviewGates refuses a merge whose gates are not all met, naming every 1793// 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
1746 g := GatesOut{Draft: mr.Draft, ApprovalsRequired: set.RequireApprovals, 1850 g := GatesOut{Draft: mr.Draft, ApprovalsRequired: set.RequireApprovals,
1747 CodeownersRequired: set.RequireCodeowners, ResolvedRequired: set.RequireResolved, 1851 CodeownersRequired: set.RequireCodeowners, ResolvedRequired: set.RequireResolved,
1748 ChecksRequired: set.RequireChecks} 1852 ChecksRequired: set.RequireChecks}
1853 in := gateInputs{st: st, repo: repo, mr: mr, dir: dir, targetSHA: targetSHA, headSHA: headSHA}
1749 // A draft is open but not asking. This gate is unconditional — no 1854 // A draft is open but not asking. This gate is unconditional — no
1750 // setting turns it off — because the author said so themselves. 1855 // setting turns it off — because the author said so themselves.
1751 if mr.Draft { 1856 if mr.Draft {
1752 g.Unmet = append(g.Unmet, fmt.Sprintf("!%d is a draft; `gitbay mr ready %s %d` first", mr.Number, repo.Path(), mr.Number)) 1857 g.Unmet = append(g.Unmet, fmt.Sprintf("!%d is a draft; `gitbay mr ready %s %d` first", mr.Number, repo.Path(), mr.Number))
1753 } 1858 }
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 }
1754 1870
1755 // Checks: with require_checks, every status the head carries must be 1871 n, err := st.UnresolvedThreadCount(mr.ID)
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)
1761 if err != nil { 1872 if err != nil {
1762 return g, err 1873 return g, err
1763 } 1874 }
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 }
1764 g.Checks = store.CombinedStatus(statuses) 1906 g.Checks = store.CombinedStatus(statuses)
1765 if set.RequireChecks { 1907 set := in.repo.Settings
1766 reported := map[string]bool{} 1908 if !set.RequireChecks {
1767 for _, s := range statuses { 1909 return nil
1768 reported[s.Context] = true 1910 }
1769 } 1911 reported := map[string]bool{}
1770 for _, want := range set.RequiredContexts { 1912 for _, s := range statuses {
1771 if !reported[want] { 1913 reported[s.Context] = true
1772 g.ChecksMissing = append(g.ChecksMissing, want) 1914 }
1773 } 1915 for _, want := range set.RequiredContexts {
1916 if !reported[want] {
1917 g.ChecksMissing = append(g.ChecksMissing, want)
1774 } 1918 }
1775 if len(g.ChecksMissing) > 0 && (g.Checks == "" || g.Checks == "success") { 1919 }
1776 g.Checks = "pending" 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))
1777 } 1928 }
1778 switch g.Checks { 1929 default:
1779 case "success": 1930 var bad []string
1780 case "": 1931 for _, st := range statuses {
1781 if checksExpected(st, repo.ID, dir, headSHA) { 1932 if st.State != "success" {
1782 g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires green checks and none were reported on %.10s", repo.Path(), headSHA)) 1933 bad = append(bad, st.Context+"="+st.State)
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 }
1790 } 1934 }
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, ", ")))
1795 } 1935 }
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, ", ")))
1796 } 1940 }
1941 return nil
1942}
1797 1943
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)
1799 if err != nil { 1953 if err != nil {
1800 return g, err 1954 return err
1801 } 1955 }
1802 // Latest fresh review per reviewer decides their stance — but only 1956 counts := ReviewersWhoCount(in.st, in.repo, reviews)
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)
1809 latest := map[string]string{} 1957 latest := map[string]string{}
1810 for _, r := range reviews { 1958 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] {
1812 continue 1960 continue
1813 } 1961 }
1814 latest[r.Reviewer] = r.Verdict 1962 latest[r.Reviewer] = r.Verdict
@@ -1823,91 +1971,79 @@ func MergeGates(st *store.Store, repo store.Repo, mr store.MR, dir, targetSHA, h
1823 } 1971 }
1824 slices.Sort(g.Approvals) 1972 slices.Sort(g.Approvals)
1825 slices.Sort(g.ChangesRequested) 1973 slices.Sort(g.ChangesRequested)
1826 if set.RequireApprovals > 0 { 1974 required := in.repo.Settings.RequireApprovals
1975 if required > 0 {
1827 if len(g.ChangesRequested) > 0 { 1976 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))
1829 } 1978 }
1830 if len(g.Approvals) < set.RequireApprovals { 1979 if len(g.Approvals) < required {
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))) 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)))
1832 } 1981 }
1833 } 1982 }
1983 return nil
1984}
1834 1985
1835 // CODEOWNERS: every owned changed file needs an approval from one of 1986// codeownersGate requires every owned changed file to have an approval from
1836 // its owners. require_codeowners is the opt-in — a repository can 1987// one of its owners. require_codeowners is the opt-in — a repository can
1837 // carry the file as documentation of who to ask without it gating 1988// carry the file as documentation of who to ask without it gating merges —
1838 // merges — and it does not wait on require_approvals (#99). 1989// and it does not wait on require_approvals (#99).
1839 if set.RequireCodeowners { 1990func (in gateInputs) codeownersGate(g *GatesOut) error {
1840 content, err := gitutil.ReadBlob(dir, "refs/heads/"+mr.TargetRef, "CODEOWNERS", 1<<20) 1991 target := "refs/heads/" + in.mr.TargetRef
1841 if err != nil { 1992 content, err := gitutil.ReadBlob(in.dir, target, "CODEOWNERS", 1<<20)
1842 content, err = gitutil.ReadBlob(dir, "refs/heads/"+mr.TargetRef, ".gitbay/CODEOWNERS", 1<<20) 1993 if err != nil {
1843 } 1994 content, err = gitutil.ReadBlob(in.dir, target, ".gitbay/CODEOWNERS", 1<<20)
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 }
1896 } 1995 }
1897 1996 if err != nil || len(content) == 0 {
1898 n, err := st.UnresolvedThreadCount(mr.ID) 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)
1899 if err != nil { 2001 if err != nil {
1900 return g, err 2002 return err
1901 } 2003 }
1902 g.OpenThreads = n 2004 files, err := gitutil.DiffFiles(in.dir, base, in.headSHA)
1903 if set.RequireResolved && n > 0 { 2005 if err != nil {
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)) 2006 return err
2007 }
2008 keys, missing := unapprovedOwners(policy.ParseCodeowners(string(content)), files, g.Approvals)
2009 if len(missing) == 0 {
2010 return nil
1905 } 2011 }
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}
1906 2024
1907 if ff, err := gitutil.IsAncestor(dir, targetSHA, headSHA); err == nil { 2025// unapprovedOwners groups the owned files no owner has approved by their
1908 g.FastForward = ff 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
1909 } 2031 }
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
1911} 2047}
1912 2048
1913func runMRDraft(c *Ctx, args []string) int { return setMRDraft(c, args, true) } 2049func runMRDraft(c *Ctx, args []string) int { return setMRDraft(c, args, true) }