-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
252 lines (228 loc) · 5.13 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
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"go/ast"
"go/format"
"go/token"
"go/types"
"golang.org/x/tools/go/packages"
"golang.org/x/tools/imports"
"io/ioutil"
"log"
"os"
"path/filepath"
)
var errNotFound = errors.New("no struct literal found at selection")
// W represents that write file.
var W string
func main() {
log.SetFlags(0)
log.SetPrefix("fillstruct-rand: ")
var (
filename = flag.String("file", "", "required. filename")
line = flag.Int("line", 0, "required. line number of the struct literal")
w = flag.String("w", "", "optional. when set this, the generated code will write to the file which names w")
)
flag.Parse()
if w != nil {
W = *w
}
if (*line == 0) || *filename == "" {
flag.PrintDefaults()
os.Exit(1)
}
path, err := absPath(*filename)
if err != nil {
log.Fatal(err)
}
var overlay map[string][]byte
cfg := &packages.Config{
Overlay: overlay,
Mode: packages.LoadAllSyntax,
Tests: true,
Dir: filepath.Dir(path),
Fset: token.NewFileSet(),
Env: os.Environ(),
}
pkgs, err := packages.Load(cfg)
if err != nil {
log.Fatal(err)
}
if *line > 0 {
err = byLine(pkgs, path, *line)
switch err {
case nil:
return
default:
log.Fatal(err)
}
}
log.Fatal(errNotFound)
}
func absPath(filename string) (string, error) {
eval, err := filepath.EvalSymlinks(filename)
if err != nil {
return "", err
}
return filepath.Abs(eval)
}
func byLine(lprog []*packages.Package, path string, line int) (err error) {
var f *ast.File
var pkg *packages.Package
for _, p := range lprog {
for _, af := range p.Syntax {
if file := p.Fset.File(af.Pos()); file.Name() == path {
f = af
pkg = p
}
}
}
if f == nil || pkg == nil {
return fmt.Errorf("could not find file %q", path)
}
importNames := buildImportNameMap(f)
rightStartLine := 0
max := func(a, b int) int {
if a > b {
return a
}
return b
}
ast.Inspect(f, func(n ast.Node) bool {
lit, ok := n.(*ast.CompositeLit)
if !ok {
return true
}
_ = lit
startLine := pkg.Fset.Position(lit.Pos()).Line
endLine := pkg.Fset.Position(lit.End()).Line
if !(startLine <= line && line <= endLine) {
return true
}
rightStartLine = max(startLine, rightStartLine)
return true
})
var outs []output
var prev types.Type
ast.Inspect(f, func(n ast.Node) bool {
lit, ok := n.(*ast.CompositeLit)
if !ok {
return true
}
startLine := pkg.Fset.Position(lit.Pos()).Line
if !(startLine == rightStartLine) {
return true
}
var info litInfo
info.name, _ = pkg.TypesInfo.Types[lit].Type.(*types.Named)
info.typ, ok = pkg.TypesInfo.Types[lit].Type.Underlying().(*types.Struct)
if !ok {
prev = pkg.TypesInfo.Types[lit].Type.Underlying()
err = errNotFound
return true
}
info.hideType = hideType(prev)
startOff := pkg.Fset.Position(lit.Pos()).Offset
endOff := pkg.Fset.Position(lit.End()).Offset
newlit, lines := zeroValue(pkg.Types, importNames, lit, info)
var out output
out, err = prepareOutput(newlit, lines, startOff, endOff)
if err != nil {
return false
}
if debug {
log.Println(out.Code)
} else if len(W) > 0 {
content, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
contentStr := string(content)
res := contentStr[:out.Start] + out.Code + contentStr[out.End:]
ioutil.WriteFile(W, []byte(res), 0644)
var resBytes []byte
resBytes, err = imports.Process(path, []byte(res), nil)
if err != nil {
panic(err)
}
ioutil.WriteFile(W, resBytes, 0644)
} else if len(W) == 0 {
content, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
contentStr := string(content)
res := contentStr[:out.Start] + out.Code + contentStr[out.End:]
ioutil.WriteFile(path, []byte(res), 0644)
var resBytes []byte
resBytes, err = imports.Process(path, []byte(res), nil)
if err != nil {
panic(err)
}
ioutil.WriteFile(path, resBytes, 0644)
}
outs = append(outs, out)
return false
})
if err != nil {
return err
}
if len(outs) == 0 {
return errNotFound
}
for i := len(outs)/2 - 1; i >= 0; i-- {
opp := len(outs) - 1 - i
outs[i], outs[opp] = outs[opp], outs[i]
}
if err != nil {
return err
}
//return json.NewEncoder(os.Stdout).Encode([]output{out})
return nil
}
func hideType(t types.Type) bool {
switch t.(type) {
case *types.Array:
return true
case *types.Map:
return true
case *types.Slice:
return true
default:
return false
}
}
func buildImportNameMap(f *ast.File) map[string]string {
imports := make(map[string]string)
for _, i := range f.Imports {
if i.Name != nil && i.Name.Name != "_" {
path := i.Path.Value
imports[path[1:len(path)-1]] = i.Name.Name
}
}
return imports
}
type output struct {
Start int `json:"start"`
End int `json:"end"`
Code string `json:"code"`
}
func prepareOutput(n ast.Node, lines, start, end int) (output, error) {
fset := token.NewFileSet()
file := fset.AddFile("", -1, lines)
for i := 1; i <= lines; i++ {
file.AddLine(i)
}
var buf bytes.Buffer
if err := format.Node(&buf, fset, n); err != nil {
return output{}, err
}
return output{
Start: start,
End: end,
Code: buf.String(),
}, nil
}