internal/deps/imports.go
83 lines · 1972 bytes
4 symbols in this file
1package deps
2
3import (
4 "context"
5 "go/parser"
6 "go/token"
7 "strconv"
8 "strings"
9
10 "gitbay.org/gitbay/internal/gitutil"
11 "gitbay.org/gitbay/internal/store"
12)
13
14// maxGoFiles bounds the Go files read for their imports. A repository with
15// more is not judged: its Go advisories are all reported.
16const maxGoFiles = 5000
17
18// GoImports returns the packages the Go files at sha import, tests
19// included, outside vendor and testdata. ok is false when they could not
20// all be read.
21func GoImports(ctx context.Context, dir, sha string) (map[string]bool, bool) {
22 entries, err := gitutil.ListBlobs(ctx, dir, sha)
23 if err != nil {
24 return nil, false
25 }
26 var shas []string
27 for _, e := range entries {
28 if !strings.HasSuffix(e.Name, ".go") || underAny(e.Name, "vendor", "testdata") {
29 continue
30 }
31 shas = append(shas, e.SHA)
32 }
33 if len(shas) > maxGoFiles {
34 return nil, false
35 }
36 out := map[string]bool{}
37 fset := token.NewFileSet()
38 err = gitutil.CatBlobs(ctx, dir, shas, func(_ int, data []byte) bool {
39 f, err := parser.ParseFile(fset, "", data, parser.ImportsOnly)
40 if err != nil {
41 return true // a file that does not parse does not build either
42 }
43 for _, imp := range f.Imports {
44 if p, err := strconv.Unquote(imp.Path.Value); err == nil {
45 out[p] = true
46 }
47 }
48 return true
49 })
50 if err != nil {
51 return nil, false
52 }
53 return out, true
54}
55
56func underAny(path string, dirs ...string) bool {
57 for _, part := range strings.Split(path, "/") {
58 for _, d := range dirs {
59 if part == d {
60 return true
61 }
62 }
63 }
64 return false
65}
66
67// MarkNotImported sets NotImported on each Go advisory that names packages
68// none of which imported holds.
69func MarkNotImported(matched []store.DepAdvisory, imported map[string]bool) {
70 for i, a := range matched {
71 if a.Ecosystem != EcoGo || len(a.Imports) == 0 {
72 continue
73 }
74 used := false
75 for _, p := range a.Imports {
76 if imported[p] {
77 used = true
78 break
79 }
80 }
81 matched[i].NotImported = !used
82 }
83}