Debian Codegraph @

resolve.go

raw symbols SCIP
1 package dots
2
3 import (
4 "go/build"
5 "log"
6 "os"
7 "path"
8 "path/filepath"
9 "regexp"
10 "runtime"
11 "strings"
12 )
13
14 var (
15 buildContext = build.Default
16 goroot = filepath.Clean(runtime.GOROOT())
17 gorootSrc = filepath.Join(goroot, "src")
18 )
19
20 func flatten(arr [][]string) []string {
21 var res []string
22 for _, e := range arr {
23 res = append(res, e...)
24 }
25 return res
26 }
27
28 // Resolve accepts a slice of paths with optional "..." placeholder and a slice with paths to be skipped.
29 // The final result is the set of all files from the selected directories subtracted with
30 // the files in the skip slice.
31 func Resolve(includePatterns, skipPatterns []string) ([]string, error) {
32 skip, err := resolvePatternsIgnoringErrors(skipPatterns)
33 filter := newPathFilter(flatten(skip))
34 if err != nil {
35 return nil, err
36 }
37
38 pathSet := map[string]bool{}
39 includePackages, err := resolvePatterns(includePatterns)
40 include := flatten(includePackages)
41 if err != nil {
42 return nil, err
43 }
44
45 var result []string
46 for _, i := range include {
47 if _, ok := pathSet[i]; !ok && !filter(i) {
48 pathSet[i] = true
49 result = append(result, i)
50 }
51 }
52 return result, err
53 }
54
55 // ResolvePackages accepts a slice of paths with optional "..." placeholder and a slice with paths to be skipped.
56 // The final result is the set of all files from the selected directories subtracted with
57 // the files in the skip slice. The difference between `Resolve` and `ResolvePackages`
58 // is that `ResolvePackages` preserves the package structure in the nested slices.
59 func ResolvePackages(includePatterns, skipPatterns []string) ([][]string, error) {
60 skip, err := resolvePatternsIgnoringErrors(skipPatterns)
61 filter := newPathFilter(flatten(skip))
62 if err != nil {
63 return nil, err
64 }
65
66 pathSet := map[string]bool{}
67 include, err := resolvePatterns(includePatterns)
68 if err != nil {
69 return nil, err
70 }
71
72 var result [][]string
73 for _, p := range include {
74 var packageFiles []string
75 for _, f := range p {
76 if _, ok := pathSet[f]; !ok && !filter(f) {
77 pathSet[f] = true
78 packageFiles = append(packageFiles, f)
79 }
80 }
81 result = append(result, packageFiles)
82 }
83 return result, err
84 }
85
86 func isDir(filename string) bool {
87 fi, err := os.Stat(filename)
88 return err == nil && fi.IsDir()
89 }
90
91 func exists(filename string) bool {
92 _, err := os.Stat(filename)
93 return err == nil
94 }
95
96 func resolveDir(dirname string) ([]string, error) {
97 pkg, err := build.ImportDir(dirname, 0)
98 return resolveImportedPackage(pkg, err)
99 }
100
101 func resolvePackage(pkgname string) ([]string, error) {
102 pkg, err := build.Import(pkgname, ".", 0)
103 return resolveImportedPackage(pkg, err)
104 }
105
106 func resolveImportedPackage(pkg *build.Package, err error) ([]string, error) {
107 if err != nil {
108 if _, nogo := err.(*build.NoGoError); nogo {
109 // Don't complain if the failure is due to no Go source files.
110 return nil, nil
111 }
112 return nil, err
113 }
114
115 var files []string
116 files = append(files, pkg.GoFiles...)
117 files = append(files, pkg.CgoFiles...)
118 files = append(files, pkg.TestGoFiles...)
119 files = append(files, pkg.XTestGoFiles...)
120 if pkg.Dir != "." {
121 for i, f := range files {
122 files[i] = filepath.Join(pkg.Dir, f)
123 }
124 }
125 return files, nil
126 }
127
128 func resolvePatterns(patterns []string) ([][]string, error) {
129 var files [][]string
130 for _, pattern := range patterns {
131 f, err := resolvePattern(pattern)
132 if err != nil {
133 return nil, err
134 }
135 files = append(files, f...)
136 }
137 return files, nil
138 }
139
140 func resolvePatternsIgnoringErrors(patterns []string) ([][]string, error) {
141 var files [][]string
142 for _, pattern := range patterns {
143 f, err := resolvePattern(pattern)
144 if err != nil {
145 continue
146 }
147 files = append(files, f...)
148 }
149 return files, nil
150 }
151
152 func resolvePattern(pattern string) ([][]string, error) {
153 // dirsRun, filesRun, and pkgsRun indicate whether golint is applied to
154 // directory, file or package targets. The distinction affects which
155 // checks are run. It is no valid to mix target types.
156 var dirsRun, filesRun, pkgsRun int
157 var matches []string
158
159 if strings.HasSuffix(pattern, "/...") && isDir(pattern[:len(pattern)-len("/...")]) {
160 dirsRun = 1
161 for _, dirname := range matchPackagesInFS(pattern) {
162 matches = append(matches, dirname)
163 }
164 } else if isDir(pattern) {
165 dirsRun = 1
166 matches = append(matches, pattern)
167 } else if exists(pattern) {
168 filesRun = 1
169 matches = append(matches, pattern)
170 } else {
171 pkgsRun = 1
172 matches = append(matches, pattern)
173 }
174
175 result := [][]string{}
176 switch {
177 case dirsRun == 1:
178 for _, dir := range matches {
179 res, err := resolveDir(dir)
180 if err != nil {
181 return nil, err
182 }
183 result = append(result, res)
184 }
185 case filesRun == 1:
186 return [][]string{matches}, nil
187 case pkgsRun == 1:
188 for _, pkg := range importPaths(matches) {
189 res, err := resolvePackage(pkg)
190 if err != nil {
191 return nil, err
192 }
193 result = append(result, res)
194 }
195 }
196 return result, nil
197 }
198
199 func newPathFilter(skip []string) func(string) bool {
200 filter := map[string]bool{}
201 for _, name := range skip {
202 filter[name] = true
203 }
204
205 return func(path string) bool {
206 base := filepath.Base(path)
207 if filter[base] || filter[path] {
208 return true
209 }
210 return base != "." && base != ".." && strings.ContainsAny(base[0:1], "_.")
211 }
212 }
213
214 // importPathsNoDotExpansion returns the import paths to use for the given
215 // command line, but it does no ... expansion.
216 func importPathsNoDotExpansion(args []string) []string {
217 if len(args) == 0 {
218 return []string{"."}
219 }
220 var out []string
221 for _, a := range args {
222 // Arguments are supposed to be import paths, but
223 // as a courtesy to Windows developers, rewrite \ to /
224 // in command-line arguments. Handles .\... and so on.
225 if filepath.Separator == '\\' {
226 a = strings.Replace(a, `\`, `/`, -1)
227 }
228
229 // Put argument in canonical form, but preserve leading ./.
230 if strings.HasPrefix(a, "./") {
231 a = "./" + path.Clean(a)
232 if a == "./." {
233 a = "."
234 }
235 } else {
236 a = path.Clean(a)
237 }
238 if a == "all" || a == "std" {
239 out = append(out, matchPackages(a)...)
240 continue
241 }
242 out = append(out, a)
243 }
244 return out
245 }
246
247 // importPaths returns the import paths to use for the given command line.
248 func importPaths(args []string) []string {
249 args = importPathsNoDotExpansion(args)
250 var out []string
251 for _, a := range args {
252 if strings.Contains(a, "...") {
253 if build.IsLocalImport(a) {
254 out = append(out, matchPackagesInFS(a)...)
255 } else {
256 out = append(out, matchPackages(a)...)
257 }
258 continue
259 }
260 out = append(out, a)
261 }
262 return out
263 }
264
265 // matchPattern(pattern)(name) reports whether
266 // name matches pattern. Pattern is a limited glob
267 // pattern in which '...' means 'any string' and there
268 // is no other special syntax.
269 func matchPattern(pattern string) func(name string) bool {
270 re := regexp.QuoteMeta(pattern)
271 re = strings.Replace(re, `\.\.\.`, `.*`, -1)
272 // Special case: foo/... matches foo too.
273 if strings.HasSuffix(re, `/.*`) {
274 re = re[:len(re)-len(`/.*`)] + `(/.*)?`
275 }
276 reg := regexp.MustCompile(`^` + re + `$`)
277 return func(name string) bool {
278 return reg.MatchString(name)
279 }
280 }
281
282 // hasPathPrefix reports whether the path s begins with the
283 // elements in prefix.
284 func hasPathPrefix(s, prefix string) bool {
285 switch {
286 default:
287 return false
288 case len(s) == len(prefix):
289 return s == prefix
290 case len(s) > len(prefix):
291 if prefix != "" && prefix[len(prefix)-1] == '/' {
292 return strings.HasPrefix(s, prefix)
293 }
294 return s[len(prefix)] == '/' && s[:len(prefix)] == prefix
295 }
296 }
297
298 // treeCanMatchPattern(pattern)(name) reports whether
299 // name or children of name can possibly match pattern.
300 // Pattern is the same limited glob accepted by matchPattern.
301 func treeCanMatchPattern(pattern string) func(name string) bool {
302 wildCard := false
303 if i := strings.Index(pattern, "..."); i >= 0 {
304 wildCard = true
305 pattern = pattern[:i]
306 }
307 return func(name string) bool {
308 return len(name) <= len(pattern) && hasPathPrefix(pattern, name) ||
309 wildCard && strings.HasPrefix(name, pattern)
310 }
311 }
312
313 func matchPackages(pattern string) []string {
314 match := func(string) bool { return true }
315 treeCanMatch := func(string) bool { return true }
316 if pattern != "all" && pattern != "std" {
317 match = matchPattern(pattern)
318 treeCanMatch = treeCanMatchPattern(pattern)
319 }
320
321 have := map[string]bool{
322 "builtin": true, // ignore pseudo-package that exists only for documentation
323 }
324 if !buildContext.CgoEnabled {
325 have["runtime/cgo"] = true // ignore during walk
326 }
327 var pkgs []string
328
329 // Commands
330 cmd := filepath.Join(goroot, "src/cmd") + string(filepath.Separator)
331 filepath.Walk(cmd, func(path string, fi os.FileInfo, err error) error {
332 if err != nil || !fi.IsDir() || path == cmd {
333 return nil
334 }
335 name := path[len(cmd):]
336 if !treeCanMatch(name) {
337 return filepath.SkipDir
338 }
339 // Commands are all in cmd/, not in subdirectories.
340 if strings.Contains(name, string(filepath.Separator)) {
341 return filepath.SkipDir
342 }
343
344 // We use, e.g., cmd/gofmt as the pseudo import path for gofmt.
345 name = "cmd/" + name
346 if have[name] {
347 return nil
348 }
349 have[name] = true
350 if !match(name) {
351 return nil
352 }
353 _, err = buildContext.ImportDir(path, 0)
354 if err != nil {
355 if _, noGo := err.(*build.NoGoError); !noGo {
356 log.Print(err)
357 }
358 return nil
359 }
360 pkgs = append(pkgs, name)
361 return nil
362 })
363
364 for _, src := range buildContext.SrcDirs() {
365 if (pattern == "std" || pattern == "cmd") && src != gorootSrc {
366 continue
367 }
368 src = filepath.Clean(src) + string(filepath.Separator)
369 root := src
370 if pattern == "cmd" {
371 root += "cmd" + string(filepath.Separator)
372 }
373 filepath.Walk(root, func(path string, fi os.FileInfo, err error) error {
374 if err != nil || !fi.IsDir() || path == src {
375 return nil
376 }
377
378 // Avoid .foo, _foo, and testdata directory trees.
379 _, elem := filepath.Split(path)
380 if strings.HasPrefix(elem, ".") || strings.HasPrefix(elem, "_") || elem == "testdata" {
381 return filepath.SkipDir
382 }
383
384 name := filepath.ToSlash(path[len(src):])
385 if pattern == "std" && (strings.Contains(name, ".") || name == "cmd") {
386 // The name "std" is only the standard library.
387 // If the name is cmd, it's the root of the command tree.
388 return filepath.SkipDir
389 }
390 if !treeCanMatch(name) {
391 return filepath.SkipDir
392 }
393 if have[name] {
394 return nil
395 }
396 have[name] = true
397 if !match(name) {
398 return nil
399 }
400 _, err = buildContext.ImportDir(path, 0)
401 if err != nil {
402 if _, noGo := err.(*build.NoGoError); noGo {
403 return nil
404 }
405 }
406 pkgs = append(pkgs, name)
407 return nil
408 })
409 }
410 return pkgs
411 }
412
413 func matchPackagesInFS(pattern string) []string {
414 // Find directory to begin the scan.
415 // Could be smarter but this one optimization
416 // is enough for now, since ... is usually at the
417 // end of a path.
418 i := strings.Index(pattern, "...")
419 dir, _ := path.Split(pattern[:i])
420
421 // pattern begins with ./ or ../.
422 // path.Clean will discard the ./ but not the ../.
423 // We need to preserve the ./ for pattern matching
424 // and in the returned import paths.
425 prefix := ""
426 if strings.HasPrefix(pattern, "./") {
427 prefix = "./"
428 }
429 match := matchPattern(pattern)
430
431 var pkgs []string
432 filepath.Walk(dir, func(path string, fi os.FileInfo, err error) error {
433 if err != nil || !fi.IsDir() {
434 return nil
435 }
436 if path == dir {
437 // filepath.Walk starts at dir and recurses. For the recursive case,
438 // the path is the result of filepath.Join, which calls filepath.Clean.
439 // The initial case is not Cleaned, though, so we do this explicitly.
440 //
441 // This converts a path like "./io/" to "io". Without this step, running
442 // "cd $GOROOT/src/pkg; go list ./io/..." would incorrectly skip the io
443 // package, because prepending the prefix "./" to the unclean path would
444 // result in "././io", and match("././io") returns false.
445 path = filepath.Clean(path)
446 }
447
448 // Avoid .foo, _foo, and testdata directory trees, but do not avoid "." or "..".
449 _, elem := filepath.Split(path)
450 dot := strings.HasPrefix(elem, ".") && elem != "." && elem != ".."
451 if dot || strings.HasPrefix(elem, "_") || elem == "testdata" {
452 return filepath.SkipDir
453 }
454
455 name := prefix + filepath.ToSlash(path)
456 if !match(name) {
457 return nil
458 }
459 if _, err = build.ImportDir(path, 0); err != nil {
460 if _, noGo := err.(*build.NoGoError); !noGo {
461 log.Print(err)
462 }
463 return nil
464 }
465 pkgs = append(pkgs, name)
466 return nil
467 })
468 return pkgs
469 }