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.
5 // Package gopathwalk is like filepath.Walk but specialized for finding Go
6 // packages, particularly in $GOPATH and $GOROOT.
20 "golang.org/x/tools/internal/fastwalk"
23 // Options controls the behavior of a Walk call.
25 // If Logf is non-nil, debug logging is enabled through this function.
26 Logf func(format string, args ...interface{})
27 // Search module caches. Also disables legacy goimports ignore rules.
31 // RootType indicates the type of a Root.
35 RootUnknown RootType = iota
43 // A Root is a starting point for a Walk.
49 // Walk walks Go source directories ($GOROOT, $GOPATH, etc) to find packages.
50 // For each package found, add will be called (concurrently) with the absolute
51 // paths of the containing source directory and the package directory.
52 // add will be called concurrently.
53 func Walk(roots []Root, add func(root Root, dir string), opts Options) {
54 WalkSkip(roots, add, func(Root, string) bool { return false }, opts)
57 // WalkSkip walks Go source directories ($GOROOT, $GOPATH, etc) to find packages.
58 // For each package found, add will be called (concurrently) with the absolute
59 // paths of the containing source directory and the package directory.
60 // For each directory that will be scanned, skip will be called (concurrently)
61 // with the absolute paths of the containing source directory and the directory.
62 // If skip returns false on a directory it will be processed.
63 // add will be called concurrently.
64 // skip will be called concurrently.
65 func WalkSkip(roots []Root, add func(root Root, dir string), skip func(root Root, dir string) bool, opts Options) {
66 for _, root := range roots {
67 walkDir(root, add, skip, opts)
71 // walkDir creates a walker and starts fastwalk with this walker.
72 func walkDir(root Root, add func(Root, string), skip func(root Root, dir string) bool, opts Options) {
73 if _, err := os.Stat(root.Path); os.IsNotExist(err) {
75 opts.Logf("skipping nonexistent directory: %v", root.Path)
81 opts.Logf("gopathwalk: scanning %s", root.Path)
90 if err := fastwalk.Walk(root.Path, w.walk); err != nil {
91 log.Printf("gopathwalk: scanning directory %v: %v", root.Path, err)
95 opts.Logf("gopathwalk: scanned %s in %v", root.Path, time.Since(start))
99 // walker is the callback for fastwalk.Walk.
101 root Root // The source directory to scan.
102 add func(Root, string) // The callback that will be invoked for every possible Go package dir.
103 skip func(Root, string) bool // The callback that will be invoked for every dir. dir is skipped if it returns true.
104 opts Options // Options passed to Walk by the user.
106 ignoredDirs []os.FileInfo // The ignored directories, loaded from .goimportsignore files.
109 // init initializes the walker based on its Options
110 func (w *walker) init() {
111 var ignoredPaths []string
112 if w.root.Type == RootModuleCache {
113 ignoredPaths = []string{"cache"}
115 if !w.opts.ModulesEnabled && w.root.Type == RootGOPATH {
116 ignoredPaths = w.getIgnoredDirs(w.root.Path)
117 ignoredPaths = append(ignoredPaths, "v", "mod")
120 for _, p := range ignoredPaths {
121 full := filepath.Join(w.root.Path, p)
122 if fi, err := os.Stat(full); err == nil {
123 w.ignoredDirs = append(w.ignoredDirs, fi)
124 if w.opts.Logf != nil {
125 w.opts.Logf("Directory added to ignore list: %s", full)
127 } else if w.opts.Logf != nil {
128 w.opts.Logf("Error statting ignored directory: %v", err)
133 // getIgnoredDirs reads an optional config file at <path>/.goimportsignore
134 // of relative directories to ignore when scanning for go files.
135 // The provided path is one of the $GOPATH entries with "src" appended.
136 func (w *walker) getIgnoredDirs(path string) []string {
137 file := filepath.Join(path, ".goimportsignore")
138 slurp, err := ioutil.ReadFile(file)
139 if w.opts.Logf != nil {
141 w.opts.Logf("%v", err)
143 w.opts.Logf("Read %s", file)
150 var ignoredDirs []string
151 bs := bufio.NewScanner(bytes.NewReader(slurp))
153 line := strings.TrimSpace(bs.Text())
154 if line == "" || strings.HasPrefix(line, "#") {
157 ignoredDirs = append(ignoredDirs, line)
162 // shouldSkipDir reports whether the file should be skipped or not.
163 func (w *walker) shouldSkipDir(fi os.FileInfo, dir string) bool {
164 for _, ignoredDir := range w.ignoredDirs {
165 if os.SameFile(fi, ignoredDir) {
170 // Check with the user specified callback.
171 return w.skip(w.root, dir)
176 // walk walks through the given path.
177 func (w *walker) walk(path string, typ os.FileMode) error {
178 dir := filepath.Dir(path)
180 if dir == w.root.Path && (w.root.Type == RootGOROOT || w.root.Type == RootGOPATH) {
181 // Doesn't make sense to have regular files
182 // directly in your $GOPATH/src or $GOROOT/src.
183 return fastwalk.ErrSkipFiles
185 if !strings.HasSuffix(path, ".go") {
190 return fastwalk.ErrSkipFiles
192 if typ == os.ModeDir {
193 base := filepath.Base(path)
194 if base == "" || base[0] == '.' || base[0] == '_' ||
195 base == "testdata" ||
196 (w.root.Type == RootGOROOT && w.opts.ModulesEnabled && base == "vendor") ||
197 (!w.opts.ModulesEnabled && base == "node_modules") {
198 return filepath.SkipDir
200 fi, err := os.Lstat(path)
201 if err == nil && w.shouldSkipDir(fi, path) {
202 return filepath.SkipDir
206 if typ == os.ModeSymlink {
207 base := filepath.Base(path)
208 if strings.HasPrefix(base, ".#") {
212 fi, err := os.Lstat(path)
217 if w.shouldTraverse(dir, fi) {
218 return fastwalk.ErrTraverseLink
224 // shouldTraverse reports whether the symlink fi, found in dir,
225 // should be followed. It makes sure symlinks were never visited
226 // before to avoid symlink loops.
227 func (w *walker) shouldTraverse(dir string, fi os.FileInfo) bool {
228 path := filepath.Join(dir, fi.Name())
229 target, err := filepath.EvalSymlinks(path)
233 ts, err := os.Stat(target)
235 fmt.Fprintln(os.Stderr, err)
241 if w.shouldSkipDir(ts, dir) {
244 // Check for symlink loops by statting each directory component
245 // and seeing if any are the same file as ts.
247 parent := filepath.Dir(path)
249 // Made it to the root without seeing a cycle.
253 parentInfo, err := os.Stat(parent)
257 if os.SameFile(ts, parentInfo) {
258 // Cycle. Don't traverse.