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.
13 "cmd/go/internal/base"
15 "cmd/go/internal/imports"
16 "cmd/go/internal/module"
17 "cmd/go/internal/search"
20 // matchPackages returns a list of packages in the list of modules
21 // matching the pattern. Package loading assumes the given set of tags.
22 func matchPackages(pattern string, tags map[string]bool, useStd bool, modules []module.Version) []string {
23 match := func(string) bool { return true }
24 treeCanMatch := func(string) bool { return true }
25 if !search.IsMetaPackage(pattern) {
26 match = search.MatchPattern(pattern)
27 treeCanMatch = search.TreeCanMatchPattern(pattern)
30 have := map[string]bool{
31 "builtin": true, // ignore pseudo-package that exists only for documentation
33 if !cfg.BuildContext.CgoEnabled {
34 have["runtime/cgo"] = true // ignore during walk
40 pruneVendor = pruning(1 << iota)
44 walkPkgs := func(root, importPathRoot string, prune pruning) {
45 root = filepath.Clean(root)
46 filepath.Walk(root, func(path string, fi os.FileInfo, err error) error {
51 // Don't use GOROOT/src but do walk down into it.
52 if path == root && importPathRoot == "" {
57 // Avoid .foo, _foo, and testdata directory trees.
58 _, elem := filepath.Split(path)
59 if strings.HasPrefix(elem, ".") || strings.HasPrefix(elem, "_") || elem == "testdata" {
63 name := importPathRoot + filepath.ToSlash(path[len(root):])
64 if importPathRoot == "" {
65 name = name[1:] // cut leading slash
67 if !treeCanMatch(name) {
72 if fi.Mode()&os.ModeSymlink != 0 && want {
73 if target, err := os.Stat(path); err == nil && target.IsDir() {
74 fmt.Fprintf(os.Stderr, "warning: ignoring symlink %s\n", path)
81 return filepath.SkipDir
83 // Stop at module boundaries.
84 if (prune&pruneGoMod != 0) && path != root {
85 if fi, err := os.Stat(filepath.Join(path, "go.mod")); err == nil && !fi.IsDir() {
86 return filepath.SkipDir
93 if _, _, err := scanDir(path, tags); err != imports.ErrNoGo {
94 pkgs = append(pkgs, name)
99 if elem == "vendor" && (prune&pruneVendor != 0) {
100 return filepath.SkipDir
107 walkPkgs(cfg.GOROOTsrc, "", pruneGoMod)
108 if treeCanMatch("cmd") {
109 walkPkgs(filepath.Join(cfg.GOROOTsrc, "cmd"), "cmd", pruneGoMod)
113 if cfg.BuildMod == "vendor" {
115 walkPkgs(ModRoot(), targetPrefix, pruneGoMod|pruneVendor)
116 walkPkgs(filepath.Join(ModRoot(), "vendor"), "", pruneVendor)
121 for _, mod := range modules {
122 if !treeCanMatch(mod.Path) {
127 root, modPrefix string
132 continue // If there is no main module, we can't search in it.
135 modPrefix = targetPrefix
139 root, isLocal, err = fetch(mod)
141 base.Errorf("go: %v", err)
151 walkPkgs(root, modPrefix, prune)