forked from kesonan/goimportx
/
importx.go
324 lines (273 loc) · 7.08 KB
/
importx.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
322
323
324
package importx
import (
"bytes"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/printer"
"go/token"
"os"
"path/filepath"
"strings"
"github.com/golang-libs/goimportx/pkg/collection"
"golang.org/x/mod/modfile"
"golang.org/x/tools/go/ast/astutil"
)
const (
gomodFile = "go.mod"
groupNameSystem = "system"
groupNameLocal = "local"
groupNameThird = "third"
groupNameOthers = "others"
goExt = ".go"
)
var (
validGroupRule = map[string]struct{}{
groupNameSystem: {},
groupNameLocal: {},
groupNameThird: {},
groupNameOthers: {},
}
groupSort = map[string]int{
groupNameSystem: 0,
groupNameLocal: 1,
groupNameThird: 2,
groupNameOthers: 3,
}
)
// Sorter is the interface that wraps the basic Group and Sort method.
type Sorter interface {
Group(list []ImportPath) [][]ImportPath
Sort(list []ImportPath) []ImportPath
}
type commentGroup struct {
doc, comment *ast.CommentGroup
}
type commentGroups []*ast.CommentGroup
// ImportPath represents an import path with its name, value, use status, module path, and comment group.
type ImportPath struct {
name string
value string
use bool
modulePath string
commentGroup *commentGroup
}
func (cg commentGroups) in(comment *ast.CommentGroup) bool {
for _, v := range cg {
if v == nil {
continue
}
if comment.Pos() >= v.Pos() && comment.End() <= v.End() {
return true
}
}
return false
}
// PackageType returns the package type of the import path.
func (ip ImportPath) PackageType() string {
// Inspired by https://cs.opensource.google/go/x/tools/+/master:go/ast/astutil/imports.go;l=196
if len(ip.modulePath) > 0 && strings.HasPrefix(ip.value, ip.modulePath) {
return groupNameLocal
}
if strings.Contains(ip.value, ".") {
return groupNameThird
}
return groupNameSystem
}
// Sort reads the go.mod file in the same directory as the given file to determine the module path.
// The sorted imports will be written back to the file.
// If sorter implements io.Writer, the formatted file will be written to it instead of being written back to the file.
// If sorter is nil, use the default.
func Sort(filename string, sorter Sorter) ([]byte, error) {
if sorter == nil {
sorter = &ImportSorter{}
}
abs, err := filepath.Abs(filename)
if err != nil {
return nil, err
}
filename = abs
ext := filepath.Ext(filename)
if ext != goExt {
return nil, fmt.Errorf("expected go files, invalid file extension: %s", ext)
}
fileInfo, err := os.Stat(filename)
if err != nil {
return nil, err
}
if fileInfo.IsDir() {
return nil, fmt.Errorf("expected go files, invalid file path: %s", filename)
}
moduleFilename := getGoModFile(filename)
if len(moduleFilename) == 0 {
return nil, fmt.Errorf("can not find go.mod file")
}
data, err := os.ReadFile(moduleFilename)
if err != nil {
return nil, err
}
modFile, err := modfile.Parse(moduleFilename, data, nil)
if err != nil {
return nil, err
}
if modFile.Module == nil {
return nil, fmt.Errorf("invalid go.mod file: %s", moduleFilename)
}
modulePath := modFile.Module.Mod.Path
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, filename, nil, parser.ParseComments)
if err != nil {
return nil, err
}
importSet := collection.NewArraySet[ImportPath]()
importComment := make(map[string]*commentGroup)
var commentGroups commentGroups
importSpecIterator(f, modulePath, func(decl *ast.GenDecl, spec ast.Spec, path ImportPath) {
importSet.Add(path)
importComment[fmt.Sprintf("%s %s", path.name, path.value)] = path.commentGroup
commentGroups = append(commentGroups, path.commentGroup.doc, path.commentGroup.comment)
})
var specs []ast.Spec
var importUnGroupList = importSet.List()
var groupedImports = sorter.Group(importUnGroupList)
for idx, v := range groupedImports {
sortedImports := sorter.Sort(v)
for _, v := range sortedImports {
key := fmt.Sprintf("%s %s", v.name, v.value)
cg := importComment[key]
var doc, comment string
if cg != nil {
doc = getCommentGroupString(cg.doc)
comment = getCommentGroupString(cg.comment)
}
if len(doc) > 0 {
specs = append(specs, &ast.ImportSpec{
Path: &ast.BasicLit{Value: fmt.Sprintf("%s%s", "", doc), Kind: token.STRING},
})
}
var spec = ast.ImportSpec{
Path: &ast.BasicLit{Value: fmt.Sprintf(`"%s"%s`, v.value, comment), Kind: token.STRING},
}
if len(v.name) > 0 {
spec.Name = ast.NewIdent(v.name)
}
specs = append(specs, &spec)
}
if idx < len(groupedImports)-1 {
specs = append(specs, &ast.ImportSpec{
Path: &ast.BasicLit{Value: "", Kind: token.STRING},
})
}
}
rewriteImport(f, specs)
deletedOriginImportCommentGroup(f, commentGroups)
var buffer = bytes.NewBuffer(nil)
_ = printer.Fprint(buffer, fset, f)
result, err := format.Source(buffer.Bytes())
if err != nil {
return nil, err
}
return result, nil
}
func deletedOriginImportCommentGroup(f *ast.File, originCommentGroup commentGroups) {
var comments []*ast.CommentGroup
for _, d := range f.Comments {
if d == nil {
continue
}
if !originCommentGroup.in(d) {
comments = append(comments, d)
}
}
f.Comments = comments
}
func getCommentGroupString(commentGroup *ast.CommentGroup) string {
if commentGroup == nil {
return ""
}
var list []string
for _, v := range commentGroup.List {
list = append(list, v.Text)
}
return " " + strings.Join(list, " ")
}
func getGoModFile(file string) string {
var lastFile = filepath.Clean(file)
for {
dir := filepath.Dir(lastFile)
if lastFile == dir {
return ""
}
expectedGoModFile := filepath.Join(dir, gomodFile)
if _, err := os.Stat(expectedGoModFile); err == nil {
return expectedGoModFile
}
lastFile = dir
}
}
func rewriteImport(f *ast.File, specs []ast.Spec) {
var written bool
var decls []ast.Decl
for _, d := range f.Decls {
decl, ok := d.(*ast.GenDecl)
if ok && !written && isImportDecl(decl) {
decl.Specs = specs
if len(specs) == 1 {
decl.Lparen = 0
decl.Rparen = 0
}
written = true
decls = append(decls, decl)
} else {
decls = append(decls, d)
}
}
f.Decls = decls
}
func isImportDecl(decl *ast.GenDecl) bool {
for _, spec := range decl.Specs {
_, ok := spec.(*ast.ImportSpec)
if !ok {
return false
}
}
return true
}
func importSpecIterator(f *ast.File, modulePath string, iterator func(decl *ast.GenDecl, spec ast.Spec, path ImportPath)) {
for _, d := range f.Decls {
decl, ok := d.(*ast.GenDecl)
if !ok || decl.Tok != token.IMPORT {
continue
}
var newSpecs []ast.Spec
for _, spec := range decl.Specs {
newSpecs = append(newSpecs, spec)
imp, ok := spec.(*ast.ImportSpec)
if !ok {
continue
}
var name string
if imp.Name != nil {
name = imp.Name.String()
}
value := trimQuote(imp.Path.Value)
importPath := ImportPath{
name: name,
value: value,
use: astutil.UsesImport(f, value),
modulePath: modulePath,
commentGroup: &commentGroup{
doc: imp.Doc,
comment: imp.Comment,
},
}
iterator(decl, spec, importPath)
}
}
}
func trimQuote(s string) string {
return strings.TrimFunc(s, func(r rune) bool {
return r == '"' || r == '`'
})
}