gunk-dev/the-valley

go-dependencies.go

source9ee95920e399main's published tip history
17.0 KiB
1// Command go-dependencies holds the Go dependency boundary of the tree
2// whose root it is given (AGENTS.md, "Go dependencies"). Every Go module
3// imports only the standard library and the tree's own modules, except the
4// module rooted at flow/, which may import third-party modules, and which
5// no other module imports or replaces into.
6//
7// It reads every .go file's imports whatever its build constraints, test
8// files included, and every go.mod as `go mod edit -json` reads it. It asks
9// the go command on PATH, the pinned toolchain, which imported paths are
10// standard packages. It builds nothing and fetches nothing. What it cannot
11// read, it refuses: a workspace file, a vendor directory, a go.mod the go
12// command cannot parse, a Go file it cannot parse, a symlink that leaves
13// the tree, and a symlink named like a Go file or go.mod that it cannot
14// read through.
15//
16// Each refusal names the file and the import or directive; any refusal
17// exits 1.
18package main
19
20import (
21 "bytes"
22 "encoding/json"
23 "errors"
24 "fmt"
25 "go/parser"
26 "go/token"
27 "io"
28 "os"
29 "os/exec"
30 "path"
31 "path/filepath"
32 "slices"
33 "sort"
34 "strconv"
35 "strings"
36)
37
38// The one module that may import third-party modules: its directory,
39// relative to the root, and the path it declares.
40const (
41 flowDir = "flow"
42 flowModule = "the-valley/flow"
43)
44
45type refusal struct {
46 File string // slash-separated, relative to the root
47 Line int // the import's line, for an import
48 Subject string // the import path or go.mod directive, when there is one
49 Reason string
50}
51
52func (r refusal) String() string {
53 s := r.File
54 if r.Line > 0 {
55 s += ":" + strconv.Itoa(r.Line)
56 }
57 if r.Subject != "" {
58 s += ": " + r.Subject
59 }
60 return s + ": " + r.Reason
61}
62
63type module struct {
64 dir string // logical, slash-separated, relative to the root
65 physDir string // where it is on disk, with every symlink resolved
66 gomod string // its go.mod, logical
67 path string // the path it declares; empty when go.mod is unreadable
68 mod goMod
69}
70
71// goMod is the part of `go mod edit -json`'s output the check reads.
72type goMod struct {
73 Module struct{ Path string }
74 Require []struct{ Path string }
75 Replace []struct {
76 Old, New struct{ Path, Version string }
77 }
78 Tool []struct{ Path string }
79}
80
81type goFile struct {
82 file string
83 module *module // nil for a file in no module
84 imports []goImport
85}
86
87type goImport struct {
88 path string
89 line int
90}
91
92type tree struct {
93 realRoot string
94 goBin string
95 env []string
96 tmp string
97 modules []*module
98 files []*goFile
99 byPath map[string]*module // modules whose declared path is accepted
100 std map[string]bool
101 refused []refusal
102}
103
104func main() {
105 if len(os.Args) != 2 {
106 fmt.Fprintln(os.Stderr, "usage: go-dependencies ROOT")
107 os.Exit(2)
108 }
109 refusals, modules, files, err := check(os.Args[1])
110 if err != nil {
111 fmt.Fprintln(os.Stderr, "go-dependencies:", err)
112 os.Exit(2)
113 }
114 for _, r := range refusals {
115 fmt.Println(r)
116 }
117 if len(refusals) > 0 {
118 fmt.Printf("go-dependencies: %d refused\n", len(refusals))
119 os.Exit(1)
120 }
121 fmt.Printf("go-dependencies: %d modules and %d Go files keep to the boundary\n", modules, files)
122}
123
124// check judges the tree at root. An error means it could not judge it at
125// all.
126func check(root string) ([]refusal, int, int, error) {
127 abs, err := filepath.Abs(root)
128 if err != nil {
129 return nil, 0, 0, err
130 }
131 real, err := filepath.EvalSymlinks(abs)
132 if err != nil {
133 return nil, 0, 0, err
134 }
135 goBin, err := exec.LookPath("go")
136 if err != nil {
137 return nil, 0, 0, err
138 }
139 // The go command runs in an empty directory, so no go.mod or go.work
140 // around it changes what it reads, with its own cache, and with every
141 // setting that could switch toolchains or reach the network pinned.
142 tmp, err := os.MkdirTemp("", "go-dependencies")
143 if err != nil {
144 return nil, 0, 0, err
145 }
146 defer os.RemoveAll(tmp)
147 t := &tree{
148 realRoot: real,
149 goBin: goBin,
150 tmp: tmp,
151 env: append(os.Environ(),
152 "GOENV=off", "GOFLAGS=", "GOTOOLCHAIN=local", "GOWORK=off",
153 "GOPROXY=off", "GO111MODULE=on", "GOCACHE="+filepath.Join(tmp, "cache")),
154 byPath: map[string]*module{},
155 }
156 t.walk(".", real, nil, nil)
157 t.readModules()
158 if err := t.readStd(); err != nil {
159 return nil, 0, 0, err
160 }
161 for _, m := range t.modules {
162 if m.path != "" && m.dir != flowDir {
163 t.judgeGoMod(m)
164 }
165 }
166 for _, f := range t.files {
167 if f.module != nil && f.module.dir == flowDir {
168 continue
169 }
170 for _, imp := range f.imports {
171 if reason := t.judge(imp.path); reason != "" {
172 t.refused = append(t.refused, refusal{f.file, imp.line, strconv.Quote(imp.path), reason})
173 }
174 }
175 }
176 sort.Slice(t.refused, func(i, j int) bool {
177 a, b := t.refused[i], t.refused[j]
178 if a.File != b.File {
179 return a.File < b.File
180 }
181 if a.Line != b.Line {
182 return a.Line < b.Line
183 }
184 return a.Subject < b.Subject
185 })
186 return t.refused, len(t.modules), len(t.files), nil
187}
188
189func (t *tree) refuse(file, subject, reason string) {
190 t.refused = append(t.refused, refusal{File: file, Subject: subject, Reason: reason})
191}
192
193func child(logical, name string) string {
194 if logical == "." {
195 return name
196 }
197 return logical + "/" + name
198}
199
200func within(root, p string) bool {
201 return p == root || strings.HasPrefix(p, root+string(filepath.Separator))
202}
203
204func inFlow(dir string) bool {
205 return dir == flowDir || strings.HasPrefix(dir, flowDir+"/")
206}
207
208func inNamespace(p, ns string) bool {
209 return p == ns || strings.HasPrefix(p, ns+"/")
210}
211
212// walk reads the directory at phys, which the tree holds at logical, in
213// the module mod. ancestors are the directories, resolved, that the walk
214// descended through to reach it.
215func (t *tree) walk(logical, phys string, mod *module, ancestors []string) {
216 entries, err := os.ReadDir(phys)
217 if err != nil {
218 t.refuse(logical, "", "cannot be read: "+err.Error())
219 return
220 }
221 type entry struct {
222 name, logical, phys string
223 info os.FileInfo
224 }
225 var resolved []entry
226 for _, e := range entries {
227 name := e.Name()
228 if name == ".git" {
229 continue
230 }
231 l, p := child(logical, name), filepath.Join(phys, name)
232 info, err := os.Lstat(p)
233 if err != nil {
234 t.refuse(l, "", "cannot be read: "+err.Error())
235 continue
236 }
237 link := info.Mode()&os.ModeSymlink != 0
238 switch {
239 case name == "go.work":
240 t.refuse(l, "", "a workspace changes how every module beneath it builds, so the check refuses one")
241 continue
242 case name == "vendor" && (info.IsDir() || link):
243 t.refuse(l, "", "a vendor directory supplies packages the check does not read, so it refuses one")
244 continue
245 }
246 if link {
247 var ok bool
248 if p, info, ok = t.follow(l, p); !ok {
249 continue
250 }
251 }
252 resolved = append(resolved, entry{name, l, p, info})
253 }
254 // A go.mod makes this directory a module's root, and every file below
255 // it, down to the next go.mod, part of that module.
256 for _, e := range resolved {
257 if e.name == "go.mod" && e.info.Mode().IsRegular() {
258 mod = &module{dir: logical, physDir: phys, gomod: e.logical}
259 t.modules = append(t.modules, mod)
260 }
261 }
262 for _, e := range resolved {
263 switch {
264 case e.info.IsDir():
265 chain := append(append([]string(nil), ancestors...), phys)
266 if slices.Contains(chain, e.phys) {
267 t.refuse(e.logical, "", "a symlink loops back to a directory above it")
268 continue
269 }
270 t.walk(e.logical, e.phys, mod, chain)
271 case e.info.Mode().IsRegular() && strings.HasSuffix(e.name, ".go"):
272 t.parse(e.logical, e.phys, mod)
273 }
274 }
275}
276
277// follow resolves the symlink at phys, which the tree holds at logical.
278// A file or directory it names inside the tree is read as if it were at
279// logical, which is where Go reads it.
280func (t *tree) follow(logical, phys string) (string, os.FileInfo, bool) {
281 target, err := os.Readlink(phys)
282 if err != nil {
283 t.refuse(logical, "", "cannot be read: "+err.Error())
284 return "", nil, false
285 }
286 if filepath.IsAbs(target) || !within(t.realRoot, filepath.Join(filepath.Dir(phys), target)) {
287 t.refuse(logical, target, "a symlink leaves the repository")
288 return "", nil, false
289 }
290 // The check's source holds the tree's .go files and go.mod files and
291 // none of its other files, so a link giving one of those names to a
292 // file of another name is a link the check cannot read through.
293 name, targetName := path.Base(logical), filepath.Base(target)
294 goName := strings.HasSuffix(name, ".go") || name == "go.mod"
295 if strings.HasSuffix(name, ".go") && !strings.HasSuffix(targetName, ".go") ||
296 name == "go.mod" && targetName != "go.mod" {
297 t.refuse(logical, target, "a symlink gives a Go file's name to a file of another name, which the check does not read")
298 return "", nil, false
299 }
300 real, err := filepath.EvalSymlinks(phys)
301 if err != nil {
302 // A link of any other name that resolves to nothing here names no
303 // Go source, since every Go file is in the tree.
304 if goName {
305 t.refuse(logical, target, "a symlink resolves to no file in the tree the check reads")
306 }
307 return "", nil, false
308 }
309 if !within(t.realRoot, real) {
310 t.refuse(logical, target, "a symlink leaves the repository")
311 return "", nil, false
312 }
313 info, err := os.Stat(real)
314 if err != nil {
315 t.refuse(logical, target, "cannot be read: "+err.Error())
316 return "", nil, false
317 }
318 return real, info, true
319}
320
321func (t *tree) parse(logical, phys string, mod *module) {
322 src, err := os.ReadFile(phys)
323 if err != nil {
324 t.refuse(logical, "", "cannot be read: "+err.Error())
325 return
326 }
327 fset := token.NewFileSet()
328 f, err := parser.ParseFile(fset, logical, src, parser.ImportsOnly)
329 if err != nil {
330 t.refuse(logical, "", "its imports cannot be parsed: "+err.Error())
331 return
332 }
333 gf := &goFile{file: logical, module: mod}
334 for _, spec := range f.Imports {
335 p, err := strconv.Unquote(spec.Path.Value)
336 if err != nil {
337 t.refuse(logical, spec.Path.Value, "not an import path Go accepts")
338 continue
339 }
340 gf.imports = append(gf.imports, goImport{p, fset.Position(spec.Pos()).Line})
341 }
342 t.files = append(t.files, gf)
343}
344
345// readModules reads every go.mod with the go command, and holds each
346// declared path to the boundary before any module may be named by it.
347func (t *tree) readModules() {
348 declared := map[string]*module{}
349 for _, m := range t.modules {
350 cmd := exec.Command(t.goBin, "mod", "edit", "-json", filepath.Join(m.physDir, "go.mod"))
351 cmd.Dir, cmd.Env = t.tmp, t.env
352 var stderr bytes.Buffer
353 cmd.Stderr = &stderr
354 out, err := cmd.Output()
355 if err == nil {
356 err = json.Unmarshal(out, &m.mod)
357 }
358 if err == nil && m.mod.Module.Path == "" {
359 err = errors.New("it declares no module path")
360 }
361 if err != nil {
362 msg := strings.TrimSpace(stderr.String())
363 if msg == "" {
364 msg = err.Error()
365 }
366 t.refuse(m.gomod, "", "go mod edit cannot read it: "+msg)
367 continue
368 }
369 m.path = m.mod.Module.Path
370 subject := "module " + m.path
371 switch {
372 case m.dir == flowDir && m.path != flowModule:
373 t.refuse(m.gomod, subject, "flow/ declares "+flowModule)
374 case !inFlow(m.dir) && inNamespace(m.path, flowModule):
375 t.refuse(m.gomod, subject, "only flow/ declares "+flowModule)
376 case !inFlow(m.dir) && strings.Contains(strings.SplitN(m.path, "/", 2)[0], "."):
377 // A first element with a dot names a host the go command
378 // fetches from, so such a module would stand in for a
379 // third-party one.
380 t.refuse(m.gomod, subject, "a module outside flow/ declares a path that cannot name a third-party module")
381 case declared[m.path] != nil:
382 t.refuse(m.gomod, subject, declared[m.path].gomod+" declares it too")
383 default:
384 declared[m.path] = m
385 t.byPath[m.path] = m
386 }
387 }
388}
389
390// readStd asks the toolchain which of the imported paths are standard
391// packages. go list reports a standard package as one even where build
392// constraints exclude every file of it for this target, so a package that
393// exists only for another target counts. The command's packages under
394// cmd/ are no part of the standard library, as go list std has it.
395func (t *tree) readStd() error {
396 t.std = map[string]bool{}
397 seen := map[string]bool{}
398 var paths []string
399 add := func(p string) {
400 if !seen[p] && validImportPath(p) {
401 seen[p] = true
402 paths = append(paths, p)
403 }
404 }
405 for _, f := range t.files {
406 for _, imp := range f.imports {
407 add(imp.path)
408 }
409 }
410 for _, m := range t.modules {
411 for _, tool := range m.mod.Tool {
412 add(tool.Path)
413 }
414 }
415 if len(paths) == 0 {
416 return nil
417 }
418 sort.Strings(paths)
419 cmd := exec.Command(t.goBin, append([]string{"list", "-e", "-json=ImportPath,Standard", "--"}, paths...)...)
420 cmd.Dir, cmd.Env = t.tmp, t.env
421 var stderr bytes.Buffer
422 cmd.Stderr = &stderr
423 out, err := cmd.Output()
424 if err != nil {
425 return fmt.Errorf("go list: %v: %s", err, strings.TrimSpace(stderr.String()))
426 }
427 dec := json.NewDecoder(bytes.NewReader(out))
428 for {
429 var p struct {
430 ImportPath string
431 Standard bool
432 }
433 if err := dec.Decode(&p); err == io.EOF {
434 return nil
435 } else if err != nil {
436 return fmt.Errorf("go list: %v", err)
437 }
438 if p.Standard && !inNamespace(p.ImportPath, "cmd") {
439 t.std[p.ImportPath] = true
440 }
441 }
442}
443
444// validImportPath reports whether p is an import path by the go command's
445// rules (golang.org/x/mod/module.CheckImportPath), and neither a package
446// pattern nor a name the go command reads as a package pattern, which go
447// list would expand instead of looking up.
448func validImportPath(p string) bool {
449 switch p {
450 case "", "main", "all", "std", "cmd", "tool", "work":
451 return false
452 }
453 if p[0] == '-' || strings.Contains(p, "...") {
454 return false
455 }
456 for _, elem := range strings.Split(p, "/") {
457 if strings.Trim(elem, ".") == "" || strings.HasSuffix(elem, ".") {
458 return false
459 }
460 for _, c := range elem {
461 if !('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' || strings.ContainsRune("-._~+", c)) {
462 return false
463 }
464 }
465 short, _, _ := strings.Cut(elem, ".")
466 if windowsReserved(short) {
467 return false
468 }
469 if i := strings.LastIndexByte(short, '~'); i >= 0 && i < len(short)-1 && strings.Trim(short[i+1:], "0123456789") == "" {
470 return false
471 }
472 }
473 return true
474}
475
476// windowsReserved reports whether a path element, up to its first dot, is
477// a device name Windows reserves, which Go refuses in an import path.
478func windowsReserved(short string) bool {
479 switch strings.ToUpper(short) {
480 case "CON", "PRN", "AUX", "NUL":
481 return true
482 }
483 if len(short) == 4 && short[3] >= '1' && short[3] <= '9' {
484 prefix := strings.ToUpper(short[:3])
485 return prefix == "COM" || prefix == "LPT"
486 }
487 return false
488}
489
490func (t *tree) owner(p string) *module {
491 var best *module
492 for mp, m := range t.byPath {
493 if inNamespace(p, mp) && (best == nil || len(mp) > len(best.path)) {
494 best = m
495 }
496 }
497 return best
498}
499
500// judge returns why a module outside flow/ may not import p, or "".
501func (t *tree) judge(p string) string {
502 switch {
503 case p == "C": // cgo's pseudo-package
504 return ""
505 case !validImportPath(p):
506 return "not an import path Go accepts, or a package pattern"
507 case inNamespace(p, flowModule):
508 return "no module outside flow/ imports from it"
509 case t.std[p]:
510 return ""
511 }
512 if m := t.owner(p); m != nil {
513 if inFlow(m.dir) {
514 return "no module outside flow/ imports from it"
515 }
516 return ""
517 }
518 return "neither the standard library nor a module of this repository"
519}
520
521// judgeGoMod holds the go.mod of a module outside flow/ to the boundary.
522func (t *tree) judgeGoMod(m *module) {
523 for _, r := range m.mod.Require {
524 subject := "require " + r.Path
525 owner := t.byPath[r.Path]
526 switch {
527 case inNamespace(r.Path, flowModule) || owner != nil && inFlow(owner.dir):
528 t.refuse(m.gomod, subject, "no module outside flow/ requires a module in it")
529 case owner == nil:
530 t.refuse(m.gomod, subject, "not a module of this repository")
531 }
532 }
533 for _, r := range m.mod.Replace {
534 subject := "replace " + r.Old.Path
535 if r.Old.Version != "" {
536 subject += " " + r.Old.Version
537 }
538 subject += " => " + r.New.Path
539 if r.New.Version != "" {
540 subject += " " + r.New.Version
541 }
542 if reason := t.judgeReplace(m, r.Old.Path, r.New.Path, r.New.Version); reason != "" {
543 t.refuse(m.gomod, subject, reason)
544 }
545 }
546 for _, tool := range m.mod.Tool {
547 if reason := t.judge(tool.Path); reason != "" {
548 t.refuse(m.gomod, "tool "+tool.Path, reason)
549 }
550 }
551}
552
553func (t *tree) judgeReplace(m *module, old, dir, version string) string {
554 const outside = "the replacement is outside the repository"
555 const intoFlow = "no module outside flow/ replaces into it"
556 if version != "" || filepath.IsAbs(dir) {
557 return outside
558 }
559 logical := path.Join(m.dir, filepath.ToSlash(dir))
560 if logical == ".." || strings.HasPrefix(logical, "../") {
561 return outside
562 }
563 if inFlow(logical) {
564 return intoFlow
565 }
566 real, err := filepath.EvalSymlinks(filepath.Join(m.physDir, dir))
567 if err != nil {
568 return "the replacement is no module of this repository"
569 }
570 if !within(t.realRoot, real) {
571 return "the replacement resolves through a symlink to outside the repository"
572 }
573 if within(filepath.Join(t.realRoot, flowDir), real) {
574 return intoFlow
575 }
576 var target *module
577 for _, other := range t.modules {
578 if other.physDir == real {
579 target = other
580 break
581 }
582 }
583 switch {
584 case target == nil || target.path == "":
585 return "the replacement is no module of this repository"
586 case inFlow(target.dir):
587 return intoFlow
588 case target.path != old || t.byPath[old] != target:
589 return "the replacement declares " + target.path + ", so it would stand in for another module"
590 }
591 return ""
592}