Giant blob of minor changes
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / mvdan.cc / gofumpt@v0.0.0-20200802201014-ab5a8192947d / gofumports / internal / gopathwalk / walk.go
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.
4
5 // Package gopathwalk is like filepath.Walk but specialized for finding Go
6 // packages, particularly in $GOPATH and $GOROOT.
7 package gopathwalk
8
9 import (
10         "bufio"
11         "bytes"
12         "fmt"
13         "go/build"
14         "io/ioutil"
15         "log"
16         "os"
17         "path/filepath"
18         "strings"
19         "time"
20
21         "mvdan.cc/gofumpt/gofumports/internal/fastwalk"
22 )
23
24 // Options controls the behavior of a Walk call.
25 type Options struct {
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.
29         ModulesEnabled bool
30 }
31
32 // RootType indicates the type of a Root.
33 type RootType int
34
35 const (
36         RootUnknown RootType = iota
37         RootGOROOT
38         RootGOPATH
39         RootCurrentModule
40         RootModuleCache
41         RootOther
42 )
43
44 // A Root is a starting point for a Walk.
45 type Root struct {
46         Path string
47         Type RootType
48 }
49
50 // SrcDirsRoots returns the roots from build.Default.SrcDirs(). Not modules-compatible.
51 func SrcDirsRoots(ctx *build.Context) []Root {
52         var roots []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})
56         }
57         return roots
58 }
59
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)
66 }
67
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)
79         }
80 }
81
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) {
85                 if opts.Logf != nil {
86                         opts.Logf("skipping nonexistent directory: %v", root.Path)
87                 }
88                 return
89         }
90         start := time.Now()
91         if opts.Logf != nil {
92                 opts.Logf("gopathwalk: scanning %s", root.Path)
93         }
94         w := &walker{
95                 root: root,
96                 add:  add,
97                 skip: skip,
98                 opts: opts,
99         }
100         w.init()
101         if err := fastwalk.Walk(root.Path, w.walk); err != nil {
102                 log.Printf("gopathwalk: scanning directory %v: %v", root.Path, err)
103         }
104
105         if opts.Logf != nil {
106                 opts.Logf("gopathwalk: scanned %s in %v", root.Path, time.Since(start))
107         }
108 }
109
110 // walker is the callback for fastwalk.Walk.
111 type walker struct {
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.
116
117         ignoredDirs []os.FileInfo // The ignored directories, loaded from .goimportsignore files.
118 }
119
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"}
125         }
126         if !w.opts.ModulesEnabled && w.root.Type == RootGOPATH {
127                 ignoredPaths = w.getIgnoredDirs(w.root.Path)
128                 ignoredPaths = append(ignoredPaths, "v", "mod")
129         }
130
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)
137                         }
138                 } else if w.opts.Logf != nil {
139                         w.opts.Logf("Error statting ignored directory: %v", err)
140                 }
141         }
142 }
143
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 {
151                 if err != nil {
152                         w.opts.Logf("%v", err)
153                 } else {
154                         w.opts.Logf("Read %s", file)
155                 }
156         }
157         if err != nil {
158                 return nil
159         }
160
161         var ignoredDirs []string
162         bs := bufio.NewScanner(bytes.NewReader(slurp))
163         for bs.Scan() {
164                 line := strings.TrimSpace(bs.Text())
165                 if line == "" || strings.HasPrefix(line, "#") {
166                         continue
167                 }
168                 ignoredDirs = append(ignoredDirs, line)
169         }
170         return ignoredDirs
171 }
172
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) {
177                         return true
178                 }
179         }
180         if w.skip != nil {
181                 // Check with the user specified callback.
182                 return w.skip(w.root, dir)
183         }
184         return false
185 }
186
187 // walk walks through the given path.
188 func (w *walker) walk(path string, typ os.FileMode) error {
189         dir := filepath.Dir(path)
190         if typ.IsRegular() {
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
195                 }
196                 if !strings.HasSuffix(path, ".go") {
197                         return nil
198                 }
199
200                 w.add(w.root, dir)
201                 return fastwalk.ErrSkipFiles
202         }
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
210                 }
211                 fi, err := os.Lstat(path)
212                 if err == nil && w.shouldSkipDir(fi, path) {
213                         return filepath.SkipDir
214                 }
215                 return nil
216         }
217         if typ == os.ModeSymlink {
218                 base := filepath.Base(path)
219                 if strings.HasPrefix(base, ".#") {
220                         // Emacs noise.
221                         return nil
222                 }
223                 fi, err := os.Lstat(path)
224                 if err != nil {
225                         // Just ignore it.
226                         return nil
227                 }
228                 if w.shouldTraverse(dir, fi) {
229                         return fastwalk.ErrTraverseLink
230                 }
231         }
232         return nil
233 }
234
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)
241         if err != nil {
242                 return false
243         }
244         ts, err := os.Stat(target)
245         if err != nil {
246                 fmt.Fprintln(os.Stderr, err)
247                 return false
248         }
249         if !ts.IsDir() {
250                 return false
251         }
252         if w.shouldSkipDir(ts, dir) {
253                 return false
254         }
255         // Check for symlink loops by statting each directory component
256         // and seeing if any are the same file as ts.
257         for {
258                 parent := filepath.Dir(path)
259                 if parent == path {
260                         // Made it to the root without seeing a cycle.
261                         // Use this symlink.
262                         return true
263                 }
264                 parentInfo, err := os.Stat(parent)
265                 if err != nil {
266                         return false
267                 }
268                 if os.SameFile(ts, parentInfo) {
269                         // Cycle. Don't traverse.
270                         return false
271                 }
272                 path = parent
273         }
274 }