/
rewrite.go
97 lines (85 loc) · 2.58 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
package rewriter
import (
"fmt"
"go/types"
"log"
"strings"
"github.com/goghcrow/go-loader"
"github.com/goghcrow/go-try/rewriter/helper"
)
type (
Option func(*option)
option struct {
fileSuffix string
buildTag string
}
)
func WithFileSuffix(s string) Option { return func(opt *option) { opt.fileSuffix = s } }
func WithBuildTag(s string) Option { return func(opt *option) { opt.buildTag = s } }
func Rewrite(dir string, opts ...Option) {
opt := &option{
fileSuffix: defaultFileSuffix,
buildTag: defaultBuildTag,
}
for _, o := range opts {
o(opt)
}
var (
endsWith = strings.HasSuffix
replace = strings.ReplaceAll
srcFileSuffix = fmt.Sprintf("_%s.go", opt.fileSuffix)
testFileSuffix = fmt.Sprintf("_%s_test.go", opt.fileSuffix)
isTryFile = func(filename string) bool {
return endsWith(filename, srcFileSuffix) || endsWith(filename, testFileSuffix)
}
toOptimize = map[string]bool{}
)
rewrite(loader.MustNew(
dir,
loader.WithLoadDepts(),
loader.WithLoadTest(),
loader.WithBuildTag(opt.buildTag),
loader.WithFileFilter(func(f *loader.File) bool {
return isTryFile(f.Filename) && helper.Imported(f.File, pkgTryPath)
}),
), func(filename string, f *loader.File) {
filename = replace(filename, srcFileSuffix, ".go")
filename = replace(filename, testFileSuffix, "_test.go")
f.Write(filename)
toOptimize[filename] = true
})
optimize(loader.MustNew(
dir,
loader.WithLoadDepts(),
loader.WithLoadTest(),
loader.WithBuildTag("!"+opt.buildTag),
loader.WithFileFilter(func(f *loader.File) bool {
return toOptimize[f.Filename] // && helper.Imported(f.File, pkgRTPath)
}),
), func(filename string, f *loader.File) {
// 延迟到最后全部修改完成再清理 pos 重新生成
loader.ClearPos(f.File)
comment := fmt.Sprintf(fileComment, opt.buildTag)
f.WriteWithComment(filename, comment)
})
}
type filePrinter func(filename string, file *loader.File)
func rewrite(l *loader.Loader, printer filePrinter) {
tryPkg := l.LookupPackage(pkgTryPath)
if tryPkg == nil {
log.Printf("skipped: missing %s\n", pkgTryPath)
return
}
tryFns := map[types.Object]fnName{}
for _, n := range tryFnNames {
tryFns[l.MustLookup(pkgTryPath+"."+n)] = n
}
l.VisitAllFiles(func(f *loader.File) {
log.Printf("write file: %s\n", f.Filename)
pkg := loader.MkPkg(f.Pkg)
f.File = rewriteFile(tryFns, pkg, f.File) // 1. rewrite try call
f.File.Comments = nil // 2. delete comments
f.File.Doc = nil // 3. delete pkg doc
printer(f.Filename, f) // 4. write back
})
}