-
Notifications
You must be signed in to change notification settings - Fork 3
/
import.go
321 lines (279 loc) · 9.09 KB
/
import.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
package porto
import (
"bytes"
"errors"
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"path/filepath"
"regexp"
"strings"
)
var (
errMainPackage = errors.New("failed to add import to a main package")
errGenerated = errors.New("failed to add import to a generated file")
// Matches https://golang.org/s/generatedcode and cgo generated comment.
// Taken from https://github.com/golang/tools/blob/c5188f24a/refactor/rename/spec.go#L574-L576
generatedRx = regexp.MustCompile(`// .*DO NOT EDIT\.?`)
)
// isGeneratedFile reports whether ast.File is a generated file.
// Taken from https://github.com/golang/tools/blob/c5188f24a/refactor/rename/spec.go#L578-L593
func isGeneratedFile(pf *ast.File, tokenFile *token.File) bool {
// Iterate over the comments in the file
for _, commentGroup := range pf.Comments {
for _, comment := range commentGroup.List {
if matched := generatedRx.MatchString(comment.Text); matched {
// Check if comment is at the beginning of the line in source
if pos := tokenFile.Position(comment.Slash); pos.Column == 1 {
return true
}
}
}
}
return false
}
// addImportPath adds the vanity import path to a given go file.
func addImportPath(absFilepath string, module string) (bool, []byte, error) {
fset := token.NewFileSet()
pf, err := parser.ParseFile(fset, absFilepath, nil, parser.ParseComments)
if err != nil {
return false, nil, fmt.Errorf("failed to parse the file %q: %v", absFilepath, err)
}
packageName := pf.Name.String()
if packageName == "main" { // you can't import a main package
return false, nil, errMainPackage
}
// Skip generated files.
tokenFile := fset.File(pf.Pos())
if isGeneratedFile(pf, tokenFile) {
return false, nil, errGenerated
}
content, err := os.ReadFile(absFilepath)
if err != nil {
return false, nil, fmt.Errorf("failed to parse the file %q: %v", absFilepath, err)
}
// 9 = len("package ") + 1 because that is the first character of the package name
startPackageLinePos := int(pf.Name.NamePos) - 9
// first 1 = len(" ") as in "package " and the other 1 is for newline
endPackageLinePos := pf.Name.NamePos
newLineChar := byte(10)
for {
// we look for new lines in case we already had comments next to the package or
// another vanity import
if content[endPackageLinePos] == newLineChar {
break
}
endPackageLinePos++
}
importComment := []byte(" // import \"" + module + "\"")
newContent := []byte{}
if startPackageLinePos != 0 {
newContent = append(newContent, content[0:startPackageLinePos]...)
}
newContent = append(newContent, []byte("package "+packageName)...)
newContent = append(newContent, importComment...)
newContent = append(newContent, content[endPackageLinePos:]...)
return !bytes.Equal(content, newContent), newContent, nil
}
func isUnexportedModule(moduleName string, includeInternal bool) bool {
return !includeInternal && (strings.Contains(moduleName, "/internal/") ||
strings.HasSuffix(moduleName, "/internal"))
}
func findAndAddVanityImportForModuleDir(workingDir, baseAbsDir, absDir string, moduleName string, opts Options) (int, error) {
if isUnexportedModule(moduleName, opts.IncludeInternal) {
return 0, nil
}
files, err := os.ReadDir(absDir)
if err != nil {
return 0, fmt.Errorf("failed to read the content of %q: %v", absDir, err)
}
gc := 0
for _, f := range files {
if isDir, dirName := f.IsDir(), f.Name(); isDir {
var (
c int
err error
)
relDir := ""
if baseAbsDir != absDir {
relDir, err = filepath.Rel(baseAbsDir, absDir)
if err != nil {
return 0, fmt.Errorf("failed to resolve relative path: %v", err)
}
relDir += pathSeparator
}
if isUnexportedDir(dirName, opts.IncludeInternal) {
continue
} else if len(opts.RestrictToDirsRegexes) > 0 && !matchesAny(opts.RestrictToDirsRegexes, relDir+dirName) {
continue
} else if len(opts.SkipDirsRegexes) > 0 && matchesAny(opts.SkipDirsRegexes, relDir+dirName) {
continue
} else if newModuleName, ok := findGoModule(absDir + pathSeparator + dirName); ok {
// if folder contains go.mod we use it from now on to build the vanity import
c, err = findAndAddVanityImportForModuleDir(workingDir, baseAbsDir, absDir+pathSeparator+dirName, newModuleName, opts)
if err != nil {
return 0, err
}
} else {
// if not, we add the folder name to the vanity import
if c, err = findAndAddVanityImportForModuleDir(workingDir, baseAbsDir, absDir+pathSeparator+dirName, moduleName+"/"+dirName, opts); err != nil {
return 0, err
}
}
gc += c
} else if fileName := f.Name(); isGoFile(fileName) && !isGoTestFile(fileName) {
if !shouldEvaluate(opts, fileName) {
continue
}
absFilepath := absDir + pathSeparator + fileName
hasChanged, newContent, err := addImportPath(absDir+pathSeparator+fileName, moduleName)
if !hasChanged {
continue
}
switch err {
case nil:
err = handleNilErrorCase(opts, absFilepath, newContent, workingDir)
if err != nil {
return 0, err
}
gc++
case errMainPackage:
continue
default:
return 0, fmt.Errorf("failed to add vanity import path to %q: %v", absDir+pathSeparator+fileName, err)
}
}
}
return gc, nil
}
func shouldEvaluate(opts Options, fileName string) bool {
shouldEvaluate := true
if len(opts.RestrictToFilesRegexes) > 0 {
shouldEvaluate = matchesAny(opts.RestrictToFilesRegexes, fileName)
} else if len(opts.SkipFilesRegexes) > 0 {
shouldEvaluate = !matchesAny(opts.SkipFilesRegexes, fileName)
}
return shouldEvaluate
}
func handleNilErrorCase(opts Options, absFilepath string, newContent []byte, workingDir string) error {
if opts.WriteResultToFile {
err := writeContentToFile(absFilepath, newContent)
if err != nil {
return fmt.Errorf("failed to write file: %v", err)
}
} else if opts.ListDiffFiles {
relFilepath, err := filepath.Rel(workingDir, absFilepath)
if err != nil {
return fmt.Errorf("failed to resolve relative path: %v", err)
}
// TODO(jcchavezs): make this pluggable to allow different output formats
// and test assertions.
fmt.Printf("%s: missing right vanity import\n", relFilepath)
} else {
relFilepath, err := filepath.Rel(workingDir, absFilepath)
if err != nil {
return fmt.Errorf("failed to resolve relative path: %v", err)
}
fmt.Printf("👉 %s\n\n", relFilepath)
fmt.Println(string(newContent))
}
return nil
}
func matchesAny(regexes []*regexp.Regexp, str string) bool {
for _, fr := range regexes {
if matched := fr.MatchString(str); matched {
return true
}
}
return false
}
func findAndAddVanityImportForNonModuleDir(workingDir, baseAbsDir, absDir string, opts Options) (int, error) {
files, err := os.ReadDir(absDir)
if err != nil {
return 0, fmt.Errorf("failed to read %q: %v", absDir, err)
}
gc := 0
for _, f := range files {
if !f.IsDir() {
continue
}
dirName := f.Name()
if isUnexportedDir(dirName, opts.IncludeInternal) {
continue
}
var (
c int
err error
)
absDirName := absDir + pathSeparator + dirName
if moduleName, ok := findGoModule(absDirName); ok {
if c, err = findAndAddVanityImportForModuleDir(workingDir, baseAbsDir, dirName, moduleName, opts); err != nil {
return 0, err
}
} else {
if c, err = findAndAddVanityImportForNonModuleDir(workingDir, baseAbsDir, absDirName, opts); err != nil {
return 0, err
}
}
gc += c
}
return gc, nil
}
// Options represents the options for adding vanity import.
type Options struct {
// writes result to file directly
WriteResultToFile bool
// List files to be changed
ListDiffFiles bool
// Set of regex for matching files to be skipped
SkipFilesRegexes []*regexp.Regexp
// Set of regex for matching directories to be skipped
SkipDirsRegexes []*regexp.Regexp
// Include internal packages
IncludeInternal bool
// Set of regex for matching files to be included
RestrictToFilesRegexes []*regexp.Regexp
// Set of regex for matching dirs to be included
RestrictToDirsRegexes []*regexp.Regexp
}
// FindAndAddVanityImportForDir scans all files in a folder and based on go.mod files
// encountered decides wether add a vanity import or not.
func FindAndAddVanityImportForDir(workingDir, absDir string, opts Options) (int, error) {
if moduleName, ok := findGoModule(absDir); ok {
return findAndAddVanityImportForModuleDir(workingDir, absDir, absDir, moduleName, opts)
}
files, err := os.ReadDir(absDir)
if err != nil {
return 0, fmt.Errorf("failed to read the content of %q: %v", absDir, err)
}
gc := 0
for _, f := range files {
if !f.IsDir() {
// we already knew this is not a Go modules folder hence we are not looking
// for files but for directories
continue
}
dirName := f.Name()
if isUnexportedDir(dirName, opts.IncludeInternal) {
continue
}
var (
c int
err error
)
absDirName := absDir + pathSeparator + dirName
if moduleName, ok := findGoModule(absDirName); ok {
if c, err = findAndAddVanityImportForModuleDir(workingDir, absDir, dirName, moduleName, opts); err != nil {
return 0, err
}
} else {
if c, err = findAndAddVanityImportForNonModuleDir(workingDir, absDir, absDirName, opts); err != nil {
return 0, err
}
}
gc += c
}
return gc, nil
}