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.
21 "cmd/go/internal/fsys"
22 "cmd/go/internal/imports"
23 "cmd/go/internal/modindex"
25 "cmd/go/internal/search"
26 "cmd/go/internal/trace"
27 "cmd/internal/pkgpattern"
29 "golang.org/x/mod/module"
35 omitStd = stdFilter(iota)
39 // matchPackages is like m.MatchPackages, but uses a local variable (rather than
40 // a global) for tags, can include or exclude packages in the standard library,
41 // and is restricted to the given list of modules.
42 func matchPackages(ctx context.Context, m *search.Match, tags map[string]bool, filter stdFilter, modules []module.Version) {
43 ctx, span := trace.StartSpan(ctx, "modload.matchPackages")
48 isMatch := func(string) bool { return true }
49 treeCanMatch := func(string) bool { return true }
51 isMatch = pkgpattern.MatchPattern(m.Pattern())
52 treeCanMatch = pkgpattern.TreeCanMatchPattern(m.Pattern())
56 have := map[string]bool{
57 "builtin": true, // ignore pseudo-package that exists only for documentation
59 addPkg := func(p string) {
61 m.Pkgs = append(m.Pkgs, p)
64 if !cfg.BuildContext.CgoEnabled {
65 have["runtime/cgo"] = true // ignore during walk
70 pruneVendor = pruning(1 << iota)
74 q := par.NewQueue(runtime.GOMAXPROCS(0))
76 walkPkgs := func(root, importPathRoot string, prune pruning) {
77 _, span := trace.StartSpan(ctx, "walkPkgs "+root)
80 root = filepath.Clean(root)
81 err := fsys.Walk(root, func(pkgDir string, fi fs.FileInfo, err error) error {
90 // Don't use GOROOT/src but do walk down into it.
92 if importPathRoot == "" {
96 // Avoid .foo, _foo, and testdata subdirectory trees.
97 _, elem = filepath.Split(pkgDir)
98 if strings.HasPrefix(elem, ".") || strings.HasPrefix(elem, "_") || elem == "testdata" {
103 rel := strings.TrimPrefix(filepath.ToSlash(pkgDir[len(root):]), "/")
104 name := path.Join(importPathRoot, rel)
106 if !treeCanMatch(name) {
111 if fi.Mode()&fs.ModeSymlink != 0 && want && strings.Contains(m.Pattern(), "...") {
112 if target, err := fsys.Stat(pkgDir); err == nil && target.IsDir() {
113 fmt.Fprintf(os.Stderr, "warning: ignoring symlink %s\n", pkgDir)
120 return filepath.SkipDir
122 // Stop at module boundaries.
123 if (prune&pruneGoMod != 0) && pkgDir != root {
124 if fi, err := os.Stat(filepath.Join(pkgDir, "go.mod")); err == nil && !fi.IsDir() {
125 return filepath.SkipDir
133 if _, _, err := scanDir(root, pkgDir, tags); err != imports.ErrNoGo {
140 if elem == "vendor" && (prune&pruneVendor != 0) {
141 return filepath.SkipDir
150 // Wait for all in-flight operations to complete before returning.
153 sort.Strings(m.Pkgs) // sort everything we added for determinism
156 if filter == includeStd {
157 walkPkgs(cfg.GOROOTsrc, "", pruneGoMod)
158 if treeCanMatch("cmd") {
159 walkPkgs(filepath.Join(cfg.GOROOTsrc, "cmd"), "cmd", pruneGoMod)
163 if cfg.BuildMod == "vendor" {
164 mod := MainModules.mustGetSingleMainModule()
165 if modRoot := MainModules.ModRoot(mod); modRoot != "" {
166 walkPkgs(modRoot, MainModules.PathPrefix(mod), pruneGoMod|pruneVendor)
167 walkPkgs(filepath.Join(modRoot, "vendor"), "", pruneVendor)
172 for _, mod := range modules {
173 if !treeCanMatch(mod.Path) {
178 root, modPrefix string
181 if MainModules.Contains(mod.Path) {
182 if MainModules.ModRoot(mod) == "" {
183 continue // If there is no main module, we can't search in it.
185 root = MainModules.ModRoot(mod)
186 modPrefix = MainModules.PathPrefix(mod)
190 root, isLocal, err = fetch(ctx, mod)
197 if mi, err := modindex.GetModule(root); err == nil {
198 walkFromIndex(mi, modPrefix, isMatch, treeCanMatch, tags, have, addPkg)
200 } else if !errors.Is(err, modindex.ErrNotIndexed) {
208 walkPkgs(root, modPrefix, prune)
214 // walkFromIndex matches packages in a module using the module index. modroot
215 // is the module's root directory on disk, index is the modindex.Module for the
216 // module, and importPathRoot is the module's path prefix.
217 func walkFromIndex(index *modindex.Module, importPathRoot string, isMatch, treeCanMatch func(string) bool, tags, have map[string]bool, addPkg func(string)) {
218 index.Walk(func(reldir string) {
219 // Avoid .foo, _foo, and testdata subdirectory trees.
222 elem, rest, found := strings.Cut(p, string(filepath.Separator))
223 if strings.HasPrefix(elem, ".") || strings.HasPrefix(elem, "_") || elem == "testdata" {
226 if found && elem == "vendor" {
227 // Ignore this path if it contains the element "vendor" anywhere
228 // except for the last element (packages named vendor are allowed
229 // for historical reasons). Note that found is true when this
230 // isn't the last path element.
234 // Didn't find the separator, so we're considering the last element.
240 // Don't use GOROOT/src.
241 if reldir == "" && importPathRoot == "" {
245 name := path.Join(importPathRoot, filepath.ToSlash(reldir))
246 if !treeCanMatch(name) {
253 if _, _, err := index.Package(reldir).ScanDir(tags); err != imports.ErrNoGo {
261 // MatchInModule identifies the packages matching the given pattern within the
262 // given module version, which does not need to be in the build list or module
263 // requirement graph.
265 // If m is the zero module.Version, MatchInModule matches the pattern
266 // against the standard library (std and cmd) in GOROOT/src.
267 func MatchInModule(ctx context.Context, pattern string, m module.Version, tags map[string]bool) *search.Match {
268 match := search.NewMatch(pattern)
269 if m == (module.Version{}) {
270 matchPackages(ctx, match, tags, includeStd, nil)
273 LoadModFile(ctx) // Sets Target, needed by fetch and matchPackages.
275 if !match.IsLiteral() {
276 matchPackages(ctx, match, tags, omitStd, []module.Version{m})
280 root, isLocal, err := fetch(ctx, m)
282 match.Errs = []error{err}
286 dir, haveGoFiles, err := dirInModule(pattern, m.Path, root, isLocal)
288 match.Errs = []error{err}
292 if _, _, err := scanDir(root, dir, tags); err != imports.ErrNoGo {
293 // ErrNoGo indicates that the directory is not actually a Go package,
294 // perhaps due to the tags in use. Any other non-nil error indicates a
295 // problem with one or more of the Go source files, but such an error does
296 // not stop the package from existing, so it has no impact on matching.
297 match.Pkgs = []string{pattern}