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