Federated via graft
6.3 kB
189 lines
1package sync
2
3import (
4 "bytes"
5 "fmt"
6 "os"
7 "os/exec"
8 "regexp"
9 "strings"
10
11 "graft/internal/forgejo"
12 "graft/internal/radicle"
13 "graft/internal/state"
14)
15
16// PatchSyncer mirrors Forgejo pull requests and Radicle patches. It reuses
17// the same working clone GitSyncer maintains, since a patch/PR can only be
18// opened once its head commit is reachable on the destination side.
19type PatchSyncer struct {
20 RepoPair string
21 WorkDir string
22 RadHome string
23 DefaultBranch string
24 Forgejo *forgejo.Client
25 Radicle *radicle.Client
26 State *state.Store
27 ForgejoWebURL string // https://host/owner/repo, for links in the UI
28 RadicleWebURL string // https://explorer/nodes/host/rid, for links in the UI
29 Series string // dashboard row this pair's activity groups under
30 SeriesURL string // where clicking that row's name goes
31 Bluesky *BlueskyPoster // nil unless this pair has bluesky configured
32}
33
34func (s *PatchSyncer) git(args ...string) (string, error) {
35 cmd := exec.Command("git", args...)
36 cmd.Dir = s.WorkDir
37 // Must start from the inherited environment, not a bare slice: git
38 // needs PATH to resolve the git-remote-rad helper for rad:// remotes.
39 cmd.Env = append(os.Environ(), "RAD_HOME="+s.RadHome)
40 var out bytes.Buffer
41 cmd.Stdout = &out
42 cmd.Stderr = &out
43 if err := cmd.Run(); err != nil {
44 return out.String(), fmt.Errorf("git %v: %w: %s", args, err, out.String())
45 }
46 return out.String(), nil
47}
48
49func (s *PatchSyncer) Sync() error {
50 prs, err := s.Forgejo.ListPullRequests()
51 if err != nil {
52 return fmt.Errorf("list forgejo pull requests: %w", err)
53 }
54 patches, err := s.Radicle.ListPatches()
55 if err != nil {
56 return fmt.Errorf("list radicle patches: %w", err)
57 }
58
59 for _, pr := range prs {
60 if err := s.mirrorForgejoToRadicle(pr); err != nil {
61 return fmt.Errorf("mirror forgejo PR #%d: %w", pr.Index, err)
62 }
63 }
64 for _, p := range patches {
65 if err := s.mirrorRadicleToForgejo(p); err != nil {
66 return fmt.Errorf("mirror radicle patch %s: %w", p.ID, err)
67 }
68 }
69 return nil
70}
71
72var patchOpenedRe = regexp.MustCompile(`Patch ([0-9a-f]{40}) opened`)
73
74func (s *PatchSyncer) mirrorForgejoToRadicle(pr forgejo.PullRequest) error {
75 existing, err := s.State.FindByForgejoID(s.RepoPair, "patch", pr.Index)
76 if err != nil {
77 return err
78 }
79 if existing != nil {
80 return nil
81 }
82
83 // Bring the PR's head branch content into the local clone, then open a
84 // patch from it via the pseudo-ref, exactly as verified interactively:
85 // `git push rad HEAD:refs/patches`.
86 if _, err := s.git("fetch", "-q", "forgejo", pr.Head.Ref); err != nil {
87 return fmt.Errorf("fetch PR head: %w", err)
88 }
89 if _, err := s.git("checkout", "-q", "-B", localPRBranch(pr.Index), "FETCH_HEAD"); err != nil {
90 return fmt.Errorf("checkout PR head: %w", err)
91 }
92 // git push -o values cannot contain newlines, unlike issue/PR bodies.
93 message := pr.Title + " (mirrored automatically, do not edit here)"
94 out, err := s.git("push", "rad", "-o", "patch.message="+message, "HEAD:refs/patches")
95 // The working clone's mirroring never touches local branch refs (only
96 // FETCH_HEAD and the remotes), so there may be no local default-branch
97 // ref to switch back to yet: fetch and (re)create it rather than assume
98 // it exists.
99 if _, errFetch := s.git("fetch", "-q", "forgejo", s.DefaultBranch); errFetch != nil {
100 return fmt.Errorf("fetch %s to restore: %w", s.DefaultBranch, errFetch)
101 }
102 if _, errCheckout := s.git("checkout", "-q", "-B", s.DefaultBranch, "FETCH_HEAD"); errCheckout != nil {
103 return fmt.Errorf("checkout back to %s: %w", s.DefaultBranch, errCheckout)
104 }
105 if err != nil {
106 return fmt.Errorf("open radicle patch: %w", err)
107 }
108
109 m := patchOpenedRe.FindStringSubmatch(out)
110 if m == nil {
111 return fmt.Errorf("could not parse patch id from: %q", out)
112 }
113
114 if err := s.State.Upsert(s.RepoPair, state.ItemMapping{
115 Kind: "patch",
116 ForgejoID: pr.Index,
117 RadicleID: m[1],
118 ContentHash: hashText(pr.Title, pr.Body),
119 }); err != nil {
120 return err
121 }
122 s.State.LogActivity(state.Activity{
123 RepoPair: s.RepoPair, Series: s.Series, SeriesURL: s.SeriesURL,
124 Kind: "patch", Direction: state.ForgejoToRadicle, Summary: pr.Title,
125 URL: s.RadicleWebURL + "/patches/" + m[1],
126 ForgejoID: pr.Index, RadicleID: m[1],
127 })
128 s.Bluesky.Post(s.Series + ": patch opened — " + pr.Title + "\n" + s.RadicleWebURL + "/patches/" + m[1])
129 return nil
130}
131
132func (s *PatchSyncer) mirrorRadicleToForgejo(p radicle.Patch) error {
133 existing, err := s.State.FindByRadicleID(s.RepoPair, "patch", p.ID)
134 if err != nil {
135 return err
136 }
137 if existing != nil {
138 return nil
139 }
140 if len(p.Revisions) == 0 {
141 return fmt.Errorf("patch has no revisions")
142 }
143 latest := p.Revisions[len(p.Revisions)-1]
144
145 branch := localPatchBranch(p.ID)
146 if _, err := s.git("fetch", "-q", "rad", latest.OID); err != nil {
147 return fmt.Errorf("fetch patch revision: %w", err)
148 }
149 if _, err := s.git("branch", "-q", "-f", branch, "FETCH_HEAD"); err != nil {
150 return fmt.Errorf("branch patch revision: %w", err)
151 }
152 if _, err := s.git("push", "-q", "forgejo", branch+":refs/heads/"+branch); err != nil {
153 return fmt.Errorf("push branch to forgejo: %w", err)
154 }
155
156 pr, err := s.Forgejo.CreatePullRequest(p.Title, latest.Description+mirrorNotice, branch, s.DefaultBranch)
157 if err != nil {
158 return fmt.Errorf("create forgejo pull request: %w", err)
159 }
160
161 if err := s.State.Upsert(s.RepoPair, state.ItemMapping{
162 Kind: "patch",
163 ForgejoID: pr.Index,
164 RadicleID: p.ID,
165 ContentHash: hashText(p.Title, latest.Description),
166 }); err != nil {
167 return err
168 }
169 s.State.LogActivity(state.Activity{
170 RepoPair: s.RepoPair, Series: s.Series, SeriesURL: s.SeriesURL,
171 Kind: "patch", Direction: state.RadicleToForgejo, Summary: p.Title,
172 URL: fmt.Sprintf("%s/pulls/%d", s.ForgejoWebURL, pr.Index),
173 ForgejoID: pr.Index, RadicleID: p.ID,
174 })
175 s.Bluesky.Post(fmt.Sprintf("%s: patch opened — %s\n%s/pulls/%d", s.Series, p.Title, s.ForgejoWebURL, pr.Index))
176 return nil
177}
178
179func localPRBranch(index int64) string {
180 return fmt.Sprintf("sync/forgejo-pr-%d", index)
181}
182
183func localPatchBranch(radicleID string) string {
184 short := radicleID
185 if len(short) > 12 {
186 short = short[:12]
187 }
188 return "sync/radicle-patch-" + strings.ToLower(short)
189}