forked from wusendong/gogimport
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
348 lines (310 loc) · 7.38 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
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package main
import (
"bufio"
"bytes"
"errors"
"flag"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/printer"
"go/token"
"io/ioutil"
"log"
"os"
"regexp"
"sort"
"strings"
)
const defaultLocal = "code.yunzhanghu.com"
var rootPkg = flag.String("local", "", "local package name")
func main() {
flag.Parse()
argIdx := 3
if *rootPkg == "" {
*rootPkg = defaultLocal
argIdx = 1
}
files := os.Args[argIdx:]
for _, fileName := range files {
formatFile(fileName)
}
}
func formatFile(fileName string) {
st := &Sorter{
filename: fileName,
rootPkg: *rootPkg,
}
log.Printf("sort import for %s %s", st.rootPkg, st.filename)
file, err := os.OpenFile(fileName, os.O_RDWR, 644)
if nil != err {
log.Printf("open file=%s err=%v", fileName, err)
}
defer func() {
err := file.Close()
if err != nil {
log.Printf("close file=%s, err=%v", fileName, err)
}
}()
err = st.init(file)
if err != nil {
log.Printf("init error: %v", err.Error())
return
}
st.sortImports()
st.addFuncNameComment()
st.addCommentSpace()
err = st.Write(file)
if err != nil {
log.Printf("write error %v", err.Error())
return
}
}
func (st *Sorter) sortImports() {
for _, d := range st.f.Decls {
d, ok := d.(*ast.GenDecl)
if !ok || d.Tok != token.IMPORT {
break
}
if !d.Lparen.IsValid() {
continue
}
cf := st.fset.File(st.f.Pos())
loffset := cf.Position(d.Lparen).Offset
roffset := cf.Position(d.Rparen).Offset
st.lines = deleteLinesRange(st.lines, loffset, roffset)
specs := d.Specs[:0]
specs = append(specs, st.sortSpecs(d.Specs[0:])...)
d.Specs = specs
}
}
func (st *Sorter) addFuncNameComment() {
for _, d := range st.f.Decls {
d, ok := d.(*ast.FuncDecl)
if !ok {
continue
}
// 没有日志的不处理
if d.Doc == nil {
continue
}
// 暂时只处理第一行,后续可以处理多行
for _, item := range d.Doc.List {
if !strings.HasPrefix(item.Text, "//") {
continue
}
if len(item.Text) == 2 {
item.Text = "// " + d.Name.Name + " "
break
}
sub := item.Text[2:]
if !strings.HasPrefix(sub, " ") {
sub = " " + sub
}
if !strings.HasPrefix(sub, " "+d.Name.Name) {
if regexp.MustCompile(fmt.Sprintf(`(?i)^ (%s)`, d.Name.Name)).MatchString(sub) {
sub = " " + d.Name.Name + sub[len(" "+d.Name.Name):]
} else {
sub = " " + d.Name.Name + sub[1:]
}
}
if !strings.HasPrefix(sub, " "+d.Name.Name+" ") {
sub = " " + d.Name.Name + " " + sub[len(" "+d.Name.Name):]
}
item.Text = "//" + sub
break
}
}
}
func (st *Sorter) addCommentSpace() {
for _, cg := range st.f.Comments {
for _, cm := range cg.List {
runeStr := []rune(cm.Text)
if strings.HasPrefix(cm.Text, "//") && len(runeStr) > 2 && runeStr[2] != ' ' {
runeStr = append(runeStr[:2], append([]rune{' '}, runeStr[2:]...)...)
cm.Text = string(runeStr)
}
}
}
}
func deleteLinesRange(lines []int, lline, rline int) []int {
nline := []int{}
for _, line := range lines {
if line >= lline && line <= rline {
continue
}
nline = append(nline, line)
}
return nline
}
func (st *Sorter) sortSpecs(specs []ast.Spec) (results []ast.Spec) {
innerPkg := []*ast.ImportSpec{}
thirdpartyPkg := []*ast.ImportSpec{}
appPkg := []*ast.ImportSpec{}
lowestPos := token.Pos(MaxInt)
for _, spec := range specs {
switch im := spec.(type) {
case *ast.ImportSpec:
if strings.HasPrefix(im.Path.Value, `"`+st.rootPkg) {
appPkg = append(appPkg, im)
} else if isThirdParty(im.Path.Value) {
thirdpartyPkg = append(thirdpartyPkg, im)
} else {
innerPkg = append(innerPkg, im)
}
if lowestPos >= im.Pos() {
lowestPos = im.Pos()
}
default:
log.Printf("default %v", im)
}
}
cf := st.fset.File(st.f.Pos())
// inner package first
for _, im := range innerPkg {
results = append(results, im)
lenth := im.End() - im.Pos()
setPos(lowestPos, im)
lowestPos += lenth
st.lines = addline(st.lines, cf.Position(plugPos(&lowestPos)).Offset)
lowestPos++
}
if len(innerPkg) > 0 {
st.lines = addline(st.lines, cf.Position(plugPos(&lowestPos)).Offset)
}
// local package second
for _, im := range appPkg {
results = append(results, im)
lenth := im.End() - im.Pos()
setPos(lowestPos, im)
lowestPos += lenth
st.lines = addline(st.lines, cf.Position(plugPos(&lowestPos)).Offset)
lowestPos++
}
if len(appPkg) > 0 {
st.lines = addline(st.lines, cf.Position(plugPos(&lowestPos)).Offset)
}
// third party third
for _, im := range thirdpartyPkg {
results = append(results, im)
lenth := im.End() - im.Pos()
setPos(lowestPos, im)
lowestPos += lenth
st.lines = addline(st.lines, cf.Position(plugPos(&lowestPos)).Offset)
lowestPos++
}
if len(thirdpartyPkg) > 0 {
st.lines = addline(st.lines, cf.Position(plugPos(&lowestPos)).Offset)
}
// verify validity of lines table
size := cf.Size()
for i, offset := range st.lines {
if i > 0 && offset <= st.lines[i-1] || size <= offset {
log.Printf("set line faile. %d, %d, %d, %d", i, offset, st.lines[i-1], size)
}
}
ok := cf.SetLines(st.lines)
if !ok {
log.Print("setlines failed\n")
}
return results
}
func plugPos(p *token.Pos) token.Pos {
*p = *p + 1
return *p
}
func (st *Sorter) init(file *os.File) error {
var err error
src, err := ioutil.ReadAll(file)
if err != nil {
return errors.New("read file " + st.filename + " error: " + err.Error())
}
src = append(src, []byte("\n\n\n")...)
st.lines, err = getLines(src)
if err != nil {
return err
}
parserMode := parser.ParseComments
st.fset = token.NewFileSet()
st.f, err = parser.ParseFile(st.fset, "", src, parserMode)
if err != nil {
log.Printf("parse file error :%s", err.Error())
return err
}
return nil
}
func (st *Sorter) Write(file *os.File) error {
var buf = &bytes.Buffer{}
if err := printer.Fprint(buf, st.fset, st.f); err != nil {
return err
}
out, err := format.Source(buf.Bytes())
if err != nil {
return err
}
_, err = file.Seek(0, 0)
if err != nil {
return err
}
err = file.Truncate(int64(buf.Len()))
if err != nil {
return err
}
_, err = file.Write(out)
return err
}
func setPos(pos token.Pos, im *ast.ImportSpec) {
if im.Name != nil {
im.Name.NamePos = pos
// log.Printf("set %v to %d", im.Path.Value, pos)
im.Path.ValuePos = im.Name.End() + 1
im.EndPos = im.Path.ValuePos + token.Pos(len(im.Path.Value))
return
}
// log.Printf("set %v to %d", im.Path.Value, pos)
im.Path.ValuePos = pos
im.EndPos = im.Path.ValuePos + token.Pos(len(im.Path.Value))
}
func getLines(data []byte) ([]int, error) {
rd := bufio.NewScanner(bytes.NewBuffer(data))
offset := 0
lines := []int{offset}
for rd.Scan() {
offset += len(rd.Bytes()) + 1
lines = append(lines, offset)
}
return lines[:len(lines)-1], nil
}
func addline(lines []int, offset ...int) []int {
lines = append(lines, offset...)
sort.Ints(lines)
return deduline(lines)
}
func deduline(lines []int) []int {
for index, line := range lines {
if index > 0 && lines[index-1] == line {
lines = append(lines[0:index-1], lines[index:]...)
}
}
return lines
}
var thirdPartRegex = regexp.MustCompile(`^"([0-9a-zA-Z]+\.)+[0-9a-zA-Z]+(/.+)+"$`)
func isThirdParty(path string) bool {
return thirdPartRegex.MatchString(path)
}
// Sorter gogimport sorter
type Sorter struct {
filename string
rootPkg string
lines []int
fset *token.FileSet
f *ast.File
}
// integer const
const (
MaxUint64 = ^uint64(0)
MaxInt64 = int64(MaxUint64 >> 1)
MaxUint = ^uint(0)
MaxInt = int(MaxUint >> 1)
)