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.
20 "golang.org/x/tools/internal/gocommand"
23 // processGolistOverlay provides rudimentary support for adding
24 // files that don't exist on disk to an overlay. The results can be
25 // sometimes incorrect.
26 // TODO(matloob): Handle unsupported cases, including the following:
27 // - determining the correct package to add given a new import path
28 func (state *golistState) processGolistOverlay(response *responseDeduper) (modifiedPkgs, needPkgs []string, err error) {
29 havePkgs := make(map[string]string) // importPath -> non-test package ID
30 needPkgsSet := make(map[string]bool)
31 modifiedPkgsSet := make(map[string]bool)
33 pkgOfDir := make(map[string][]*Package)
34 for _, pkg := range response.dr.Packages {
35 // This is an approximation of import path to id. This can be
36 // wrong for tests, vendored packages, and a number of other cases.
37 havePkgs[pkg.PkgPath] = pkg.ID
38 x := commonDir(pkg.GoFiles)
40 pkgOfDir[x] = append(pkgOfDir[x], pkg)
44 // If no new imports are added, it is safe to avoid loading any needPkgs.
45 // Otherwise, it's hard to tell which package is actually being loaded
46 // (due to vendoring) and whether any modified package will show up
47 // in the transitive set of dependencies (because new imports are added,
48 // potentially modifying the transitive set of dependencies).
49 var overlayAddsImports bool
51 // If both a package and its test package are created by the overlay, we
52 // need the real package first. Process all non-test files before test
53 // files, and make the whole process deterministic while we're at it.
54 var overlayFiles []string
55 for opath := range state.cfg.Overlay {
56 overlayFiles = append(overlayFiles, opath)
58 sort.Slice(overlayFiles, func(i, j int) bool {
59 iTest := strings.HasSuffix(overlayFiles[i], "_test.go")
60 jTest := strings.HasSuffix(overlayFiles[j], "_test.go")
62 return !iTest // non-tests are before tests.
64 return overlayFiles[i] < overlayFiles[j]
66 for _, opath := range overlayFiles {
67 contents := state.cfg.Overlay[opath]
68 base := filepath.Base(opath)
69 dir := filepath.Dir(opath)
70 var pkg *Package // if opath belongs to both a package and its test variant, this will be the test variant
71 var testVariantOf *Package // if opath is a test file, this is the package it is testing
73 isTestFile := strings.HasSuffix(opath, "_test.go")
74 pkgName, ok := extractPackageName(opath, contents)
76 // Don't bother adding a file that doesn't even have a parsable package statement
80 // If all the overlay files belong to a different package, change the
81 // package name to that package.
82 maybeFixPackageName(pkgName, isTestFile, pkgOfDir[dir])
84 for _, p := range response.dr.Packages {
85 if pkgName != p.Name && p.ID != "command-line-arguments" {
88 for _, f := range p.GoFiles {
89 if !sameFile(filepath.Dir(f), dir) {
92 // Make sure to capture information on the package's test variant, if needed.
93 if isTestFile && !hasTestFiles(p) {
94 // TODO(matloob): Are there packages other than the 'production' variant
95 // of a package that this can match? This shouldn't match the test main package
96 // because the file is generated in another directory.
99 } else if !isTestFile && hasTestFiles(p) {
100 // We're examining a test variant, but the overlaid file is
101 // a non-test file. Because the overlay implementation
102 // (currently) only adds a file to one package, skip this
103 // package, so that we can add the file to the production
104 // variant of the package. (https://golang.org/issue/36857
105 // tracks handling overlays on both the production and test
106 // variant of a package).
109 if pkg != nil && p != pkg && pkg.PkgPath == p.PkgPath {
110 // We have already seen the production version of the
111 // for which p is a test variant.
117 if filepath.Base(f) == base {
122 // The overlay could have included an entirely new package or an
123 // ad-hoc package. An ad-hoc package is one that we have manually
124 // constructed from inadequate `go list` results for a file= query.
125 // It will have the ID command-line-arguments.
126 if pkg == nil || pkg.ID == "command-line-arguments" {
127 // Try to find the module or gopath dir the file is contained in.
128 // Then for modules, add the module opath to the beginning.
129 pkgPath, ok, err := state.getPkgPath(dir)
136 var forTest string // only set for x tests
137 isXTest := strings.HasSuffix(pkgName, "_test")
145 id = fmt.Sprintf("%s [%s.test]", pkgPath, forTest)
147 id = fmt.Sprintf("%s [%s.test]", pkgPath, pkgPath)
151 // TODO(rstambler): We should change the package's path and ID
152 // here. The only issue is that this messes with the roots.
154 // Try to reclaim a package with the same ID, if it exists in the response.
155 for _, p := range response.dr.Packages {
156 if reclaimPackage(p, id, opath, contents) {
161 // Otherwise, create a new package.
167 Imports: make(map[string]*Package),
169 response.addPackage(pkg)
170 havePkgs[pkg.PkgPath] = id
171 // Add the production package's sources for a test variant.
172 if isTestFile && !isXTest && testVariantOf != nil {
173 pkg.GoFiles = append(pkg.GoFiles, testVariantOf.GoFiles...)
174 pkg.CompiledGoFiles = append(pkg.CompiledGoFiles, testVariantOf.CompiledGoFiles...)
175 // Add the package under test and its imports to the test variant.
176 pkg.forTest = testVariantOf.PkgPath
177 for k, v := range testVariantOf.Imports {
178 pkg.Imports[k] = &Package{ID: v.ID}
182 pkg.forTest = forTest
188 pkg.GoFiles = append(pkg.GoFiles, opath)
189 // TODO(matloob): Adding the file to CompiledGoFiles can exhibit the wrong behavior
190 // if the file will be ignored due to its build tags.
191 pkg.CompiledGoFiles = append(pkg.CompiledGoFiles, opath)
192 modifiedPkgsSet[pkg.ID] = true
194 imports, err := extractImports(opath, contents)
196 // Let the parser or type checker report errors later.
199 for _, imp := range imports {
200 // TODO(rstambler): If the package is an x test and the import has
201 // a test variant, make sure to replace it.
202 if _, found := pkg.Imports[imp]; found {
205 overlayAddsImports = true
206 id, ok := havePkgs[imp]
209 id, err = state.resolveImport(dir, imp)
214 pkg.Imports[imp] = &Package{ID: id}
215 // Add dependencies to the non-test variant version of this package as well.
216 if testVariantOf != nil {
217 testVariantOf.Imports[imp] = &Package{ID: id}
222 // toPkgPath guesses the package path given the id.
223 toPkgPath := func(sourceDir, id string) (string, error) {
224 if i := strings.IndexByte(id, ' '); i >= 0 {
225 return state.resolveImport(sourceDir, id[:i])
227 return state.resolveImport(sourceDir, id)
230 // Now that new packages have been created, do another pass to determine
231 // the new set of missing packages.
232 for _, pkg := range response.dr.Packages {
233 for _, imp := range pkg.Imports {
234 if len(pkg.GoFiles) == 0 {
235 return nil, nil, fmt.Errorf("cannot resolve imports for package %q with no Go files", pkg.PkgPath)
237 pkgPath, err := toPkgPath(filepath.Dir(pkg.GoFiles[0]), imp.ID)
241 if _, ok := havePkgs[pkgPath]; !ok {
242 needPkgsSet[pkgPath] = true
247 if overlayAddsImports {
248 needPkgs = make([]string, 0, len(needPkgsSet))
249 for pkg := range needPkgsSet {
250 needPkgs = append(needPkgs, pkg)
253 modifiedPkgs = make([]string, 0, len(modifiedPkgsSet))
254 for pkg := range modifiedPkgsSet {
255 modifiedPkgs = append(modifiedPkgs, pkg)
257 return modifiedPkgs, needPkgs, err
260 // resolveImport finds the ID of a package given its import path.
261 // In particular, it will find the right vendored copy when in GOPATH mode.
262 func (state *golistState) resolveImport(sourceDir, importPath string) (string, error) {
263 env, err := state.getEnv()
267 if env["GOMOD"] != "" {
268 return importPath, nil
271 searchDir := sourceDir
273 vendorDir := filepath.Join(searchDir, "vendor")
274 exists, ok := state.vendorDirs[vendorDir]
276 info, err := os.Stat(vendorDir)
277 exists = err == nil && info.IsDir()
278 state.vendorDirs[vendorDir] = exists
282 vendoredPath := filepath.Join(vendorDir, importPath)
283 if info, err := os.Stat(vendoredPath); err == nil && info.IsDir() {
284 // We should probably check for .go files here, but shame on anyone who fools us.
285 path, ok, err := state.getPkgPath(vendoredPath)
295 // We know we've hit the top of the filesystem when we Dir / and get /,
296 // or C:\ and get C:\, etc.
297 next := filepath.Dir(searchDir)
298 if next == searchDir {
303 return importPath, nil
306 func hasTestFiles(p *Package) bool {
307 for _, f := range p.GoFiles {
308 if strings.HasSuffix(f, "_test.go") {
315 // determineRootDirs returns a mapping from absolute directories that could
316 // contain code to their corresponding import path prefixes.
317 func (state *golistState) determineRootDirs() (map[string]string, error) {
318 env, err := state.getEnv()
322 if env["GOMOD"] != "" {
323 state.rootsOnce.Do(func() {
324 state.rootDirs, state.rootDirsError = state.determineRootDirsModules()
327 state.rootsOnce.Do(func() {
328 state.rootDirs, state.rootDirsError = state.determineRootDirsGOPATH()
331 return state.rootDirs, state.rootDirsError
334 func (state *golistState) determineRootDirsModules() (map[string]string, error) {
335 // List all of the modules--the first will be the directory for the main
336 // module. Any replaced modules will also need to be treated as roots.
337 // Editing files in the module cache isn't a great idea, so we don't
338 // plan to ever support that.
339 out, err := state.invokeGo("list", "-m", "-json", "all")
341 // 'go list all' will fail if we're outside of a module and
342 // GO111MODULE=on. Try falling back without 'all'.
344 out, innerErr = state.invokeGo("list", "-m", "-json")
349 roots := map[string]string{}
350 modules := map[string]string{}
352 for dec := json.NewDecoder(out); dec.More(); {
353 mod := new(gocommand.ModuleJSON)
354 if err := dec.Decode(mod); err != nil {
357 if mod.Dir != "" && mod.Path != "" {
358 // This is a valid module; add it to the map.
359 absDir, err := filepath.Abs(mod.Dir)
363 modules[absDir] = mod.Path
364 // The first result is the main module.
365 if i == 0 || mod.Replace != nil && mod.Replace.Path != "" {
366 roots[absDir] = mod.Path
374 func (state *golistState) determineRootDirsGOPATH() (map[string]string, error) {
375 m := map[string]string{}
376 for _, dir := range filepath.SplitList(state.mustGetEnv()["GOPATH"]) {
377 absDir, err := filepath.Abs(dir)
381 m[filepath.Join(absDir, "src")] = ""
386 func extractImports(filename string, contents []byte) ([]string, error) {
387 f, err := parser.ParseFile(token.NewFileSet(), filename, contents, parser.ImportsOnly) // TODO(matloob): reuse fileset?
392 for _, imp := range f.Imports {
393 quotedPath := imp.Path.Value
394 path, err := strconv.Unquote(quotedPath)
398 res = append(res, path)
403 // reclaimPackage attempts to reuse a package that failed to load in an overlay.
405 // If the package has errors and has no Name, GoFiles, or Imports,
406 // then it's possible that it doesn't yet exist on disk.
407 func reclaimPackage(pkg *Package, id string, filename string, contents []byte) bool {
408 // TODO(rstambler): Check the message of the actual error?
409 // It differs between $GOPATH and module mode.
413 if len(pkg.Errors) != 1 {
416 if pkg.Name != "" || pkg.ExportFile != "" {
419 if len(pkg.GoFiles) > 0 || len(pkg.CompiledGoFiles) > 0 || len(pkg.OtherFiles) > 0 {
422 if len(pkg.Imports) > 0 {
425 pkgName, ok := extractPackageName(filename, contents)
434 func extractPackageName(filename string, contents []byte) (string, bool) {
435 // TODO(rstambler): Check the message of the actual error?
436 // It differs between $GOPATH and module mode.
437 f, err := parser.ParseFile(token.NewFileSet(), filename, contents, parser.PackageClauseOnly) // TODO(matloob): reuse fileset?
441 return f.Name.Name, true
444 func commonDir(a []string) string {
445 seen := make(map[string]bool)
446 x := append([]string{}, a...)
447 for _, f := range x {
448 seen[filepath.Dir(f)] = true
451 log.Fatalf("commonDir saw %v for %v", seen, x)
453 for k := range seen {
457 return "" // no files
460 // It is possible that the files in the disk directory dir have a different package
461 // name from newName, which is deduced from the overlays. If they all have a different
462 // package name, and they all have the same package name, then that name becomes
464 // It returns true if it changes the package name, false otherwise.
465 func maybeFixPackageName(newName string, isTestFile bool, pkgsOfDir []*Package) {
466 names := make(map[string]int)
467 for _, p := range pkgsOfDir {
471 // some files are in different packages
475 for k := range names {
478 if newName == oldName {
481 // We might have a case where all of the package names in the directory are
482 // the same, but the overlay file is for an x test, which belongs to its
483 // own package. If the x test does not yet exist on disk, we may not yet
484 // have its package name on disk, but we should not rename the packages.
486 // We use a heuristic to determine if this file belongs to an x test:
487 // The test file should have a package name whose package name has a _test
488 // suffix or looks like "newName_test".
489 maybeXTest := strings.HasPrefix(oldName+"_test", newName) || strings.HasSuffix(newName, "_test")
490 if isTestFile && maybeXTest {
493 for _, p := range pkgsOfDir {
498 // This function is copy-pasted from
499 // https://github.com/golang/go/blob/9706f510a5e2754595d716bd64be8375997311fb/src/cmd/go/internal/search/search.go#L360.
500 // It should be deleted when we remove support for overlays from go/packages.
502 // NOTE: This does not handle any ./... or ./ style queries, as this function
503 // doesn't know the working directory.
505 // matchPattern(pattern)(name) reports whether
506 // name matches pattern. Pattern is a limited glob
507 // pattern in which '...' means 'any string' and there
508 // is no other special syntax.
509 // Unfortunately, there are two special cases. Quoting "go help packages":
511 // First, /... at the end of the pattern can match an empty string,
512 // so that net/... matches both net and packages in its subdirectories, like net/http.
513 // Second, any slash-separated pattern element containing a wildcard never
514 // participates in a match of the "vendor" element in the path of a vendored
515 // package, so that ./... does not match packages in subdirectories of
516 // ./vendor or ./mycode/vendor, but ./vendor/... and ./mycode/vendor/... do.
517 // Note, however, that a directory named vendor that itself contains code
518 // is not a vendored package: cmd/vendor would be a command named vendor,
519 // and the pattern cmd/... matches it.
520 func matchPattern(pattern string) func(name string) bool {
521 // Convert pattern to regular expression.
522 // The strategy for the trailing /... is to nest it in an explicit ? expression.
523 // The strategy for the vendor exclusion is to change the unmatchable
524 // vendor strings to a disallowed code point (vendorChar) and to use
525 // "(anything but that codepoint)*" as the implementation of the ... wildcard.
526 // This is a bit complicated but the obvious alternative,
527 // namely a hand-written search like in most shell glob matchers,
528 // is too easy to make accidentally exponential.
529 // Using package regexp guarantees linear-time matching.
531 const vendorChar = "\x00"
533 if strings.Contains(pattern, vendorChar) {
534 return func(name string) bool { return false }
537 re := regexp.QuoteMeta(pattern)
538 re = replaceVendor(re, vendorChar)
540 case strings.HasSuffix(re, `/`+vendorChar+`/\.\.\.`):
541 re = strings.TrimSuffix(re, `/`+vendorChar+`/\.\.\.`) + `(/vendor|/` + vendorChar + `/\.\.\.)`
542 case re == vendorChar+`/\.\.\.`:
543 re = `(/vendor|/` + vendorChar + `/\.\.\.)`
544 case strings.HasSuffix(re, `/\.\.\.`):
545 re = strings.TrimSuffix(re, `/\.\.\.`) + `(/\.\.\.)?`
547 re = strings.ReplaceAll(re, `\.\.\.`, `[^`+vendorChar+`]*`)
549 reg := regexp.MustCompile(`^` + re + `$`)
551 return func(name string) bool {
552 if strings.Contains(name, vendorChar) {
555 return reg.MatchString(replaceVendor(name, vendorChar))
559 // replaceVendor returns the result of replacing
560 // non-trailing vendor path elements in x with repl.
561 func replaceVendor(x, repl string) string {
562 if !strings.Contains(x, "vendor") {
565 elem := strings.Split(x, "/")
566 for i := 0; i < len(elem)-1; i++ {
567 if elem[i] == "vendor" {
571 return strings.Join(elem, "/")