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.
14 "cmd/go/internal/imports"
15 "cmd/go/internal/search"
17 "golang.org/x/mod/module"
23 omitStd = stdFilter(iota)
27 // matchPackages is like m.MatchPackages, but uses a local variable (rather than
28 // a global) for tags, can include or exclude packages in the standard library,
29 // and is restricted to the given list of modules.
30 func matchPackages(m *search.Match, tags map[string]bool, filter stdFilter, modules []module.Version) {
33 isMatch := func(string) bool { return true }
34 treeCanMatch := func(string) bool { return true }
36 isMatch = search.MatchPattern(m.Pattern())
37 treeCanMatch = search.TreeCanMatchPattern(m.Pattern())
40 have := map[string]bool{
41 "builtin": true, // ignore pseudo-package that exists only for documentation
43 if !cfg.BuildContext.CgoEnabled {
44 have["runtime/cgo"] = true // ignore during walk
49 pruneVendor = pruning(1 << iota)
53 walkPkgs := func(root, importPathRoot string, prune pruning) {
54 root = filepath.Clean(root)
55 err := filepath.Walk(root, func(path string, fi os.FileInfo, err error) error {
64 // Don't use GOROOT/src but do walk down into it.
66 if importPathRoot == "" {
70 // Avoid .foo, _foo, and testdata subdirectory trees.
71 _, elem = filepath.Split(path)
72 if strings.HasPrefix(elem, ".") || strings.HasPrefix(elem, "_") || elem == "testdata" {
77 name := importPathRoot + filepath.ToSlash(path[len(root):])
78 if importPathRoot == "" {
79 name = name[1:] // cut leading slash
81 if !treeCanMatch(name) {
86 if fi.Mode()&os.ModeSymlink != 0 && want {
87 if target, err := os.Stat(path); err == nil && target.IsDir() {
88 fmt.Fprintf(os.Stderr, "warning: ignoring symlink %s\n", path)
95 return filepath.SkipDir
97 // Stop at module boundaries.
98 if (prune&pruneGoMod != 0) && path != root {
99 if fi, err := os.Stat(filepath.Join(path, "go.mod")); err == nil && !fi.IsDir() {
100 return filepath.SkipDir
107 if _, _, err := scanDir(path, tags); err != imports.ErrNoGo {
108 m.Pkgs = append(m.Pkgs, name)
113 if elem == "vendor" && (prune&pruneVendor != 0) {
114 return filepath.SkipDir
123 if filter == includeStd {
124 walkPkgs(cfg.GOROOTsrc, "", pruneGoMod)
125 if treeCanMatch("cmd") {
126 walkPkgs(filepath.Join(cfg.GOROOTsrc, "cmd"), "cmd", pruneGoMod)
130 if cfg.BuildMod == "vendor" {
132 walkPkgs(ModRoot(), targetPrefix, pruneGoMod|pruneVendor)
133 walkPkgs(filepath.Join(ModRoot(), "vendor"), "", pruneVendor)
138 for _, mod := range modules {
139 if !treeCanMatch(mod.Path) {
144 root, modPrefix string
149 continue // If there is no main module, we can't search in it.
152 modPrefix = targetPrefix
156 root, isLocal, err = fetch(mod)
168 walkPkgs(root, modPrefix, prune)