forked from pquerna/ffjson
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinceptionmain.go
293 lines (246 loc) · 6.29 KB
/
inceptionmain.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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/**
* Copyright 2014 Paul Querna
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package generator
import (
"bytes"
"errors"
"fmt"
"go/format"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"text/template"
"github.com/pquerna/ffjson/shared"
)
const inceptionMainTemplate = `
// DO NOT EDIT!
// Code generated by ffjson <https://github.com/pquerna/ffjson>
// DO NOT EDIT!
package main
import (
"github.com/pquerna/ffjson/inception"
importedinceptionpackage "{{.ImportName}}"
)
func main() {
i := ffjsoninception.NewInception("{{.InputPath}}", "{{.PackageName}}", "{{.OutputPath}}", {{.ResetFields}})
i.AddMany(importedinceptionpackage.FFJSONExpose())
i.Execute()
}
`
const ffjsonExposeTemplate = `
// Code generated by ffjson <https://github.com/pquerna/ffjson>
//
// This should be automatically deleted by running 'ffjson',
// if leftover, please delete it.
package {{.PackageName}}
import (
ffjsonshared "github.com/pquerna/ffjson/shared"
)
func FFJSONExpose() []ffjsonshared.InceptionType {
rv := make([]ffjsonshared.InceptionType, 0)
{{range .StructNames}}
rv = append(rv, ffjsonshared.InceptionType{Obj: {{.Name}}{}, Options: ffjson{{printf "%#v" .Options}} } )
{{end}}
return rv
}
`
type structName struct {
Name string
Options shared.StructOptions
}
type templateCtx struct {
StructNames []structName
ImportName string
PackageName string
InputPath string
OutputPath string
ResetFields bool
}
type InceptionMain struct {
goCmd string
inputPath string
exposePath string
outputPath string
TempMainPath string
tempDir string
tempMain *os.File
tempExpose *os.File
resetFields bool
}
func NewInceptionMain(goCmd string, inputPath string, outputPath string, resetFields bool) *InceptionMain {
exposePath := getExposePath(inputPath)
return &InceptionMain{
goCmd: goCmd,
inputPath: inputPath,
outputPath: outputPath,
exposePath: exposePath,
resetFields: resetFields,
}
}
func goEnv(name string) string {
value, err := exec.Command("go", "env", name).Output()
if err != nil {
return ""
}
return string(bytes.TrimSuffix(value, []byte("\n")))
}
func getImportName(inputPath string) (string, error) {
p, err := filepath.Abs(inputPath)
if err != nil {
return "", err
}
dir := filepath.Dir(p)
moduleName, err := exec.Command("go", "list", "-m").Output()
if err == nil && len(moduleName) > 0 {
moduleImportName := func() string {
goMod := goEnv("GOMOD")
if len(goMod) == 0 {
return ""
}
path := filepath.Dir(string(goMod))
absPath, err := filepath.Abs(path)
if err != nil {
return ""
}
stat, err := os.Stat(absPath)
if err != nil || !stat.IsDir() {
return ""
}
rel, err := filepath.Rel(filepath.ToSlash(absPath), dir)
if err != nil {
return ""
}
return string(bytes.TrimSuffix(moduleName, []byte("\n"))) + string(os.PathSeparator) + rel
}()
if len(moduleImportName) > 0 {
return moduleImportName, nil
}
}
goPath := os.Getenv("GOPATH")
if len(goPath) == 0 {
goPath = goEnv("GOPATH")
}
gopaths := strings.Split(goPath, string(os.PathListSeparator))
for _, path := range gopaths {
gpath, err := filepath.Abs(path)
if err != nil {
continue
}
rel, err := filepath.Rel(filepath.ToSlash(gpath), dir)
if err != nil {
return "", err
}
if len(rel) < 4 || rel[:4] != "src"+string(os.PathSeparator) {
continue
}
return rel[4:], nil
}
return "", errors.New(fmt.Sprintf("Could not find source directory: GOPATH=%q REL=%q", gopaths, dir))
}
func getExposePath(inputPath string) string {
return inputPath[0:len(inputPath)-3] + "_ffjson_expose.go"
}
func (im *InceptionMain) renderTpl(f *os.File, t *template.Template, tc *templateCtx) error {
buf := new(bytes.Buffer)
err := t.Execute(buf, tc)
if err != nil {
return err
}
formatted, err := format.Source(buf.Bytes())
if err != nil {
return err
}
_, err = f.Write(formatted)
return err
}
func (im *InceptionMain) Generate(packageName string, si []*StructInfo, importName string) error {
var err error
if importName == "" {
importName, err = getImportName(im.inputPath)
if err != nil {
return err
}
}
im.tempDir, err = ioutil.TempDir(filepath.Dir(im.inputPath), "ffjson-inception")
if err != nil {
return err
}
importName = filepath.ToSlash(importName)
// for `go run` to work, we must have a file ending in ".go".
im.tempMain, err = TempFileWithPostfix(im.tempDir, "ffjson-inception", ".go")
if err != nil {
return err
}
im.TempMainPath = im.tempMain.Name()
sn := make([]structName, len(si))
for i, st := range si {
sn[i].Name = st.Name
sn[i].Options = st.Options
}
tc := &templateCtx{
ImportName: importName,
PackageName: packageName,
StructNames: sn,
InputPath: im.inputPath,
OutputPath: im.outputPath,
ResetFields: im.resetFields,
}
t := template.Must(template.New("inception.go").Parse(inceptionMainTemplate))
err = im.renderTpl(im.tempMain, t, tc)
if err != nil {
return err
}
im.tempExpose, err = os.Create(im.exposePath)
if err != nil {
return err
}
t = template.Must(template.New("ffjson_expose.go").Parse(ffjsonExposeTemplate))
err = im.renderTpl(im.tempExpose, t, tc)
if err != nil {
return err
}
return nil
}
func (im *InceptionMain) Run() error {
var out bytes.Buffer
var errOut bytes.Buffer
cmd := exec.Command(im.goCmd, "run", "-a", im.TempMainPath)
cmd.Stdout = &out
cmd.Stderr = &errOut
err := cmd.Run()
if err != nil {
return errors.New(
fmt.Sprintf("Go Run Failed for: %s\nSTDOUT:\n%s\nSTDERR:\n%s\n",
im.TempMainPath,
string(out.Bytes()),
string(errOut.Bytes())))
}
defer func() {
if im.tempExpose != nil {
im.tempExpose.Close()
}
if im.tempMain != nil {
im.tempMain.Close()
}
os.Remove(im.TempMainPath)
os.Remove(im.exposePath)
os.Remove(im.tempDir)
}()
return nil
}