Debian Codegraph @

internal/packagestest/export.go

raw symbols SCIP
1 // Copyright 2018 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 /*
6 Package packagestest creates temporary projects on disk for testing go tools on.
7
8 By changing the exporter used, you can create projects for multiple build
9 systems from the same description, and run the same tests on them in many
10 cases.
11
12 # Example
13
14 As an example of packagestest use, consider the following test that runs
15 the 'go list' command on the specified modules:
16
17 // TestGoList exercises the 'go list' command in module mode and in GOPATH mode.
18 func TestGoList(t *testing.T) { packagestest.TestAll(t, testGoList) }
19 func testGoList(t *testing.T, x packagestest.Exporter) {
20 e := packagestest.Export(t, x, []packagestest.Module{
21 {
22 Name: "gopher.example/repoa",
23 Files: map[string]interface{}{
24 "a/a.go": "package a",
25 },
26 },
27 {
28 Name: "gopher.example/repob",
29 Files: map[string]interface{}{
30 "b/b.go": "package b",
31 },
32 },
33 })
34 defer e.Cleanup()
35
36 cmd := exec.Command("go", "list", "gopher.example/...")
37 cmd.Dir = e.Config.Dir
38 cmd.Env = e.Config.Env
39 out, err := cmd.Output()
40 if err != nil {
41 t.Fatal(err)
42 }
43 t.Logf("'go list gopher.example/...' with %s mode layout:\n%s", x.Name(), out)
44 }
45
46 TestGoList uses TestAll to exercise the 'go list' command with all
47 exporters known to packagestest. Currently, packagestest includes
48 exporters that produce module mode layouts and GOPATH mode layouts.
49 Running the test with verbose output will print:
50
51 === RUN TestGoList
52 === RUN TestGoList/GOPATH
53 === RUN TestGoList/Modules
54 --- PASS: TestGoList (0.21s)
55 --- PASS: TestGoList/GOPATH (0.03s)
56 main_test.go:36: 'go list gopher.example/...' with GOPATH mode layout:
57 gopher.example/repoa/a
58 gopher.example/repob/b
59 --- PASS: TestGoList/Modules (0.18s)
60 main_test.go:36: 'go list gopher.example/...' with Modules mode layout:
61 gopher.example/repoa/a
62 gopher.example/repob/b
63 */
64 package packagestest
65
66 import (
67 "errors"
68 "flag"
69 "fmt"
70 "go/token"
71 "io"
72 "log"
73 "os"
74 "path/filepath"
75 "runtime"
76 "strings"
77 "testing"
78
79 "golang.org/x/tools/go/packages"
80 "golang.org/x/tools/internal/astutil"
81 "golang.org/x/tools/internal/expect"
82 "golang.org/x/tools/internal/testenv"
83 )
84
85 var (
86 skipCleanup = flag.Bool("skip-cleanup", false, "Do not delete the temporary export folders") // for debugging
87 )
88
89 // ErrUnsupported indicates an error due to an operation not supported on the
90 // current platform.
91 var ErrUnsupported = errors.New("operation is not supported")
92
93 // Module is a representation of a go module.
94 type Module struct {
95 // Name is the base name of the module as it would be in the go.mod file.
96 Name string
97 // Files is the set of source files for all packages that make up the module.
98 // The keys are the file fragment that follows the module name, the value can
99 // be a string or byte slice, in which case it is the contents of the
100 // file, otherwise it must be a Writer function.
101 Files map[string]any
102
103 // Overlay is the set of source file overlays for the module.
104 // The keys are the file fragment as in the Files configuration.
105 // The values are the in memory overlay content for the file.
106 Overlay map[string][]byte
107 }
108
109 // A Writer is a function that writes out a test file.
110 // It is provided the name of the file to write, and may return an error if it
111 // cannot write the file.
112 // These are used as the content of the Files map in a Module.
113 type Writer func(filename string) error
114
115 // Exported is returned by the Export function to report the structure that was produced on disk.
116 type Exported struct {
117 // Config is a correctly configured packages.Config ready to be passed to packages.Load.
118 // Exactly what it will contain varies depending on the Exporter being used.
119 Config *packages.Config
120
121 // Modules is the module description that was used to produce this exported data set.
122 Modules []Module
123
124 ExpectFileSet *token.FileSet // The file set used when parsing expectations
125
126 Exporter Exporter // the exporter used
127 temp string // the temporary directory that was exported to
128 primary string // the first non GOROOT module that was exported
129 written map[string]map[string]string // the full set of exported files
130 notes []*expect.Note // The list of expectations extracted from go source files
131 markers map[string]astutil.Range // The set of markers extracted from go source files
132 }
133
134 // Exporter implementations are responsible for converting from the generic description of some
135 // test data to a driver specific file layout.
136 type Exporter interface {
137 // Name reports the name of the exporter, used in logging and sub-test generation.
138 Name() string
139 // Filename reports the system filename for test data source file.
140 // It is given the base directory, the module the file is part of and the filename fragment to
141 // work from.
142 Filename(exported *Exported, module, fragment string) string
143 // Finalize is called once all files have been written to write any extra data needed and modify
144 // the Config to match. It is handed the full list of modules that were encountered while writing
145 // files.
146 Finalize(exported *Exported) error
147 }
148
149 // All is the list of known exporters.
150 // This is used by TestAll to run tests with all the exporters.
151 var All = []Exporter{GOPATH, Modules}
152
153 // TestAll invokes the testing function once for each exporter registered in
154 // the All global.
155 // Each exporter will be run as a sub-test named after the exporter being used.
156 func TestAll(t *testing.T, f func(*testing.T, Exporter)) {
157 t.Helper()
158 for _, e := range All {
159 t.Run(e.Name(), func(t *testing.T) {
160 t.Helper()
161 f(t, e)
162 })
163 }
164 }
165
166 // BenchmarkAll invokes the testing function once for each exporter registered in
167 // the All global.
168 // Each exporter will be run as a sub-test named after the exporter being used.
169 func BenchmarkAll(b *testing.B, f func(*testing.B, Exporter)) {
170 b.Helper()
171 for _, e := range All {
172 b.Run(e.Name(), func(b *testing.B) {
173 b.Helper()
174 f(b, e)
175 })
176 }
177 }
178
179 // Export is called to write out a test directory from within a test function.
180 // It takes the exporter and the build system agnostic module descriptions, and
181 // uses them to build a temporary directory.
182 // It returns an Exported with the results of the export.
183 // The Exported.Config is prepared for loading from the exported data.
184 // You must invoke Exported.Cleanup on the returned value to clean up.
185 // The file deletion in the cleanup can be skipped by setting the skip-cleanup
186 // flag when invoking the test, allowing the temporary directory to be left for
187 // debugging tests.
188 //
189 // If the Writer for any file within any module returns an error equivalent to
190 // ErrUnspported, Export skips the test.
191 func Export(t testing.TB, exporter Exporter, modules []Module) *Exported {
192 t.Helper()
193 if exporter == Modules {
194 testenv.NeedsTool(t, "go")
195 }
196
197 dirname := strings.Replace(t.Name(), "/", "_", -1)
198 dirname = strings.Replace(dirname, "#", "_", -1) // duplicate subtests get a #NNN suffix.
199 temp, err := os.MkdirTemp("", dirname)
200 if err != nil {
201 t.Fatal(err)
202 }
203 exported := &Exported{
204 Config: &packages.Config{
205 Dir: temp,
206 Env: append(os.Environ(), "GOPACKAGESDRIVER=off", "GOROOT="), // Clear GOROOT to work around #32849.
207 Overlay: make(map[string][]byte),
208 Tests: true,
209 Mode: packages.LoadImports,
210 },
211 Modules: modules,
212 Exporter: exporter,
213 temp: temp,
214 primary: modules[0].Name,
215 written: map[string]map[string]string{},
216 ExpectFileSet: token.NewFileSet(),
217 }
218 if testing.Verbose() {
219 exported.Config.Logf = t.Logf
220 }
221 defer func() {
222 if t.Failed() || t.Skipped() {
223 exported.Cleanup()
224 }
225 }()
226 for _, module := range modules {
227 // Create all parent directories before individual files. If any file is a
228 // symlink to a directory, that directory must exist before the symlink is
229 // created or else it may be created with the wrong type on Windows.
230 // (See https://golang.org/issue/39183.)
231 for fragment := range module.Files {
232 fullpath := exporter.Filename(exported, module.Name, filepath.FromSlash(fragment))
233 if err := os.MkdirAll(filepath.Dir(fullpath), 0755); err != nil {
234 t.Fatal(err)
235 }
236 }
237
238 for fragment, value := range module.Files {
239 fullpath := exporter.Filename(exported, module.Name, filepath.FromSlash(fragment))
240 written, ok := exported.written[module.Name]
241 if !ok {
242 written = map[string]string{}
243 exported.written[module.Name] = written
244 }
245 written[fragment] = fullpath
246 switch value := value.(type) {
247 case Writer:
248 if err := value(fullpath); err != nil {
249 if errors.Is(err, ErrUnsupported) {
250 t.Skip(err)
251 }
252 t.Fatal(err)
253 }
254 case string:
255 if err := os.WriteFile(fullpath, []byte(value), 0644); err != nil {
256 t.Fatal(err)
257 }
258 default:
259 t.Fatalf("Invalid type %T in files, must be string or Writer", value)
260 }
261 }
262 for fragment, value := range module.Overlay {
263 fullpath := exporter.Filename(exported, module.Name, filepath.FromSlash(fragment))
264 exported.Config.Overlay[fullpath] = value
265 }
266 }
267 if err := exporter.Finalize(exported); err != nil {
268 t.Fatal(err)
269 }
270 testenv.NeedsGoPackagesEnv(t, exported.Config.Env)
271 return exported
272 }
273
274 // Script returns a Writer that writes out contents to the file and sets the
275 // executable bit on the created file.
276 // It is intended for source files that are shell scripts.
277 func Script(contents string) Writer {
278 return func(filename string) error {
279 return os.WriteFile(filename, []byte(contents), 0755)
280 }
281 }
282
283 // Link returns a Writer that creates a hard link from the specified source to
284 // the required file.
285 // This is used to link testdata files into the generated testing tree.
286 //
287 // If hard links to source are not supported on the destination filesystem, the
288 // returned Writer returns an error for which errors.Is(_, ErrUnsupported)
289 // returns true.
290 func Link(source string) Writer {
291 return func(filename string) error {
292 linkErr := os.Link(source, filename)
293
294 if linkErr != nil && !builderMustSupportLinks() {
295 // Probe to figure out whether Link failed because the Link operation
296 // isn't supported.
297 if stat, err := openAndStat(source); err == nil {
298 if err := createEmpty(filename, stat.Mode()); err == nil {
299 // Successfully opened the source and created the destination,
300 // but the result is empty and not a hard-link.
301 return &os.PathError{Op: "Link", Path: filename, Err: ErrUnsupported}
302 }
303 }
304 }
305
306 return linkErr
307 }
308 }
309
310 // Symlink returns a Writer that creates a symlink from the specified source to the
311 // required file.
312 // This is used to link testdata files into the generated testing tree.
313 //
314 // If symlinks to source are not supported on the destination filesystem, the
315 // returned Writer returns an error for which errors.Is(_, ErrUnsupported)
316 // returns true.
317 func Symlink(source string) Writer {
318 if !strings.HasPrefix(source, ".") {
319 if absSource, err := filepath.Abs(source); err == nil {
320 if _, err := os.Stat(source); !os.IsNotExist(err) {
321 source = absSource
322 }
323 }
324 }
325 return func(filename string) error {
326 symlinkErr := os.Symlink(source, filename)
327
328 if symlinkErr != nil && !builderMustSupportLinks() {
329 // Probe to figure out whether Symlink failed because the Symlink
330 // operation isn't supported.
331 fullSource := source
332 if !filepath.IsAbs(source) {
333 // Compute the target path relative to the parent of filename, not the
334 // current working directory.
335 fullSource = filepath.Join(filename, "..", source)
336 }
337 stat, err := openAndStat(fullSource)
338 mode := os.ModePerm
339 if err == nil {
340 mode = stat.Mode()
341 } else if !errors.Is(err, os.ErrNotExist) {
342 // We couldn't open the source, but it might exist. We don't expect to be
343 // able to portably create a symlink to a file we can't see.
344 return symlinkErr
345 }
346
347 if err := createEmpty(filename, mode|0644); err == nil {
348 // Successfully opened the source (or verified that it does not exist) and
349 // created the destination, but we couldn't create it as a symlink.
350 // Probably the OS just doesn't support symlinks in this context.
351 return &os.PathError{Op: "Symlink", Path: filename, Err: ErrUnsupported}
352 }
353 }
354
355 return symlinkErr
356 }
357 }
358
359 // builderMustSupportLinks reports whether we are running on a Go builder
360 // that is known to support hard and symbolic links.
361 func builderMustSupportLinks() bool {
362 if os.Getenv("GO_BUILDER_NAME") == "" {
363 // Any OS can be configured to mount an exotic filesystem.
364 // Don't make assumptions about what users are running.
365 return false
366 }
367
368 switch runtime.GOOS {
369 case "windows", "plan9":
370 // Some versions of Windows and all versions of plan9 do not support
371 // symlinks by default.
372 return false
373
374 default:
375 // All other platforms should support symlinks by default, and our builders
376 // should not do anything unusual that would violate that.
377 return true
378 }
379 }
380
381 // openAndStat attempts to open source for reading.
382 func openAndStat(source string) (os.FileInfo, error) {
383 src, err := os.Open(source)
384 if err != nil {
385 return nil, err
386 }
387 stat, err := src.Stat()
388 src.Close()
389 if err != nil {
390 return nil, err
391 }
392 return stat, nil
393 }
394
395 // createEmpty creates an empty file or directory (depending on mode)
396 // at dst, with the same permissions as mode.
397 func createEmpty(dst string, mode os.FileMode) error {
398 if mode.IsDir() {
399 return os.Mkdir(dst, mode.Perm())
400 }
401
402 f, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_EXCL, mode.Perm())
403 if err != nil {
404 return err
405 }
406 if err := f.Close(); err != nil {
407 os.Remove(dst) // best-effort
408 return err
409 }
410
411 return nil
412 }
413
414 // Copy returns a Writer that copies a file from the specified source to the
415 // required file.
416 // This is used to copy testdata files into the generated testing tree.
417 func Copy(source string) Writer {
418 return func(filename string) error {
419 stat, err := os.Stat(source)
420 if err != nil {
421 return err
422 }
423 if !stat.Mode().IsRegular() {
424 // cannot copy non-regular files (e.g., directories,
425 // symlinks, devices, etc.)
426 return fmt.Errorf("cannot copy non regular file %s", source)
427 }
428 return copyFile(filename, source, stat.Mode().Perm())
429 }
430 }
431
432 func copyFile(dest, source string, perm os.FileMode) error {
433 src, err := os.Open(source)
434 if err != nil {
435 return err
436 }
437 defer src.Close()
438
439 dst, err := os.OpenFile(dest, os.O_WRONLY|os.O_CREATE|os.O_EXCL, perm)
440 if err != nil {
441 return err
442 }
443
444 _, err = io.Copy(dst, src)
445 if closeErr := dst.Close(); err == nil {
446 err = closeErr
447 }
448 return err
449 }
450
451 // GroupFilesByModules attempts to map directories to the modules within each directory.
452 // This function assumes that the folder is structured in the following way:
453 //
454 // dir/
455 // primarymod/
456 // *.go files
457 // packages
458 // go.mod (optional)
459 // modules/
460 // repoa/
461 // mod1/
462 // *.go files
463 // packages
464 // go.mod (optional)
465 //
466 // It scans the directory tree anchored at root and adds a Copy writer to the
467 // map for every file found.
468 // This is to enable the common case in tests where you have a full copy of the
469 // package in your testdata.
470 func GroupFilesByModules(root string) ([]Module, error) {
471 root = filepath.FromSlash(root)
472 primarymodPath := filepath.Join(root, "primarymod")
473
474 _, err := os.Stat(primarymodPath)
475 if os.IsNotExist(err) {
476 return nil, fmt.Errorf("could not find primarymod folder within %s", root)
477 }
478
479 primarymod := &Module{
480 Name: root,
481 Files: make(map[string]any),
482 Overlay: make(map[string][]byte),
483 }
484 mods := map[string]*Module{
485 root: primarymod,
486 }
487 modules := []Module{*primarymod}
488
489 if err := filepath.Walk(primarymodPath, func(path string, info os.FileInfo, err error) error {
490 if err != nil {
491 return err
492 }
493 if info.IsDir() {
494 return nil
495 }
496 fragment, err := filepath.Rel(primarymodPath, path)
497 if err != nil {
498 return err
499 }
500 primarymod.Files[filepath.ToSlash(fragment)] = Copy(path)
501 return nil
502 }); err != nil {
503 return nil, err
504 }
505
506 modulesPath := filepath.Join(root, "modules")
507 if _, err := os.Stat(modulesPath); os.IsNotExist(err) {
508 return modules, nil
509 }
510
511 var currentRepo, currentModule string
512 updateCurrentModule := func(dir string) {
513 if dir == currentModule {
514 return
515 }
516 // Handle the case where we step into a nested directory that is a module
517 // and then step out into the parent which is also a module.
518 // Example:
519 // - repoa
520 // - moda
521 // - go.mod
522 // - v2
523 // - go.mod
524 // - what.go
525 // - modb
526 for dir != root {
527 if mods[dir] != nil {
528 currentModule = dir
529 return
530 }
531 dir = filepath.Dir(dir)
532 }
533 }
534
535 if err := filepath.Walk(modulesPath, func(path string, info os.FileInfo, err error) error {
536 if err != nil {
537 return err
538 }
539 enclosingDir := filepath.Dir(path)
540 // If the path is not a directory, then we want to add the path to
541 // the files map of the currentModule.
542 if !info.IsDir() {
543 updateCurrentModule(enclosingDir)
544 fragment, err := filepath.Rel(currentModule, path)
545 if err != nil {
546 return err
547 }
548 mods[currentModule].Files[filepath.ToSlash(fragment)] = Copy(path)
549 return nil
550 }
551 // If the path is a directory and it's enclosing folder is equal to
552 // the modules folder, then the path is a new repo.
553 if enclosingDir == modulesPath {
554 currentRepo = path
555 return nil
556 }
557 // If the path is a directory and it's enclosing folder is not the same
558 // as the current repo and it is not of the form `v1`,`v2`,...
559 // then the path is a folder/package of the current module.
560 if enclosingDir != currentRepo && !versionSuffixRE.MatchString(filepath.Base(path)) {
561 return nil
562 }
563 // If the path is a directory and it's enclosing folder is the current repo
564 // then the path is a new module.
565 module, err := filepath.Rel(modulesPath, path)
566 if err != nil {
567 return err
568 }
569 mods[path] = &Module{
570 Name: filepath.ToSlash(module),
571 Files: make(map[string]any),
572 Overlay: make(map[string][]byte),
573 }
574 currentModule = path
575 modules = append(modules, *mods[path])
576 return nil
577 }); err != nil {
578 return nil, err
579 }
580 return modules, nil
581 }
582
583 // MustCopyFileTree returns a file set for a module based on a real directory tree.
584 // It scans the directory tree anchored at root and adds a Copy writer to the
585 // map for every file found. It skips copying files in nested modules.
586 // This is to enable the common case in tests where you have a full copy of the
587 // package in your testdata.
588 // This will panic if there is any kind of error trying to walk the file tree.
589 func MustCopyFileTree(root string) map[string]any {
590 result := map[string]any{}
591 if err := filepath.Walk(filepath.FromSlash(root), func(path string, info os.FileInfo, err error) error {
592 if err != nil {
593 return err
594 }
595 if info.IsDir() {
596 // skip nested modules.
597 if path != root {
598 if fi, err := os.Stat(filepath.Join(path, "go.mod")); err == nil && !fi.IsDir() {
599 return filepath.SkipDir
600 }
601 }
602 return nil
603 }
604 fragment, err := filepath.Rel(root, path)
605 if err != nil {
606 return err
607 }
608 result[filepath.ToSlash(fragment)] = Copy(path)
609 return nil
610 }); err != nil {
611 log.Panic(fmt.Sprintf("MustCopyFileTree failed: %v", err))
612 }
613 return result
614 }
615
616 // Cleanup removes the temporary directory (unless the --skip-cleanup flag was set)
617 // It is safe to call cleanup multiple times.
618 func (e *Exported) Cleanup() {
619 if e.temp == "" {
620 return
621 }
622 if *skipCleanup {
623 log.Printf("Skipping cleanup of temp dir: %s", e.temp)
624 return
625 }
626 // Make everything read-write so that the Module exporter's module cache can be deleted.
627 filepath.Walk(e.temp, func(path string, info os.FileInfo, err error) error {
628 if err != nil {
629 return nil
630 }
631 if info.IsDir() {
632 os.Chmod(path, 0777)
633 }
634 return nil
635 })
636 os.RemoveAll(e.temp) // ignore errors
637 e.temp = ""
638 }
639
640 // Temp returns the temporary directory that was generated.
641 func (e *Exported) Temp() string {
642 return e.temp
643 }
644
645 // File returns the full path for the given module and file fragment.
646 func (e *Exported) File(module, fragment string) string {
647 if m := e.written[module]; m != nil {
648 return m[fragment]
649 }
650 return ""
651 }
652
653 // FileContents returns the contents of the specified file.
654 // It will use the overlay if the file is present, otherwise it will read it
655 // from disk.
656 func (e *Exported) FileContents(filename string) ([]byte, error) {
657 if content, found := e.Config.Overlay[filename]; found {
658 return content, nil
659 }
660 content, err := os.ReadFile(filename)
661 if err != nil {
662 return nil, err
663 }
664 return content, nil
665 }