本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

269 lines
7.2KB

  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. // Package gopathwalk is like filepath.Walk but specialized for finding Go
  5. // packages, particularly in $GOPATH and $GOROOT.
  6. package gopathwalk
  7. import (
  8. "bufio"
  9. "bytes"
  10. "fmt"
  11. "go/build"
  12. "io/ioutil"
  13. "log"
  14. "os"
  15. "path/filepath"
  16. "strings"
  17. "golang.org/x/tools/internal/fastwalk"
  18. )
  19. // Options controls the behavior of a Walk call.
  20. type Options struct {
  21. Debug bool // Enable debug logging
  22. ModulesEnabled bool // Search module caches. Also disables legacy goimports ignore rules.
  23. }
  24. // RootType indicates the type of a Root.
  25. type RootType int
  26. const (
  27. RootUnknown RootType = iota
  28. RootGOROOT
  29. RootGOPATH
  30. RootCurrentModule
  31. RootModuleCache
  32. RootOther
  33. )
  34. // A Root is a starting point for a Walk.
  35. type Root struct {
  36. Path string
  37. Type RootType
  38. }
  39. // SrcDirsRoots returns the roots from build.Default.SrcDirs(). Not modules-compatible.
  40. func SrcDirsRoots(ctx *build.Context) []Root {
  41. var roots []Root
  42. roots = append(roots, Root{filepath.Join(ctx.GOROOT, "src"), RootGOROOT})
  43. for _, p := range filepath.SplitList(ctx.GOPATH) {
  44. roots = append(roots, Root{filepath.Join(p, "src"), RootGOPATH})
  45. }
  46. return roots
  47. }
  48. // Walk walks Go source directories ($GOROOT, $GOPATH, etc) to find packages.
  49. // For each package found, add will be called (concurrently) with the absolute
  50. // paths of the containing source directory and the package directory.
  51. // add will be called concurrently.
  52. func Walk(roots []Root, add func(root Root, dir string), opts Options) {
  53. WalkSkip(roots, add, func(Root, string) bool { return false }, opts)
  54. }
  55. // WalkSkip walks Go source directories ($GOROOT, $GOPATH, etc) to find packages.
  56. // For each package found, add will be called (concurrently) with the absolute
  57. // paths of the containing source directory and the package directory.
  58. // For each directory that will be scanned, skip will be called (concurrently)
  59. // with the absolute paths of the containing source directory and the directory.
  60. // If skip returns false on a directory it will be processed.
  61. // add will be called concurrently.
  62. // skip will be called concurrently.
  63. func WalkSkip(roots []Root, add func(root Root, dir string), skip func(root Root, dir string) bool, opts Options) {
  64. for _, root := range roots {
  65. walkDir(root, add, skip, opts)
  66. }
  67. }
  68. func walkDir(root Root, add func(Root, string), skip func(root Root, dir string) bool, opts Options) {
  69. if _, err := os.Stat(root.Path); os.IsNotExist(err) {
  70. if opts.Debug {
  71. log.Printf("skipping nonexistent directory: %v", root.Path)
  72. }
  73. return
  74. }
  75. if opts.Debug {
  76. log.Printf("scanning %s", root.Path)
  77. }
  78. w := &walker{
  79. root: root,
  80. add: add,
  81. skip: skip,
  82. opts: opts,
  83. }
  84. w.init()
  85. if err := fastwalk.Walk(root.Path, w.walk); err != nil {
  86. log.Printf("gopathwalk: scanning directory %v: %v", root.Path, err)
  87. }
  88. if opts.Debug {
  89. log.Printf("scanned %s", root.Path)
  90. }
  91. }
  92. // walker is the callback for fastwalk.Walk.
  93. type walker struct {
  94. root Root // The source directory to scan.
  95. add func(Root, string) // The callback that will be invoked for every possible Go package dir.
  96. skip func(Root, string) bool // The callback that will be invoked for every dir. dir is skipped if it returns true.
  97. opts Options // Options passed to Walk by the user.
  98. ignoredDirs []os.FileInfo // The ignored directories, loaded from .goimportsignore files.
  99. }
  100. // init initializes the walker based on its Options.
  101. func (w *walker) init() {
  102. var ignoredPaths []string
  103. if w.root.Type == RootModuleCache {
  104. ignoredPaths = []string{"cache"}
  105. }
  106. if !w.opts.ModulesEnabled && w.root.Type == RootGOPATH {
  107. ignoredPaths = w.getIgnoredDirs(w.root.Path)
  108. ignoredPaths = append(ignoredPaths, "v", "mod")
  109. }
  110. for _, p := range ignoredPaths {
  111. full := filepath.Join(w.root.Path, p)
  112. if fi, err := os.Stat(full); err == nil {
  113. w.ignoredDirs = append(w.ignoredDirs, fi)
  114. if w.opts.Debug {
  115. log.Printf("Directory added to ignore list: %s", full)
  116. }
  117. } else if w.opts.Debug {
  118. log.Printf("Error statting ignored directory: %v", err)
  119. }
  120. }
  121. }
  122. // getIgnoredDirs reads an optional config file at <path>/.goimportsignore
  123. // of relative directories to ignore when scanning for go files.
  124. // The provided path is one of the $GOPATH entries with "src" appended.
  125. func (w *walker) getIgnoredDirs(path string) []string {
  126. file := filepath.Join(path, ".goimportsignore")
  127. slurp, err := ioutil.ReadFile(file)
  128. if w.opts.Debug {
  129. if err != nil {
  130. log.Print(err)
  131. } else {
  132. log.Printf("Read %s", file)
  133. }
  134. }
  135. if err != nil {
  136. return nil
  137. }
  138. var ignoredDirs []string
  139. bs := bufio.NewScanner(bytes.NewReader(slurp))
  140. for bs.Scan() {
  141. line := strings.TrimSpace(bs.Text())
  142. if line == "" || strings.HasPrefix(line, "#") {
  143. continue
  144. }
  145. ignoredDirs = append(ignoredDirs, line)
  146. }
  147. return ignoredDirs
  148. }
  149. func (w *walker) shouldSkipDir(fi os.FileInfo, dir string) bool {
  150. for _, ignoredDir := range w.ignoredDirs {
  151. if os.SameFile(fi, ignoredDir) {
  152. return true
  153. }
  154. }
  155. if w.skip != nil {
  156. // Check with the user specified callback.
  157. return w.skip(w.root, dir)
  158. }
  159. return false
  160. }
  161. func (w *walker) walk(path string, typ os.FileMode) error {
  162. dir := filepath.Dir(path)
  163. if typ.IsRegular() {
  164. if dir == w.root.Path && (w.root.Type == RootGOROOT || w.root.Type == RootGOPATH) {
  165. // Doesn't make sense to have regular files
  166. // directly in your $GOPATH/src or $GOROOT/src.
  167. return fastwalk.SkipFiles
  168. }
  169. if !strings.HasSuffix(path, ".go") {
  170. return nil
  171. }
  172. w.add(w.root, dir)
  173. return fastwalk.SkipFiles
  174. }
  175. if typ == os.ModeDir {
  176. base := filepath.Base(path)
  177. if base == "" || base[0] == '.' || base[0] == '_' ||
  178. base == "testdata" ||
  179. (w.root.Type == RootGOROOT && w.opts.ModulesEnabled && base == "vendor") ||
  180. (!w.opts.ModulesEnabled && base == "node_modules") {
  181. return filepath.SkipDir
  182. }
  183. fi, err := os.Lstat(path)
  184. if err == nil && w.shouldSkipDir(fi, path) {
  185. return filepath.SkipDir
  186. }
  187. return nil
  188. }
  189. if typ == os.ModeSymlink {
  190. base := filepath.Base(path)
  191. if strings.HasPrefix(base, ".#") {
  192. // Emacs noise.
  193. return nil
  194. }
  195. fi, err := os.Lstat(path)
  196. if err != nil {
  197. // Just ignore it.
  198. return nil
  199. }
  200. if w.shouldTraverse(dir, fi) {
  201. return fastwalk.TraverseLink
  202. }
  203. }
  204. return nil
  205. }
  206. // shouldTraverse reports whether the symlink fi, found in dir,
  207. // should be followed. It makes sure symlinks were never visited
  208. // before to avoid symlink loops.
  209. func (w *walker) shouldTraverse(dir string, fi os.FileInfo) bool {
  210. path := filepath.Join(dir, fi.Name())
  211. target, err := filepath.EvalSymlinks(path)
  212. if err != nil {
  213. return false
  214. }
  215. ts, err := os.Stat(target)
  216. if err != nil {
  217. fmt.Fprintln(os.Stderr, err)
  218. return false
  219. }
  220. if !ts.IsDir() {
  221. return false
  222. }
  223. if w.shouldSkipDir(ts, dir) {
  224. return false
  225. }
  226. // Check for symlink loops by statting each directory component
  227. // and seeing if any are the same file as ts.
  228. for {
  229. parent := filepath.Dir(path)
  230. if parent == path {
  231. // Made it to the root without seeing a cycle.
  232. // Use this symlink.
  233. return true
  234. }
  235. parentInfo, err := os.Stat(parent)
  236. if err != nil {
  237. return false
  238. }
  239. if os.SameFile(ts, parentInfo) {
  240. // Cycle. Don't traverse.
  241. return false
  242. }
  243. path = parent
  244. }
  245. }
上海开阖软件有限公司 沪ICP备12045867号-1