gunk-dev/the-valley

projectsync.go

sourcec14b0e68e9c3main's published tip history
5.3 KiB
1// Package projectsync keeps registered project clones current with their
2// upstreams. It is deliberately conservative: it fetches every project, and
3// only performs a fast-forward merge when the working tree is clean and the
4// current branch has a tracking upstream. It never resets, force-updates, or
5// switches branches. Any surprising state (dirty tree, detached HEAD, diverged
6// branch, no upstream) is reported as a "skipped" result and left untouched.
7package projectsync
8
9import (
10 "context"
11 "fmt"
12 "path/filepath"
13 "sort"
14 "sync"
15 "time"
16
17 "the-valley/flow/internal/git"
18 "the-valley/flow/internal/project"
19)
20
21// PerRepoTimeout bounds the total time spent syncing a single repo.
22const PerRepoTimeout = 15 * time.Second
23
24// MaxConcurrency caps how many project syncs run at once. Each sync spawns
25// several `git` subprocesses, so unbounded fan-out on a registry with many
26// projects can exhaust file descriptors or thrash the disk.
27const MaxConcurrency = 8
28
29// Status is the outcome of syncing a single project.
30type Status string
31
32const (
33 // StatusUpToDate means fetch ran and the branch was already current.
34 StatusUpToDate Status = "up-to-date"
35 // StatusPulled means a fast-forward merge advanced the working branch.
36 StatusPulled Status = "pulled"
37 // StatusFetched means fetch ran but no ff was attempted.
38 StatusFetched Status = "fetched-only"
39 // StatusSkipped means the repo was left untouched (dirty, diverged,
40 // detached, or no upstream). Detail explains why.
41 StatusSkipped Status = "skipped"
42 // StatusError means fetch or a git query failed. Detail contains the error.
43 StatusError Status = "error"
44)
45
46// SyncResult describes the outcome of syncing one project.
47type SyncResult struct {
48 Name string
49 Path string
50 Branch string
51 Status Status
52 // Detail is a short human-readable explanation. For skipped results this
53 // is the reason (e.g. "dirty tree"); for errors it's the error message;
54 // for pulled results it notes how many commits were applied.
55 Detail string
56}
57
58// Sync fetches and fast-forwards every project in reg concurrently. Returns
59// results sorted by project name. Per-project failures are reported in the
60// results, never as a returned error.
61//
62// excludePaths lists absolute paths the caller is already operating on in the
63// foreground; matching projects are skipped to avoid racing with concurrent
64// git operations (e.g., FETCH_HEAD.lock contention).
65func Sync(ctx context.Context, reg *project.Registry, gc git.Client, excludePaths ...string) []SyncResult {
66 if reg == nil {
67 return nil
68 }
69 projects := reg.List()
70 if len(projects) == 0 {
71 return nil
72 }
73
74 excluded := make(map[string]struct{}, len(excludePaths))
75 for _, p := range excludePaths {
76 if p == "" {
77 continue
78 }
79 if abs, err := filepath.Abs(p); err == nil {
80 excluded[abs] = struct{}{}
81 } else {
82 excluded[p] = struct{}{}
83 }
84 }
85
86 resCh := make(chan SyncResult, len(projects))
87 sem := make(chan struct{}, MaxConcurrency)
88 var wg sync.WaitGroup
89 for name, path := range projects {
90 if isExcluded(path, excluded) {
91 continue
92 }
93 wg.Add(1)
94 go func(name, path string) {
95 defer wg.Done()
96 select {
97 case sem <- struct{}{}:
98 case <-ctx.Done():
99 return
100 }
101 defer func() { <-sem }()
102 resCh <- syncOne(ctx, gc, name, path)
103 }(name, path)
104 }
105 wg.Wait()
106 close(resCh)
107
108 results := make([]SyncResult, 0, len(projects))
109 for r := range resCh {
110 results = append(results, r)
111 }
112 sort.Slice(results, func(i, j int) bool { return results[i].Name < results[j].Name })
113 return results
114}
115
116// isExcluded reports whether path resolves to the same absolute path as any
117// entry in excluded.
118func isExcluded(path string, excluded map[string]struct{}) bool {
119 if len(excluded) == 0 {
120 return false
121 }
122 abs, err := filepath.Abs(path)
123 if err != nil {
124 abs = path
125 }
126 _, ok := excluded[abs]
127 return ok
128}
129
130func syncOne(ctx context.Context, gc git.Client, name, path string) SyncResult {
131 r := SyncResult{Name: name, Path: path}
132
133 ctx, cancel := context.WithTimeout(ctx, PerRepoTimeout)
134 defer cancel()
135
136 // Capture the branch for reporting even if later steps fail/skip.
137 branch, _ := gc.CurrentBranch(ctx, path)
138 r.Branch = branch
139
140 if err := gc.FetchAll(ctx, path); err != nil {
141 r.Status = StatusError
142 r.Detail = fmt.Sprintf("fetch failed: %v", err)
143 return r
144 }
145
146 if branch == "" {
147 r.Status = StatusSkipped
148 r.Detail = "detached HEAD"
149 return r
150 }
151
152 clean, err := gc.IsClean(ctx, path)
153 if err != nil {
154 r.Status = StatusError
155 r.Detail = fmt.Sprintf("status check failed: %v", err)
156 return r
157 }
158 if !clean {
159 r.Status = StatusSkipped
160 r.Detail = "dirty tree"
161 return r
162 }
163
164 hasUp, err := gc.HasUpstream(ctx, path)
165 if err != nil {
166 r.Status = StatusError
167 r.Detail = fmt.Sprintf("upstream check failed: %v", err)
168 return r
169 }
170 if !hasUp {
171 r.Status = StatusSkipped
172 r.Detail = "no upstream"
173 return r
174 }
175
176 behind, err := gc.CommitsBehindUpstream(ctx, path)
177 if err != nil {
178 r.Status = StatusError
179 r.Detail = fmt.Sprintf("rev-list failed: %v", err)
180 return r
181 }
182 if behind == 0 {
183 r.Status = StatusUpToDate
184 return r
185 }
186
187 if err := gc.MergeFastForward(ctx, path); err != nil {
188 // ff failed — most likely diverged. Leave the tree alone.
189 r.Status = StatusSkipped
190 r.Detail = fmt.Sprintf("cannot fast-forward: %v", err)
191 return r
192 }
193
194 r.Status = StatusPulled
195 if behind == 1 {
196 r.Detail = "1 commit"
197 } else {
198 r.Detail = fmt.Sprintf("%d commits", behind)
199 }
200 return r
201}