-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
173 lines (144 loc) · 3.61 KB
/
main.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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package main
import (
"encoding/json"
"flag"
"fmt"
"go/parser"
"go/token"
"log"
"os"
"path/filepath"
"regexp"
"strings"
)
const usageDoc = `gogetimports: get a JSON-formatted map of imports per file
Usage:
gogetimports ARGS <directory>
Flags:
-only-third-parties return only third party imports
-list return a list instead of a map
-ignore ignore imports matching the given regular expression
-pretty output JSON with proper indentation
Examples:
gogetimports ./...
gogetimports -only-third-parties $GOPATH/src/github.com/cockroachdb/cockroach
gogetimports -ignore "jgautheron\/gocha" -list $GOPATH/src/github.com/jgautheron/gocha/...
gogetimports -pretty .
`
var (
flagThirdParties = flag.Bool("only-third-parties", false, "return only third party imports")
flagList = flag.Bool("list", false, "return a list instead of a map")
flagIgnore = flag.String("ignore", "", "ignore imports matching the given regular expression")
flagPretty = flag.Bool("pretty", false, "output JSON with proper indentation")
// imports contains the list of import path.
// filename[]import path
imports = map[string][]string{}
sourcePath = ""
)
func main() {
flag.Parse()
log.SetPrefix("gogetimports: ")
args := flag.Args()
if len(args) != 1 {
usage()
}
sourcePath = args[0]
if err := parseTree(); err != nil {
log.Println(err)
os.Exit(1)
}
removeDuplicates := func(list []string) []string {
encountered, result := map[string]bool{}, []string{}
for el := range list {
if _, ok := encountered[list[el]]; ok {
continue
}
encountered[list[el]] = true
result = append(result, list[el])
}
return result
}
var output interface{}
if *flagList {
lst := []string{}
for _, mp := range imports {
lst = append(lst, mp...)
}
output = removeDuplicates(lst)
} else {
output = imports
}
var o []byte
if *flagPretty {
o, _ = json.MarshalIndent(output, "", " ")
} else {
o, _ = json.Marshal(output)
}
fmt.Print(string(o))
}
func usage() {
fmt.Fprintf(os.Stderr, usageDoc)
os.Exit(1)
}
func parseTree() error {
pathLen := len(sourcePath)
// Parse recursively the given path if the recursive notation is found
if pathLen >= 5 && sourcePath[pathLen-3:] == "..." {
filepath.Walk(sourcePath[:pathLen-3], func(p string, f os.FileInfo, err error) error {
if err != nil {
log.Println(err)
// resume walking
return nil
}
if f.IsDir() {
parseDir(p)
}
return nil
})
} else {
parseDir(sourcePath)
}
return nil
}
func parseDir(dir string) error {
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, dir, nil, parser.ImportsOnly)
if err != nil {
return err
}
for _, pkg := range pkgs {
for fn, f := range pkg.Files {
if _, ok := imports[fn]; !ok {
imports[fn] = make([]string, 0)
}
for _, imprt := range f.Imports {
// Cleanup the import path
path := strings.Replace(imprt.Path.Value, `"`, "", 2)
if *flagThirdParties && !isThirdParty(path) {
continue
}
if len(*flagIgnore) != 0 {
match, err := regexp.MatchString(*flagIgnore, path)
if err != nil {
return err
}
if match {
continue
}
}
imports[fn] = append(imports[fn], path)
}
}
}
return nil
}
// isThirdParty determines if the given import path is a third party or not.
// It's safe to assume that if the first path of the import path looks like a domain name,
// then we're dealing with a third party.
func isThirdParty(path string) bool {
r, err := regexp.Compile(`^(\w+)\.(\w+)/`)
if err != nil {
return false
}
return r.MatchString(path)
}