forked from go-kit/kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transform.go
230 lines (196 loc) · 4.94 KB
/
transform.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
package main
import (
"bytes"
"fmt"
"go/ast"
"go/format"
"go/token"
"io"
"os"
"path/filepath"
"sort"
"strings"
"github.com/davecgh/go-spew/spew"
"github.com/pkg/errors"
"golang.org/x/tools/imports"
)
type (
files map[string]io.Reader
layout interface {
transformAST(ctx *sourceContext) (files, error)
}
outputTree map[string]*ast.File
)
func (ot outputTree) addFile(path, pkgname string) *ast.File {
file := &ast.File{
Name: id(pkgname),
Decls: []ast.Decl{},
}
ot[path] = file
return file
}
func getGopath() string {
gopath, set := os.LookupEnv("GOPATH")
if !set {
return filepath.Join(os.Getenv("HOME"), "go")
}
return gopath
}
func importPath(targetDir, gopath string) (string, error) {
if !filepath.IsAbs(targetDir) {
return "", fmt.Errorf("%q is not an absolute path", targetDir)
}
for _, dir := range filepath.SplitList(gopath) {
abspath, err := filepath.Abs(dir)
if err != nil {
continue
}
srcPath := filepath.Join(abspath, "src")
res, err := filepath.Rel(srcPath, targetDir)
if err != nil {
continue
}
if strings.Index(res, "..") == -1 {
return res, nil
}
}
return "", fmt.Errorf("%q is not in GOPATH (%s)", targetDir, gopath)
}
func selectify(file *ast.File, pkgName, identName, importPath string) *ast.File {
if file.Name.Name == pkgName {
return file
}
selector := sel(id(pkgName), id(identName))
var did bool
if file, did = selectifyIdent(identName, file, selector); did {
addImport(file, importPath)
}
return file
}
type selIdentFn func(ast.Node, func(ast.Node)) Visitor
func (f selIdentFn) Visit(node ast.Node, r func(ast.Node)) Visitor {
return f(node, r)
}
func selectifyIdent(identName string, file *ast.File, selector ast.Expr) (*ast.File, bool) {
var replaced bool
var r selIdentFn
r = selIdentFn(func(node ast.Node, replaceWith func(ast.Node)) Visitor {
switch id := node.(type) {
case *ast.SelectorExpr:
return nil
case *ast.Ident:
if id.Name == identName {
replaced = true
replaceWith(selector)
}
}
return r
})
return WalkReplace(r, file).(*ast.File), replaced
}
func formatNode(fname string, node ast.Node) (*bytes.Buffer, error) {
if file, is := node.(*ast.File); is {
sort.Stable(sortableDecls(file.Decls))
}
outfset := token.NewFileSet()
buf := &bytes.Buffer{}
err := format.Node(buf, outfset, node)
if err != nil {
return nil, err
}
imps, err := imports.Process(fname, buf.Bytes(), nil)
if err != nil {
return nil, err
}
return bytes.NewBuffer(imps), nil
}
type sortableDecls []ast.Decl
func (sd sortableDecls) Len() int {
return len(sd)
}
func (sd sortableDecls) Less(i int, j int) bool {
switch left := sd[i].(type) {
case *ast.GenDecl:
switch right := sd[j].(type) {
default:
return left.Tok == token.IMPORT
case *ast.GenDecl:
return left.Tok == token.IMPORT && right.Tok != token.IMPORT
}
}
return false
}
func (sd sortableDecls) Swap(i int, j int) {
sd[i], sd[j] = sd[j], sd[i]
}
func formatNodes(nodes outputTree) (files, error) {
res := files{}
var err error
for fn, node := range nodes {
res[fn], err = formatNode(fn, node)
if err != nil {
return nil, errors.Wrapf(err, "formatNodes")
}
}
return res, nil
}
// XXX debug
func spewDecls(f *ast.File) {
for _, d := range f.Decls {
switch dcl := d.(type) {
default:
spew.Dump(dcl)
case *ast.GenDecl:
spew.Dump(dcl.Tok)
case *ast.FuncDecl:
spew.Dump(dcl.Name.Name)
}
}
}
func addImports(root *ast.File, ctx *sourceContext) {
root.Decls = append(root.Decls, ctx.importDecls()...)
}
func addImport(root *ast.File, path string) {
for _, d := range root.Decls {
if imp, is := d.(*ast.GenDecl); is && imp.Tok == token.IMPORT {
for _, s := range imp.Specs {
if s.(*ast.ImportSpec).Path.Value == `"`+path+`"` {
return // already have one
// xxx aliased imports?
}
}
}
}
root.Decls = append(root.Decls, importFor(importSpec(path)))
}
func addStubStruct(root *ast.File, iface iface) {
root.Decls = append(root.Decls, iface.stubStructDecl())
}
func addType(root *ast.File, typ *ast.TypeSpec) {
root.Decls = append(root.Decls, typeDecl(typ))
}
func addMethod(root *ast.File, iface iface, meth method) {
def := meth.definition(iface)
root.Decls = append(root.Decls, def)
}
func addRequestStruct(root *ast.File, meth method) {
root.Decls = append(root.Decls, meth.requestStruct())
}
func addResponseStruct(root *ast.File, meth method) {
root.Decls = append(root.Decls, meth.responseStruct())
}
func addEndpointMaker(root *ast.File, ifc iface, meth method) {
root.Decls = append(root.Decls, meth.endpointMaker(ifc))
}
func addEndpointsStruct(root *ast.File, ifc iface) {
root.Decls = append(root.Decls, ifc.endpointsStruct())
}
func addHTTPHandler(root *ast.File, ifc iface) {
root.Decls = append(root.Decls, ifc.httpHandler())
}
func addDecoder(root *ast.File, meth method) {
root.Decls = append(root.Decls, meth.decoderFunc())
}
func addEncoder(root *ast.File, meth method) {
root.Decls = append(root.Decls, meth.encoderFunc())
}