1
2
3
4
5 package moddeps_test
6
7 import (
8 "bytes"
9 "encoding/json"
10 "fmt"
11 "internal/testenv"
12 "io"
13 "io/fs"
14 "os"
15 "path/filepath"
16 "slices"
17 "sort"
18 "strings"
19 "sync"
20 "testing"
21
22 "golang.org/x/mod/module"
23 )
24
25
26
27
28
29
30
31
32
33
34
35 func TestAllDependencies(t *testing.T) {
36 goBin := testenv.GoToolPath(t)
37
38
39
40
41
42
43
44
45
46
47
48
49 for _, m := range findGorootModules(t) {
50
51
52 t.Run(m.Path+"(quick)", func(t *testing.T) {
53 t.Logf("module %s in directory %s", m.Path, m.Dir)
54
55 if m.hasVendor {
56
57
58
59 cmd := testenv.Command(t, goBin, "list", "-mod=vendor", "-deps", "./...")
60 cmd.Dir = m.Dir
61 cmd.Env = append(cmd.Environ(), "GO111MODULE=on", "GOWORK=off")
62 cmd.Stderr = new(strings.Builder)
63 _, err := cmd.Output()
64 if err != nil {
65 t.Errorf("%s: %v\n%s", strings.Join(cmd.Args, " "), err, cmd.Stderr)
66 t.Logf("(Run 'go mod vendor' in %s to ensure that dependencies have been vendored.)", m.Dir)
67 }
68 return
69 }
70
71
72
73 cmd := testenv.Command(t, goBin, "list", "-mod=readonly", "-m", "all")
74 cmd.Dir = m.Dir
75 cmd.Env = append(cmd.Environ(), "GO111MODULE=on", "GOWORK=off")
76 cmd.Stderr = new(strings.Builder)
77 out, err := cmd.Output()
78 if err != nil {
79 t.Fatalf("%s: %v\n%s", strings.Join(cmd.Args, " "), err, cmd.Stderr)
80 }
81 if strings.TrimSpace(string(out)) != m.Path {
82 t.Errorf("'%s' reported active modules other than %s:\n%s", strings.Join(cmd.Args, " "), m.Path, out)
83 t.Logf("(Run 'go mod tidy' in %s to ensure that no extraneous dependencies were added, or 'go mod vendor' to copy in imported packages.)", m.Dir)
84 }
85 })
86 }
87
88
89
90 if testing.Short() {
91 return
92 }
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109 testenv.MustHaveExternalNetwork(t)
110 if haveDiff := func() bool {
111 diff, err := testenv.Command(t, "diff", "--recursive", "--unified", ".", ".").CombinedOutput()
112 if err != nil || len(diff) != 0 {
113 return false
114 }
115 diff, err = testenv.Command(t, "diff", "--recursive", "--unified", ".", "..").CombinedOutput()
116 if err == nil || len(diff) == 0 {
117 return false
118 }
119 return true
120 }(); !haveDiff {
121
122
123
124
125 t.Skip("skipping because a diff command with support for --recursive and --unified flags is unavailable")
126 }
127
128
129
130
131
132
133 var modcacheEnv []string
134 {
135 out, err := testenv.Command(t, goBin, "env", "GOMODCACHE").Output()
136 if err != nil {
137 t.Fatalf("%s env GOMODCACHE: %v", goBin, err)
138 }
139 modcacheOk := false
140 if gomodcache := string(bytes.TrimSpace(out)); gomodcache != "" {
141 if _, err := os.Stat(gomodcache); err == nil {
142 modcacheOk = true
143 }
144 }
145 if !modcacheOk {
146 modcacheEnv = []string{
147 "GOMODCACHE=" + t.TempDir(),
148 "GOFLAGS=" + os.Getenv("GOFLAGS") + " -modcacherw",
149 }
150 }
151 }
152
153
154
155 bundleDir := t.TempDir()
156 r := runner{
157 Dir: filepath.Join(testenv.GOROOT(t), "src/cmd"),
158 Env: append(os.Environ(), modcacheEnv...),
159 }
160 r.run(t, goBin, "build", "-mod=readonly", "-o", bundleDir, "golang.org/x/tools/cmd/bundle")
161
162 var gorootCopyDir string
163 for _, m := range findGorootModules(t) {
164
165
166
167
168
169
170
171
172 if gorootCopyDir == "" {
173 gorootCopyDir = makeGOROOTCopy(t)
174 }
175
176 t.Run(m.Path+"(thorough)", func(t *testing.T) {
177 t.Logf("module %s in directory %s", m.Path, m.Dir)
178
179 defer func() {
180 if t.Failed() {
181
182
183
184
185 gorootCopyDir = ""
186 }
187 }()
188
189 rel, err := filepath.Rel(testenv.GOROOT(t), m.Dir)
190 if err != nil {
191 t.Fatalf("filepath.Rel(%q, %q): %v", testenv.GOROOT(t), m.Dir, err)
192 }
193 r := runner{
194 Dir: filepath.Join(gorootCopyDir, rel),
195 Env: append(append(os.Environ(), modcacheEnv...),
196
197 "GOROOT="+gorootCopyDir,
198
199 "PATH="+filepath.Join(gorootCopyDir, "bin")+string(filepath.ListSeparator)+
200 bundleDir+string(filepath.ListSeparator)+os.Getenv("PATH"),
201 "GOWORK=off",
202 ),
203 }
204 goBinCopy := filepath.Join(gorootCopyDir, "bin", "go")
205 r.run(t, goBinCopy, "mod", "tidy")
206 r.run(t, goBinCopy, "mod", "verify")
207 r.run(t, goBinCopy, "mod", "vendor")
208 pkgs := packagePattern(m.Path)
209 r.run(t, goBinCopy, "generate", `-run=^//go:generate bundle `, pkgs)
210 advice := "$ cd " + m.Dir + "\n" +
211 "$ go mod tidy # to remove extraneous dependencies\n" +
212 "$ go mod vendor # to vendor dependencies\n" +
213 "$ go generate -run=bundle " + pkgs + " # to regenerate bundled packages\n"
214 if m.Path == "std" {
215 r.run(t, goBinCopy, "generate", "syscall", "internal/syscall/...")
216 advice += "$ go generate syscall internal/syscall/... # to regenerate syscall packages\n"
217 }
218
219
220 diff, err := testenv.Command(t, "diff", "--recursive", "--unified", r.Dir, m.Dir).CombinedOutput()
221 if err != nil || len(diff) != 0 {
222 t.Errorf(`Module %s in %s is not tidy (-want +got):
223
224 %s
225 To fix it, run:
226
227 %s
228 (If module %[1]s is definitely tidy, this could mean
229 there's a problem in the go or bundle command.)`, m.Path, m.Dir, diff, advice)
230 }
231 })
232 }
233 }
234
235
236
237 func packagePattern(modulePath string) string {
238 if modulePath == "std" {
239 return "std"
240 }
241 return modulePath + "/..."
242 }
243
244
245
246
247
248
249
250
251
252
253 func makeGOROOTCopy(t *testing.T) string {
254 t.Helper()
255
256 gorootCopyDir := t.TempDir()
257 err := filepath.Walk(testenv.GOROOT(t), func(src string, info os.FileInfo, err error) error {
258 if err != nil {
259 return err
260 }
261 if info.IsDir() && src == filepath.Join(testenv.GOROOT(t), ".git") {
262 return filepath.SkipDir
263 }
264
265 rel, err := filepath.Rel(testenv.GOROOT(t), src)
266 if err != nil {
267 return fmt.Errorf("filepath.Rel(%q, %q): %v", testenv.GOROOT(t), src, err)
268 }
269 dst := filepath.Join(gorootCopyDir, rel)
270
271 if info.IsDir() && (src == filepath.Join(testenv.GOROOT(t), "bin") ||
272 src == filepath.Join(testenv.GOROOT(t), "pkg")) {
273
274
275 if err := os.Symlink(src, dst); err == nil {
276 return filepath.SkipDir
277 }
278 }
279
280 perm := info.Mode() & os.ModePerm
281 if info.Mode()&os.ModeSymlink != 0 {
282 info, err = os.Stat(src)
283 if err != nil {
284 return err
285 }
286 perm = info.Mode() & os.ModePerm
287 }
288
289
290 if info.IsDir() {
291 return os.MkdirAll(dst, perm|0200)
292 }
293
294
295
296
297 s, err := os.Open(src)
298 if err != nil {
299 return err
300 }
301 defer s.Close()
302 d, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_EXCL, perm)
303 if err != nil {
304 return err
305 }
306 _, err = io.Copy(d, s)
307 if err != nil {
308 d.Close()
309 return err
310 }
311 return d.Close()
312 })
313 if err != nil {
314 t.Fatal(err)
315 }
316 t.Logf("copied GOROOT from %s to %s", testenv.GOROOT(t), gorootCopyDir)
317 return gorootCopyDir
318 }
319
320 type runner struct {
321 Dir string
322 Env []string
323 }
324
325
326 func (r runner) run(t *testing.T, args ...string) {
327 t.Helper()
328 cmd := testenv.Command(t, args[0], args[1:]...)
329 cmd.Dir = r.Dir
330 cmd.Env = slices.Clip(r.Env)
331 if r.Dir != "" {
332 cmd.Env = append(cmd.Env, "PWD="+r.Dir)
333 }
334 out, err := cmd.CombinedOutput()
335 if err != nil {
336 t.Logf("> %s\n", strings.Join(args, " "))
337 t.Fatalf("command failed: %s\n%s", err, out)
338 }
339 }
340
341
342
343
344
345
346
347
348
349 func TestDependencyVersionsConsistent(t *testing.T) {
350
351 type requirement struct {
352 Required module.Version
353 Replacement module.Version
354 }
355 seen := map[string]map[requirement][]gorootModule{}
356 for _, m := range findGorootModules(t) {
357 if !m.hasVendor {
358
359 continue
360 }
361
362
363
364
365
366
367
368
369
370 vendor, err := os.ReadFile(filepath.Join(m.Dir, "vendor", "modules.txt"))
371 if err != nil {
372 t.Error(err)
373 continue
374 }
375
376 for _, line := range strings.Split(strings.TrimSpace(string(vendor)), "\n") {
377 parts := strings.Fields(line)
378 if len(parts) < 3 || parts[0] != "#" {
379 continue
380 }
381
382
383 var r requirement
384 r.Required.Path = parts[1]
385 r.Required.Version = parts[2]
386 if len(parts) >= 5 && parts[3] == "=>" {
387 r.Replacement.Path = parts[4]
388 if module.CheckPath(r.Replacement.Path) != nil {
389
390
391
392
393
394
395 t.Errorf("cannot check consistency for filesystem-local replacement in module %s (%s):\n%s", m.Path, m.Dir, line)
396 }
397
398 if len(parts) >= 6 {
399 r.Replacement.Version = parts[5]
400 }
401 }
402
403 if seen[r.Required.Path] == nil {
404 seen[r.Required.Path] = make(map[requirement][]gorootModule)
405 }
406 seen[r.Required.Path][r] = append(seen[r.Required.Path][r], m)
407 }
408 }
409
410
411 for path, versions := range seen {
412 if len(versions) > 1 {
413 t.Errorf("Modules within GOROOT require different versions of %s.", path)
414 for r, mods := range versions {
415 desc := new(strings.Builder)
416 desc.WriteString(r.Required.Version)
417 if r.Replacement.Path != "" {
418 fmt.Fprintf(desc, " => %s", r.Replacement.Path)
419 if r.Replacement.Version != "" {
420 fmt.Fprintf(desc, " %s", r.Replacement.Version)
421 }
422 }
423
424 for _, m := range mods {
425 t.Logf("%s\trequires %v", m.Path, desc)
426 }
427 }
428 }
429 }
430 }
431
432 type gorootModule struct {
433 Path string
434 Dir string
435 hasVendor bool
436 }
437
438
439 func findGorootModules(t *testing.T) []gorootModule {
440 t.Helper()
441 goBin := testenv.GoToolPath(t)
442
443 goroot.once.Do(func() {
444
445
446
447 root := testenv.GOROOT(t)
448 if !os.IsPathSeparator(root[len(root)-1]) {
449 root += string(filepath.Separator)
450 }
451 goroot.err = filepath.WalkDir(root, func(path string, info fs.DirEntry, err error) error {
452 if err != nil {
453 return err
454 }
455 if info.IsDir() && path != root && (info.Name() == "vendor" || info.Name() == "testdata") {
456 return filepath.SkipDir
457 }
458 if info.IsDir() && path == filepath.Join(testenv.GOROOT(t), "pkg") {
459
460
461
462
463
464 return filepath.SkipDir
465 }
466 if info.IsDir() && path != root && (strings.HasPrefix(info.Name(), "_") || strings.HasPrefix(info.Name(), ".")) {
467
468
469
470 return filepath.SkipDir
471 }
472 if info.IsDir() || info.Name() != "go.mod" {
473 return nil
474 }
475 dir := filepath.Dir(path)
476
477
478
479 cmd := testenv.Command(t, goBin, "list", "-json", "-m")
480 cmd.Dir = dir
481 cmd.Env = append(cmd.Environ(), "GO111MODULE=on", "GOWORK=off")
482 cmd.Stderr = new(strings.Builder)
483 out, err := cmd.Output()
484 if err != nil {
485 return fmt.Errorf("'go list -json -m' in %s: %w\n%s", dir, err, cmd.Stderr)
486 }
487
488 var m gorootModule
489 if err := json.Unmarshal(out, &m); err != nil {
490 return fmt.Errorf("decoding 'go list -json -m' in %s: %w", dir, err)
491 }
492 if m.Path == "" || m.Dir == "" {
493 return fmt.Errorf("'go list -json -m' in %s failed to populate Path and/or Dir", dir)
494 }
495 if _, err := os.Stat(filepath.Join(dir, "vendor")); err == nil {
496 m.hasVendor = true
497 }
498 goroot.modules = append(goroot.modules, m)
499 return nil
500 })
501 if goroot.err != nil {
502 return
503 }
504
505
506
507
508
509 knownGOROOTModules := [...]string{
510 "std",
511 "cmd",
512
513 }
514 var seen = make(map[string]bool)
515 for _, m := range goroot.modules {
516 seen[m.Path] = true
517 }
518 for _, m := range knownGOROOTModules {
519 if !seen[m] {
520 goroot.err = fmt.Errorf("findGorootModules didn't find the well-known module %q", m)
521 break
522 }
523 }
524 sort.Slice(goroot.modules, func(i, j int) bool {
525 return goroot.modules[i].Dir < goroot.modules[j].Dir
526 })
527 })
528 if goroot.err != nil {
529 t.Fatal(goroot.err)
530 }
531 return goroot.modules
532 }
533
534
535 var goroot struct {
536 once sync.Once
537 modules []gorootModule
538 err error
539 }
540
View as plain text