oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package checks
2
3import (
4 "bytes"
5 "encoding/json"
6 "errors"
7 "go/version"
8 "io/fs"
9 "os"
10 "path"
11 "path/filepath"
12 "regexp"
13 "slices"
14 "strings"
15 "sync"
16)
17
18// Run is a command's exit code and output. Evidence is what was read
19// from the whole output as it was produced (the Output kept may be only
20// its tail); without it nothing is concluded from the output.
21type Run struct {
22 Code int
23 Output string
24 Evidence *Evidence
25}
26
27// Go's progress lines there are neither evidence nor a disqualification.
28var neutralLine = regexp.MustCompile(`^go: (?:no module dependencies to download|downloading \S+ \S+)$`)
29var offlineRefusal = regexp.MustCompile(`^go: (?:download go1\.[0-9a-z.]+ for [a-z0-9]+/[a-z0-9]+: )?(?:[^\s@:]+@[^\s@:]+: module lookup disabled by GOPROXY=off|golang\.org/toolchain@v0\.0\.1-go1\.[0-9a-z.]+-[a-z0-9]+: verifying module: checksum database disabled by GOSUMDB=off)$`)
30
31// A failure of the gate's own, beyond dependencies it could not fetch: a
32// failing test, a panic, or a compiler or vet diagnostic other than Go
33// failing to fetch a module (offline, or into the read-only cache, which
34// is how a build in the check profile reports a module the cache lacks).
35// These lines only decide what does not count against the stage's
36// evidence; they never establish it.
37var independentFailure = regexp.MustCompile(`(?m)^(?:--- FAIL: |panic: |\S+\.go:[0-9]+(?::[0-9]+)?: )`)
38var offlineDiagnostic = regexp.MustCompile(`^\S+\.go:[0-9]+(?::[0-9]+)?: (?:module lookup disabled by GOPROXY=off|(?:mkdir|open) /opt/go-mod/cache/download/\S+: read-only file system)$`)
39
40// NeedsNetwork reports whether a failed gate could neither pass nor fail
41// honestly offline. Only Equipo's own dependency stage can show it: the
42// stage failed, its whole output was read, and every line is Go refusing
43// an offline download. The gate's output is the candidate's, so it can
44// only keep a failure a failure: read whole, it must show no failing
45// test (plain or go test -json), panic, build failure or diagnostic
46// other than Go failing to fetch a module. Evidence that is missing or
47// incomplete keeps it a failure.
48func NeedsNetwork(stage, gate Run) bool {
49 s, g := stage.Evidence, gate.Evidence
50 if stage.Code == 0 || gate.Code == 0 || s == nil || g == nil {
51 return false
52 }
53 s.mu.Lock()
54 staged := s.complete() && s.refusals > 0 && s.others == 0
55 s.mu.Unlock()
56 g.mu.Lock()
57 defer g.mu.Unlock()
58 return staged && g.complete() && !g.failure
59}
60
61// maxEvidenceLine bounds one line; a longer one makes the evidence
62// incomplete rather than unread.
63const maxEvidenceLine = 64 << 10
64
65// Evidence classifies every line of a command's output as it is
66// produced, before any tail is kept. It is complete only when every
67// stream it was given was closed whole.
68type Evidence struct {
69 mu sync.Mutex
70 open int
71 broken, failure bool
72 refusals, others int
73}
74
75// EvidenceStream is one output stream's writer. Close when the stream
76// ended whole; Abort when it was cut short or could not be read.
77type EvidenceStream struct {
78 e *Evidence
79 partial []byte
80 long bool
81 done bool
82}
83
84// NewEvidence returns evidence fed by n streams.
85func NewEvidence(n int) (*Evidence, []*EvidenceStream) {
86 e := &Evidence{open: n}
87 streams := make([]*EvidenceStream, n)
88 for i := range streams {
89 streams[i] = &EvidenceStream{e: e}
90 }
91 return e, streams
92}
93
94// Scan is the evidence of an output read whole.
95func Scan(output string) *Evidence {
96 e, w := NewEvidence(1)
97 w[0].Write([]byte(output))
98 w[0].Close()
99 return e
100}
101
102func (w *EvidenceStream) Write(p []byte) (int, error) {
103 n := len(p)
104 for len(p) > 0 {
105 i := bytes.IndexByte(p, '\n')
106 chunk := p
107 if i >= 0 {
108 chunk = p[:i]
109 }
110 if !w.long {
111 if len(w.partial)+len(chunk) > maxEvidenceLine {
112 w.long, w.partial = true, nil
113 } else {
114 w.partial = append(w.partial, chunk...)
115 }
116 }
117 if i < 0 {
118 break
119 }
120 w.line()
121 p = p[i+1:]
122 }
123 return n, nil
124}
125
126func (w *EvidenceStream) line() {
127 w.e.mu.Lock()
128 defer w.e.mu.Unlock()
129 if w.long {
130 w.e.broken = true
131 } else {
132 w.e.classify(strings.TrimSuffix(string(w.partial), "\r"))
133 }
134 w.partial, w.long = w.partial[:0], false
135}
136
137// Close records the stream's last line and that it ended whole.
138func (w *EvidenceStream) Close() error {
139 if w.done {
140 return nil
141 }
142 if len(w.partial) > 0 || w.long {
143 w.line()
144 }
145 w.done = true
146 w.e.mu.Lock()
147 w.e.open--
148 w.e.mu.Unlock()
149 return nil
150}
151
152// Abort records that the stream did not end whole.
153func (w *EvidenceStream) Abort() {
154 w.e.mu.Lock()
155 w.e.broken = true
156 w.e.mu.Unlock()
157}
158
159func (e *Evidence) complete() bool { return e.open == 0 && !e.broken }
160
161func (e *Evidence) classify(line string) {
162 if (independentFailure.MatchString(line) && !offlineDiagnostic.MatchString(line)) || jsonFailure(line) {
163 e.failure = true
164 }
165 switch trimmed := strings.TrimSpace(line); {
166 case trimmed == "" || neutralLine.MatchString(trimmed):
167 case offlineRefusal.MatchString(trimmed):
168 e.refusals++
169 default:
170 e.others++
171 }
172}
173
174// jsonFailure reports a go test -json event that failed: a test or a
175// package (fail), or a build (build-fail).
176func jsonFailure(line string) bool {
177 line = strings.TrimSpace(line)
178 if !strings.HasPrefix(line, "{") {
179 return false
180 }
181 var ev struct{ Action string }
182 return json.Unmarshal([]byte(line), &ev) == nil && (ev.Action == "fail" || ev.Action == "build-fail")
183}
184
185// GoModuleDirs lists the directories under root ("." first) holding a
186// module's go.mod whose dependencies come from the module cache: not
187// vendored, and not under vendor or testdata or a directory Go ignores
188// (a leading dot or underscore). Symlinks are not followed.
189func GoModuleDirs(root string) []string {
190 dir, err := os.OpenRoot(root)
191 if err != nil {
192 return nil
193 }
194 defer dir.Close()
195 var out []string
196 _ = fs.WalkDir(dir.FS(), ".", func(name string, d fs.DirEntry, err error) error {
197 if err != nil || len(out) >= 64 {
198 return fs.SkipDir
199 }
200 if d.IsDir() {
201 if base := d.Name(); name != "." && (ignoredDir(base)) {
202 return fs.SkipDir
203 }
204 return nil
205 }
206 if d.Name() != "go.mod" || !d.Type().IsRegular() {
207 return nil
208 }
209 if info, err := dir.Lstat(path.Join(path.Dir(name), "vendor/modules.txt")); err != nil || !info.Mode().IsRegular() {
210 out = append(out, path.Dir(name))
211 }
212 return nil
213 })
214 slices.Sort(out)
215 return out
216}
217
218func ignoredDir(base string) bool {
219 return base == "vendor" || base == "testdata" || strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_")
220}
221
222// DependencyStage is the argv of Equipo's own dependency stage: `go mod
223// download` in each module directory, stopping at the first failure. It
224// works on copies of go.mod and go.sum (-modfile), so the tree the gate
225// then checks is exactly the candidate's.
226func DependencyStage(dirs []string) []string {
227 const script = `t=$(mktemp -d) || exit 1
228i=0
229for d; do
230 i=$((i+1)); mkdir -p "$t/$i" || exit 1
231 cp -- "$d/go.mod" "$t/$i/go.mod" || exit 1
232 if [ -f "$d/go.sum" ]; then cp -- "$d/go.sum" "$t/$i/go.sum" || exit 1; fi
233 (cd -- "$d" && go mod download -modfile="$t/$i/go.mod") || exit $?
234done`
235 return append([]string{"/usr/bin/bash", "-c", script, "equipo-dependencies"}, dirs...)
236}
237
238// GoRequirement is what a repository's own files ask of the Go toolchain.
239type GoRequirement struct {
240 // Minimum is the highest go or toolchain directive in any go.mod.
241 Minimum string
242 // Make are the releases Makefiles pin. make runs with
243 // GOTOOLCHAIN=local (gotoolchain.Environment), so a newer patch of
244 // the same minor release stands in.
245 Make []string
246 // Exact are the releases other gate files pin. Nothing overrides
247 // those, so only that release runs them.
248 Exact []string
249}
250
251// GoRequirementFile reports whether a repository file is read for its Go
252// requirement: a go.mod (not a vendored or test-data copy), a Makefile or
253// .mk file, or an Amadan gate file.
254func GoRequirementFile(name string) bool {
255 for _, part := range strings.Split(path.Dir(name), "/") {
256 if part != "." && ignoredDir(part) && part != ".amadan" {
257 return false
258 }
259 }
260 base := path.Base(name)
261 return base == "go.mod" || base == "Makefile" || base == "makefile" || base == "GNUmakefile" || path.Ext(name) == ".mk" || name == ".amadan/ci" || strings.HasPrefix(name, ".amadan/ci.d/")
262}
263
264var goDirective = regexp.MustCompile(`(?m)^[ \t]*(go|toolchain)[ \t]+(\S+)[ \t]*(?://.*)?$`)
265var toolchainPin = regexp.MustCompile(`\bGOTOOLCHAIN[ \t]*(?::=|::=|\?=|=)[ \t]*['"]?(go1\.[0-9]+(?:\.[0-9]+)?(?:(?:rc|beta)[0-9]+)?)(\+auto|\+path)?`)
266
267// ReadGoRequirement reads the requirement from files named by
268// GoRequirementFile (path to content).
269func ReadGoRequirement(files map[string][]byte) GoRequirement {
270 var r GoRequirement
271 raise := func(v string) {
272 if version.IsValid(v) && (r.Minimum == "" || version.Compare(v, r.Minimum) > 0) {
273 r.Minimum = v
274 }
275 }
276 for name, body := range files {
277 text := string(body)
278 if path.Base(name) == "go.mod" {
279 for _, m := range goDirective.FindAllStringSubmatch(text, -1) {
280 v := m[2]
281 if m[1] == "go" {
282 v = "go" + v
283 }
284 raise(v)
285 }
286 continue
287 }
288 makefile := path.Base(name) != "ci" && !strings.HasPrefix(name, ".amadan/")
289 for _, m := range toolchainPin.FindAllStringSubmatch(text, -1) {
290 switch {
291 case m[2] != "":
292 raise(m[1])
293 case makefile:
294 r.Make = append(r.Make, m[1])
295 default:
296 r.Exact = append(r.Exact, m[1])
297 }
298 }
299 }
300 return r
301}
302
303// Unmet reports whether the local toolchain (go1.x.y) cannot honour r.
304func (r GoRequirement) Unmet(local string) bool {
305 if r.Minimum != "" && version.Compare(local, r.Minimum) < 0 {
306 return true
307 }
308 for _, pin := range r.Make {
309 if version.Lang(pin) != version.Lang(local) || version.Compare(local, pin) < 0 {
310 return true
311 }
312 }
313 for _, pin := range r.Exact {
314 if version.Compare(local, pin) != 0 {
315 return true
316 }
317 }
318 return false
319}
320
321// RunnerGoVersion is the release of the Go tree at goRoot, from the first
322// line of its VERSION file.
323func RunnerGoVersion(goRoot string) (string, error) {
324 raw, err := os.ReadFile(filepath.Join(goRoot, "VERSION"))
325 if err != nil {
326 return "", err
327 }
328 v, _, _ := strings.Cut(string(raw), "\n")
329 if v = strings.TrimSpace(v); !version.IsValid(v) {
330 return "", errors.New("go root has no release version")
331 }
332 return v, nil
333}
334