/
main.go
262 lines (231 loc) · 5.9 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
package main
import (
"bytes"
"fmt"
"go/ast"
"go/build"
"go/format"
"go/parser"
"go/token"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"strings"
"github.com/pkg/errors"
"github.com/spf13/pflag"
"golang.org/x/tools/go/loader"
"golang.org/x/tools/imports"
)
type options struct {
pkgs []string
dryRun bool
debug bool
cmpImportName string
showLoaderErrors bool
useAllFiles bool
}
func main() {
name := os.Args[0]
flags, opts := setupFlags(name)
handleExitError(name, flags.Parse(os.Args[1:]))
setupLogging(opts)
opts.pkgs = flags.Args()
handleExitError(name, run(*opts))
}
func setupLogging(opts *options) {
log.SetFlags(0)
enableDebug = opts.debug
}
var enableDebug = false
func debugf(msg string, args ...interface{}) {
if enableDebug {
log.Printf("DEBUG: "+msg, args...)
}
}
func setupFlags(name string) (*pflag.FlagSet, *options) {
opts := options{}
flags := pflag.NewFlagSet(name, pflag.ContinueOnError)
flags.BoolVar(&opts.dryRun, "dry-run", false,
"don't write changes to file")
flags.BoolVar(&opts.debug, "debug", false, "enable debug logging")
flags.StringVar(&opts.cmpImportName, "cmp-pkg-import-alias", "is",
"import alias to use for the assert/cmp package")
flags.BoolVar(&opts.showLoaderErrors, "print-loader-errors", false,
"print errors from loading source")
flags.BoolVar(&opts.useAllFiles, "ignore-build-tags", false,
"migrate all files ignoring build tags")
flags.Usage = func() {
fmt.Fprintf(os.Stderr, `Usage: %s [OPTIONS] PACKAGE [PACKAGE...]
Migrate calls from testify/{assert|require} to gotestyourself/assert.
%s`, name, flags.FlagUsages())
}
return flags, &opts
}
func handleExitError(name string, err error) {
switch {
case err == nil:
return
case err == pflag.ErrHelp:
os.Exit(0)
default:
log.Println(name + ": Error: " + err.Error())
os.Exit(3)
}
}
func run(opts options) error {
program, err := loadProgram(opts)
if err != nil {
return errors.Wrapf(err, "failed to load program")
}
pkgs := program.InitialPackages()
debugf("package count: %d", len(pkgs))
fileset := program.Fset
for _, pkg := range pkgs {
for _, astFile := range pkg.Files {
absFilename := fileset.File(astFile.Pos()).Name()
filename := relativePath(absFilename)
importNames := newImportNames(astFile.Imports, opts)
if !importNames.hasTestifyImports() {
debugf("skipping file %s, no imports", filename)
continue
}
debugf("migrating %s with imports: %#v", filename, importNames)
m := migration{
file: astFile,
fileset: fileset,
importNames: importNames,
pkgInfo: pkg,
}
migrateFile(m)
if opts.dryRun {
continue
}
raw, err := formatFile(m)
if err != nil {
return errors.Wrapf(err, "failed to format %s", filename)
}
if err := ioutil.WriteFile(absFilename, raw, 0); err != nil {
return errors.Wrapf(err, "failed to write file %s", filename)
}
}
}
return nil
}
func loadProgram(opts options) (*loader.Program, error) {
fakeImporter, err := newFakeImporter()
if err != nil {
return nil, err
}
defer fakeImporter.Cleanup()
conf := loader.Config{
Fset: token.NewFileSet(),
ParserMode: parser.ParseComments,
Build: buildContext(opts),
AllowErrors: true,
FindPackage: fakeImporter.Import,
}
for _, pkg := range opts.pkgs {
conf.ImportWithTests(pkg)
}
if !opts.showLoaderErrors {
conf.TypeChecker.Error = func(e error) {}
}
program, err := conf.Load()
if opts.showLoaderErrors {
for p, pkg := range program.AllPackages {
if len(pkg.Errors) > 0 {
fmt.Printf("Package %s loaded with some errors:\n", p.Name())
for _, err := range pkg.Errors {
fmt.Println(" ", err.Error())
}
}
}
}
return program, err
}
func buildContext(opts options) *build.Context {
c := build.Default
c.UseAllFiles = opts.useAllFiles
if val, ok := os.LookupEnv("GOPATH"); ok {
c.GOPATH = val
}
return &c
}
func relativePath(p string) string {
cwd, err := os.Getwd()
if err != nil {
return p
}
rel, err := filepath.Rel(cwd, p)
if err != nil {
return p
}
return rel
}
type importNames struct {
testifyAssert string
testifyRequire string
assert string
cmp string
}
func (p importNames) hasTestifyImports() bool {
return p.testifyAssert != "" || p.testifyRequire != ""
}
func (p importNames) matchesTestify(ident *ast.Ident) bool {
return ident.Name == p.testifyAssert || ident.Name == p.testifyRequire
}
func (p importNames) funcNameFromTestifyName(name string) string {
switch name {
case p.testifyAssert:
return funcNameCheck
case p.testifyRequire:
return funcNameAssert
default:
panic("unexpected testify import name " + name)
}
}
func newImportNames(imports []*ast.ImportSpec, opt options) importNames {
importNames := importNames{
assert: path.Base(pkgAssert),
cmp: path.Base(pkgCmp),
}
for _, spec := range imports {
switch strings.Trim(spec.Path.Value, `"`) {
case pkgTestifyAssert, pkgGopkgTestifyAssert:
importNames.testifyAssert = identOrDefault(spec.Name, "assert")
case pkgTestifyRequire, pkgGopkgTestifyRequire:
importNames.testifyRequire = identOrDefault(spec.Name, "require")
default:
if importedAs(spec, path.Base(pkgAssert)) {
importNames.assert = "gtyassert"
}
}
}
if opt.cmpImportName != "" {
importNames.cmp = opt.cmpImportName
}
return importNames
}
func importedAs(spec *ast.ImportSpec, pkg string) bool {
if path.Base(strings.Trim(spec.Path.Value, `""`)) == pkg {
return true
}
return spec.Name != nil && spec.Name.Name == pkg
}
func identOrDefault(ident *ast.Ident, def string) string {
if ident != nil {
return ident.Name
}
return def
}
func formatFile(migration migration) ([]byte, error) {
buf := new(bytes.Buffer)
err := format.Node(buf, migration.fileset, migration.file)
if err != nil {
return nil, err
}
filename := migration.fileset.File(migration.file.Pos()).Name()
return imports.Process(filename, buf.Bytes(), nil)
}