Federated via graft
5.5 kB
174 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}
30
31func (s *PatchSyncer) git(args ...string) (string, error) {
32 cmd := exec.Command("git", args...)
33 cmd.Dir = s.WorkDir
34 // Must start from the inherited environment, not a bare slice: git
35 // needs PATH to resolve the git-remote-rad helper for rad:// remotes.
36 cmd.Env = append(os.Environ(), "RAD_HOME="+s.RadHome)
37 var out bytes.Buffer
38 cmd.Stdout = &out
39 cmd.Stderr = &out
40 if err := cmd.Run(); err != nil {
41 return out.String(), fmt.Errorf("git %v: %w: %s", args, err, out.String())
42 }
43 return out.String(), nil
44}
45
46func (s *PatchSyncer) Sync() error {
47 prs, err := s.Forgejo.ListPullRequests()
48 if err != nil {
49 return fmt.Errorf("list forgejo pull requests: %w", err)
50 }
51 patches, err := s.Radicle.ListPatches()
52 if err != nil {
53 return fmt.Errorf("list radicle patches: %w", err)
54 }
55
56 for _, pr := range prs {
57 if err := s.mirrorForgejoToRadicle(pr); err != nil {
58 return fmt.Errorf("mirror forgejo PR #%d: %w", pr.Index, err)
59 }
60 }
61 for _, p := range patches {
62 if err := s.mirrorRadicleToForgejo(p); err != nil {
63 return fmt.Errorf("mirror radicle patch %s: %w", p.ID, err)
64 }
65 }
66 return nil
67}
68
69var patchOpenedRe = regexp.MustCompile(`Patch ([0-9a-f]{40}) opened`)
70
71func (s *PatchSyncer) mirrorForgejoToRadicle(pr forgejo.PullRequest) error {
72 existing, err := s.State.FindByForgejoID(s.RepoPair, "patch", pr.Index)
73 if err != nil {
74 return err
75 }
76 if existing != nil {
77 return nil
78 }
79
80 // Bring the PR's head branch content into the local clone, then open a
81 // patch from it via the pseudo-ref, exactly as verified interactively:
82 // `git push rad HEAD:refs/patches`.
83 if _, err := s.git("fetch", "-q", "forgejo", pr.Head.Ref); err != nil {
84 return fmt.Errorf("fetch PR head: %w", err)
85 }
86 if _, err := s.git("checkout", "-q", "-B", localPRBranch(pr.Index), "FETCH_HEAD"); err != nil {
87 return fmt.Errorf("checkout PR head: %w", err)
88 }
89 // git push -o values cannot contain newlines, unlike issue/PR bodies.
90 message := pr.Title + " (mirrored automatically, do not edit here)"
91 out, err := s.git("push", "rad", "-o", "patch.message="+message, "HEAD:refs/patches")
92 // The working clone's mirroring never touches local branch refs (only
93 // FETCH_HEAD and the remotes), so there may be no local default-branch
94 // ref to switch back to yet: fetch and (re)create it rather than assume
95 // it exists.
96 if _, errFetch := s.git("fetch", "-q", "forgejo", s.DefaultBranch); errFetch != nil {
97 return fmt.Errorf("fetch %s to restore: %w", s.DefaultBranch, errFetch)
98 }
99 if _, errCheckout := s.git("checkout", "-q", "-B", s.DefaultBranch, "FETCH_HEAD"); errCheckout != nil {
100 return fmt.Errorf("checkout back to %s: %w", s.DefaultBranch, errCheckout)
101 }
102 if err != nil {
103 return fmt.Errorf("open radicle patch: %w", err)
104 }
105
106 m := patchOpenedRe.FindStringSubmatch(out)
107 if m == nil {
108 return fmt.Errorf("could not parse patch id from: %q", out)
109 }
110
111 if err := s.State.Upsert(s.RepoPair, state.ItemMapping{
112 Kind: "patch",
113 ForgejoID: pr.Index,
114 RadicleID: m[1],
115 ContentHash: hashText(pr.Title, pr.Body),
116 }); err != nil {
117 return err
118 }
119 s.State.LogActivity(s.RepoPair, "patch", state.ForgejoToRadicle, pr.Title, s.RadicleWebURL+"/patches/"+m[1])
120 return nil
121}
122
123func (s *PatchSyncer) mirrorRadicleToForgejo(p radicle.Patch) error {
124 existing, err := s.State.FindByRadicleID(s.RepoPair, "patch", p.ID)
125 if err != nil {
126 return err
127 }
128 if existing != nil {
129 return nil
130 }
131 if len(p.Revisions) == 0 {
132 return fmt.Errorf("patch has no revisions")
133 }
134 latest := p.Revisions[len(p.Revisions)-1]
135
136 branch := localPatchBranch(p.ID)
137 if _, err := s.git("fetch", "-q", "rad", latest.OID); err != nil {
138 return fmt.Errorf("fetch patch revision: %w", err)
139 }
140 if _, err := s.git("branch", "-q", "-f", branch, "FETCH_HEAD"); err != nil {
141 return fmt.Errorf("branch patch revision: %w", err)
142 }
143 if _, err := s.git("push", "-q", "forgejo", branch+":refs/heads/"+branch); err != nil {
144 return fmt.Errorf("push branch to forgejo: %w", err)
145 }
146
147 pr, err := s.Forgejo.CreatePullRequest(p.Title, latest.Description+mirrorNotice, branch, s.DefaultBranch)
148 if err != nil {
149 return fmt.Errorf("create forgejo pull request: %w", err)
150 }
151
152 if err := s.State.Upsert(s.RepoPair, state.ItemMapping{
153 Kind: "patch",
154 ForgejoID: pr.Index,
155 RadicleID: p.ID,
156 ContentHash: hashText(p.Title, latest.Description),
157 }); err != nil {
158 return err
159 }
160 s.State.LogActivity(s.RepoPair, "patch", state.RadicleToForgejo, p.Title, fmt.Sprintf("%s/pulls/%d", s.ForgejoWebURL, pr.Index))
161 return nil
162}
163
164func localPRBranch(index int64) string {
165 return fmt.Sprintf("sync/forgejo-pr-%d", index)
166}
167
168func localPatchBranch(radicleID string) string {
169 short := radicleID
170 if len(short) > 12 {
171 short = short[:12]
172 }
173 return "sync/radicle-patch-" + strings.ToLower(short)
174}