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.
21 "mvdan.cc/gofumpt/gofumports/internal/fastwalk"
24 // Options controls the behavior of a Walk call.
26 // If Logf is non-nil, debug logging is enabled through this function.
27 Logf func(format string, args ...interface{})
28 // Search module caches. Also disables legacy goimports ignore rules.
32 // RootType indicates the type of a Root.
36 RootUnknown RootType = iota
44 // A Root is a starting point for a Walk.
50 // SrcDirsRoots returns the roots from build.Default.SrcDirs(). Not modules-compatible.
51 func SrcDirsRoots(ctx *build.Context) []Root {
53 roots = append(roots, Root{filepath.Join(ctx.GOROOT, "src"), RootGOROOT})
54 for _, p := range filepath.SplitList(ctx.GOPATH) {
55 roots = append(roots, Root{filepath.Join(p, "src"), RootGOPATH})
60 // Walk walks Go source directories ($GOROOT, $GOPATH, etc) to find packages.
61 // For each package found, add will be called (concurrently) with the absolute
62 // paths of the containing source directory and the package directory.
63 // add will be called concurrently.
64 func Walk(roots []Root, add func(root Root, dir string), opts Options) {
65 WalkSkip(roots, add, func(Root, string) bool { return false }, opts)
68 // WalkSkip walks Go source directories ($GOROOT, $GOPATH, etc) to find packages.
69 // For each package found, add will be called (concurrently) with the absolute
70 // paths of the containing source directory and the package directory.
71 // For each directory that will be scanned, skip will be called (concurrently)
72 // with the absolute paths of the containing source directory and the directory.
73 // If skip returns false on a directory it will be processed.
74 // add will be called concurrently.
75 // skip will be called concurrently.
76 func WalkSkip(roots []Root, add func(root Root, dir string), skip func(root Root, dir string) bool, opts Options) {
77 for _, root := range roots {
78 walkDir(root, add, skip, opts)
82 // walkDir creates a walker and starts fastwalk with this walker.
83 func walkDir(root Root, add func(Root, string), skip func(root Root, dir string) bool, opts Options) {
84 if _, err := os.Stat(root.Path); os.IsNotExist(err) {
86 opts.Logf("skipping nonexistent directory: %v", root.Path)
92 opts.Logf("gopathwalk: scanning %s", root.Path)
101 if err := fastwalk.Walk(root.Path, w.walk); err != nil {
102 log.Printf("gopathwalk: scanning directory %v: %v", root.Path, err)
105 if opts.Logf != nil {
106 opts.Logf("gopathwalk: scanned %s in %v", root.Path, time.Since(start))
110 // walker is the callback for fastwalk.Walk.
112 root Root // The source directory to scan.
113 add func(Root, string) // The callback that will be invoked for every possible Go package dir.
114 skip func(Root, string) bool // The callback that will be invoked for every dir. dir is skipped if it returns true.
115 opts Options // Options passed to Walk by the user.
117 ignoredDirs []os.FileInfo // The ignored directories, loaded from .goimportsignore files.
120 // init initializes the walker based on its Options
121 func (w *walker) init() {
122 var ignoredPaths []string
123 if w.root.Type == RootModuleCache {
124 ignoredPaths = []string{"cache"}
126 if !w.opts.ModulesEnabled && w.root.Type == RootGOPATH {
127 ignoredPaths = w.getIgnoredDirs(w.root.Path)
128 ignoredPaths = append(ignoredPaths, "v", "mod")
131 for _, p := range ignoredPaths {
132 full := filepath.Join(w.root.Path, p)
133 if fi, err := os.Stat(full); err == nil {
134 w.ignoredDirs = append(w.ignoredDirs, fi)
135 if w.opts.Logf != nil {
136 w.opts.Logf("Directory added to ignore list: %s", full)
138 } else if w.opts.Logf != nil {
139 w.opts.Logf("Error statting ignored directory: %v", err)
144 // getIgnoredDirs reads an optional config file at <path>/.goimportsignore
145 // of relative directories to ignore when scanning for go files.
146 // The provided path is one of the $GOPATH entries with "src" appended.
147 func (w *walker) getIgnoredDirs(path string) []string {
148 file := filepath.Join(path, ".goimportsignore")
149 slurp, err := ioutil.ReadFile(file)
150 if w.opts.Logf != nil {
152 w.opts.Logf("%v", err)
154 w.opts.Logf("Read %s", file)
161 var ignoredDirs []string
162 bs := bufio.NewScanner(bytes.NewReader(slurp))
164 line := strings.TrimSpace(bs.Text())
165 if line == "" || strings.HasPrefix(line, "#") {
168 ignoredDirs = append(ignoredDirs, line)
173 // shouldSkipDir reports whether the file should be skipped or not.
174 func (w *walker) shouldSkipDir(fi os.FileInfo, dir string) bool {
175 for _, ignoredDir := range w.ignoredDirs {
176 if os.SameFile(fi, ignoredDir) {
181 // Check with the user specified callback.
182 return w.skip(w.root, dir)
187 // walk walks through the given path.
188 func (w *walker) walk(path string, typ os.FileMode) error {
189 dir := filepath.Dir(path)
191 if dir == w.root.Path && (w.root.Type == RootGOROOT || w.root.Type == RootGOPATH) {
192 // Doesn't make sense to have regular files
193 // directly in your $GOPATH/src or $GOROOT/src.
194 return fastwalk.ErrSkipFiles
196 if !strings.HasSuffix(path, ".go") {
201 return fastwalk.ErrSkipFiles
203 if typ == os.ModeDir {
204 base := filepath.Base(path)
205 if base == "" || base[0] == '.' || base[0] == '_' ||
206 base == "testdata" ||
207 (w.root.Type == RootGOROOT && w.opts.ModulesEnabled && base == "vendor") ||
208 (!w.opts.ModulesEnabled && base == "node_modules") {
209 return filepath.SkipDir
211 fi, err := os.Lstat(path)
212 if err == nil && w.shouldSkipDir(fi, path) {
213 return filepath.SkipDir
217 if typ == os.ModeSymlink {
218 base := filepath.Base(path)
219 if strings.HasPrefix(base, ".#") {
223 fi, err := os.Lstat(path)
228 if w.shouldTraverse(dir, fi) {
229 return fastwalk.ErrTraverseLink
235 // shouldTraverse reports whether the symlink fi, found in dir,
236 // should be followed. It makes sure symlinks were never visited
237 // before to avoid symlink loops.
238 func (w *walker) shouldTraverse(dir string, fi os.FileInfo) bool {
239 path := filepath.Join(dir, fi.Name())
240 target, err := filepath.EvalSymlinks(path)
244 ts, err := os.Stat(target)
246 fmt.Fprintln(os.Stderr, err)
252 if w.shouldSkipDir(ts, dir) {
255 // Check for symlink loops by statting each directory component
256 // and seeing if any are the same file as ts.
258 parent := filepath.Dir(path)
260 // Made it to the root without seeing a cycle.
264 parentInfo, err := os.Stat(parent)
268 if os.SameFile(ts, parentInfo) {
269 // Cycle. Don't traverse.