forked from kovetskiy/manul
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimports.go
143 lines (116 loc) · 2.3 KB
/
imports.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package main
import (
"go/build"
"log"
"os"
"path/filepath"
"sort"
"strings"
)
func recursiveParseImports(
imports map[string]bool, path string, cwd string,
) error {
if path == "C" {
return nil
}
// catch internal vendoring in net/http since go 1.7
if strings.HasPrefix(path, "golang_org/") {
return nil
}
pkg, err := build.Import(path, cwd, build.IgnoreVendor)
if err != nil {
return err
}
if path != "." {
standard := false
if strings.HasPrefix(pkg.ImportPath, "golang.org/") ||
(pkg.Goroot && pkg.ImportPath != "") {
standard = true
}
imports[pkg.ImportPath] = standard
}
for _, importing := range pkg.Imports {
_, ok := imports[importing]
if !ok {
err = recursiveParseImports(imports, importing, cwd)
if err != nil {
return err
}
}
}
return nil
}
func parseImports(recursive bool) ([]string, error) {
cwd, err := os.Getwd()
if err != nil {
return nil, err
}
var (
allImports = map[string]bool{}
imports = []string{}
)
filepath.Walk(
cwd, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if filepath.Base(path) == ".git" ||
filepath.Dir(path) == filepath.Join(cwd, "vendor") {
return filepath.SkipDir
}
if path == filepath.Join(cwd, "vendor") {
return nil
}
if !info.IsDir() {
return nil
}
err = recursiveParseImports(
allImports,
".",
path,
)
if _, ok := err.(*build.NoGoError); ok {
return nil
}
if err != nil {
log.Println(err)
}
return nil
},
)
for importing, standard := range allImports {
if !standard {
importpath, err := getRootImportpath(importing)
if err != nil {
continue
}
if inTests {
importpath = strings.Replace(importpath, "__blankd__", "localhost:60001", -1)
}
if isOwnPackage(importpath, cwd) {
continue
}
found := false
for _, imported := range imports {
if importpath == imported {
found = true
break
}
}
if found {
continue
}
imports = append(imports, importpath)
}
}
sort.Strings(imports)
return imports, nil
}
func isOwnPackage(path, cwd string) bool {
for _, gopath := range filepath.SplitList(os.Getenv("GOPATH")) {
if strings.HasPrefix(filepath.Join(gopath, "src", path), cwd) {
return true
}
}
return false
}