This repository has been archived by the owner on Jun 25, 2022. It is now read-only.
/
imports.go
210 lines (168 loc) · 4.36 KB
/
imports.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
package fix
import (
"bytes"
"fmt"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/pkg/errors"
"golang.org/x/tools/go/ast/astutil"
)
// ImportConverter will changes imports from a -> b
type ImportConverter struct {
Data map[string]string
}
// Process will walk all the .go files in an application, excluding ./vendor.
// It will then attempt to convert any old import paths to any new import paths
// used by this version Buffalo.
func (c ImportConverter) Process(r *Runner) error {
fmt.Println("~~~ Rewriting Imports ~~~")
err := filepath.Walk(".", c.processFile)
if err != nil {
return errors.WithStack(err)
}
if _, err := os.Stat("Gopkg.toml"); err != nil {
return nil
}
b, err := ioutil.ReadFile("Gopkg.toml")
if err != nil {
return errors.WithStack(err)
}
for k := range c.Data {
if bytes.Contains(b, []byte(k)) {
r.Warnings = append(r.Warnings, fmt.Sprintf("Your Gopkg.toml contains the following import that need to be changed MANUALLY: %s", k))
}
}
return nil
}
func (c ImportConverter) processFile(p string, info os.FileInfo, err error) error {
er := onlyRelevantFiles(p, info, err, func(p string) error {
err := c.rewriteFile(p)
if err != nil {
err = errors.WithStack(err)
}
return err
})
return er
}
func (c ImportConverter) rewriteFile(name string) error {
// create an empty fileset.
fset := token.NewFileSet()
// parse the .go file.
// we are parsing the entire file with comments, so we don't lose anything
// if we need to write it back out.
f, err := parser.ParseFile(fset, name, nil, parser.ParseComments)
if err != nil {
e := err.Error()
msg := "expected 'package', found 'EOF'"
if e[len(e)-len(msg):] == msg {
return nil
}
return err
}
changed := false
for key, value := range c.Data {
if !astutil.DeleteImport(fset, f, key) {
continue
}
astutil.AddImport(fset, f, value)
changed = true
}
commentsChanged, err := c.handleFileComments(f)
if err != nil {
return err
}
changed = changed || commentsChanged
// if no change occurred, then we don't need to write to disk, just return.
if !changed {
return nil
}
// since the imports changed, resort them.
ast.SortImports(fset, f)
// create a temporary file, this easily avoids conflicts.
temp, err := writeTempResult(name, fset, f)
if err != nil {
return err
}
// rename the .temp to .go
return os.Rename(temp, name)
}
func (c ImportConverter) handleFileComments(f *ast.File) (bool, error) {
change := false
for _, cg := range f.Comments {
for _, cl := range cg.List {
if !strings.HasPrefix(cl.Text, "// import \"") {
continue
}
// trim off extra comment stuff
ctext := cl.Text
ctext = strings.TrimPrefix(ctext, "// import")
ctext = strings.TrimSpace(ctext)
// unquote the comment import path value
ctext, err := strconv.Unquote(ctext)
if err != nil {
return false, err
}
// match the comment import path with the given replacement map
if ctext, ok := c.match(ctext); ok {
cl.Text = "// import " + strconv.Quote(ctext)
change = true
}
}
}
return change, nil
}
// match takes an import path and replacement map.
func (c ImportConverter) match(importpath string) (string, bool) {
for key, value := range c.Data {
if !strings.HasPrefix(importpath, key) {
continue
}
result := strings.Replace(importpath, key, value, 1)
return result, true
}
return importpath, false
}
//onlyRelevantFiles processes only .go files excluding folders like node_modules and vendor.
func onlyRelevantFiles(p string, fi os.FileInfo, err error, fn func(p string) error) error {
if err != nil {
return err
}
if fi.IsDir() {
return nil
}
for _, n := range []string{"vendor", "node_modules", ".git"} {
if strings.HasPrefix(p, n+string(filepath.Separator)) {
return nil
}
}
ext := filepath.Ext(p)
if ext != ".go" {
return nil
}
return fn(p)
}
func writeTempResult(name string, fset *token.FileSet, f *ast.File) (string, error) {
temp := name + ".temp"
w, err := os.Create(temp)
if err != nil {
return "", err
}
// write changes to .temp file, and include proper formatting.
err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(w, fset, f)
if err != nil {
return "", err
}
// close the writer
err = w.Close()
if err != nil {
return "", err
}
return temp, nil
}