forked from whyrusleeping/gx-go
/
rewrite.go
249 lines (206 loc) · 4.68 KB
/
rewrite.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
package rewrite
import (
"bufio"
"bytes"
"fmt"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"io"
"os"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
fs "github.com/kr/fs"
)
var bufpool = &sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
var cfg = &printer.Config{Mode: printer.UseSpaces | printer.TabIndent, Tabwidth: 8}
func RewriteImports(ipath string, rw func(string) string, filter func(string) bool) error {
path, err := filepath.EvalSymlinks(ipath)
if err != nil {
return err
}
var rwLock sync.Mutex
var wg sync.WaitGroup
torewrite := make(chan string)
for i := 0; i < runtime.NumCPU(); i++ {
wg.Add(1)
go func() {
defer wg.Done()
for path := range torewrite {
err := rewriteImportsInFile(path, rw, &rwLock)
if err != nil {
fmt.Println("rewrite error: ", err)
}
}
}()
}
w := fs.Walk(path)
for w.Step() {
rel := w.Path()[len(path):]
if len(rel) == 0 {
continue
}
rel = rel[1:]
if strings.HasPrefix(rel, ".git") || strings.HasPrefix(rel, "vendor") {
w.SkipDir()
continue
}
if !strings.HasSuffix(w.Path(), ".go") {
continue
}
if !filter(rel) {
continue
}
torewrite <- w.Path()
}
close(torewrite)
wg.Wait()
return nil
}
// inspired by godeps rewrite, rewrites import paths with gx vendored names
func rewriteImportsInFile(fi string, rw func(string) string, rwLock *sync.Mutex) error {
// 1. Rewrite the imports (if we have any)
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, fi, nil, parser.ParseComments|parser.ImportsOnly)
if err != nil {
return err
}
if len(file.Imports) == 0 {
return nil
}
oldImportsEnd := fset.Position(file.Imports[len(file.Imports)-1].End()).Offset
rwLock.Lock()
var changed bool
for _, imp := range file.Imports {
p, err := strconv.Unquote(imp.Path.Value)
if err != nil {
rwLock.Unlock()
return err
}
np := rw(p)
if np != p {
changed = true
imp.Path.Value = strconv.Quote(np)
}
}
rwLock.Unlock()
if !changed {
return nil
}
buf := bufpool.Get().(*bytes.Buffer)
defer func() {
bufpool.Put(buf)
}()
// Write them back to a temporary buffer
buf.Reset()
if err = cfg.Fprint(buf, fset, file); err != nil {
return err
}
// 2. Read the imports back in to sort them.
fset = token.NewFileSet()
file, err = parser.ParseFile(fset, fi, buf, parser.ParseComments|parser.ImportsOnly)
if err != nil {
return err
}
ast.SortImports(fset, file)
// Write them back to a temporary buffer
buf.Reset()
if err = cfg.Fprint(buf, fset, file); err != nil {
return err
}
// 3. Read them back in to find the new end of the imports.
fset = token.NewFileSet()
file, err = parser.ParseFile(fset, fi, buf, parser.ParseComments|parser.ImportsOnly)
if err != nil {
return err
}
newImportsEnd := fset.Position(file.Imports[len(file.Imports)-1].End()).Offset
// Write them back to the buffer and truncate.
buf.Reset()
if err = cfg.Fprint(buf, fset, file); err != nil {
return err
}
buf.Truncate(newImportsEnd)
// Finally, build the file.
tmppath := fi + ".temp"
tmp, err := os.Create(tmppath)
if err != nil {
return err
}
// Write the imports
_, err = buf.WriteTo(tmp)
if err != nil {
return err
}
// Copy the rest
src, err := os.Open(fi)
if err != nil {
return err
}
_, err = src.Seek(int64(oldImportsEnd), io.SeekStart)
if err != nil {
src.Close()
return err
}
_, err = io.Copy(tmp, src)
if err != nil {
src.Close()
return err
}
// Ignore any errors, we didn't modify this file.
src.Close()
// Update the file
if err = tmp.Close(); err != nil {
return err
}
return os.Rename(tmppath, fi)
}
func fixCanonicalImports(buf []byte) (bool, error) {
var i int
var changed bool
for {
n, tok, err := bufio.ScanLines(buf[i:], true)
if err != nil {
return false, err
}
if n == 0 {
return changed, nil
}
i += n
stripped := stripImportComment(tok)
if stripped != nil {
nstr := copy(tok, stripped)
copy(tok[nstr:], bytes.Repeat([]byte(" "), len(tok)-nstr))
changed = true
}
}
}
// more code from our friends over at godep
const (
importAnnotation = `import\s+(?:"[^"]*"|` + "`[^`]*`" + `)`
importComment = `(?://\s*` + importAnnotation + `\s*$|/\*\s*` + importAnnotation + `\s*\*/)`
)
var (
importCommentRE = regexp.MustCompile(`\s*(package\s+\w+)\s+` + importComment + `(.*)`)
pkgPrefix = []byte("package ")
)
func stripImportComment(line []byte) []byte {
if !bytes.HasPrefix(line, pkgPrefix) {
// Fast path; this will skip all but one line in the file.
// This assumes there is no whitespace before the keyword.
return nil
}
if m := importCommentRE.FindSubmatch(line); m != nil {
return append(m[1], m[2]...)
}
return nil
}