-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
229 lines (191 loc) · 4.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
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"os"
"sort"
"strings"
"github.com/jessevdk/go-flags"
"github.com/xeipuuv/gojsonpointer"
)
func main() {
var opts struct {
Output string `long:"output" description:"output filepath" default:"-"`
TypeName string `long:"typename" description:"type name to be generated"`
VarName string `long:"varname" description:"variable name to be generated"`
Package string `long:"package" description:"output package name"`
Root string `long:"root" description:"JSON pointer specifing root object or array"`
Structure string `long:"structure" description:"comma separated \"map\" or \"slice\" sequence" default:"slice"`
Fields string `long:"fields" description:"comma separated target property names"`
}
args, err := flags.Parse(&opts)
if err != nil {
os.Exit(1)
}
if len(args) == 0 {
log.Fatal("argument is not found")
}
if opts.Package == "" {
log.Fatal("--package must be specifed")
}
if opts.TypeName == "" {
log.Fatal("--typename must be specified")
}
if opts.VarName == "" {
log.Fatal("--varname must be specified")
}
structurePaths := strings.Split(opts.Structure, ",")
for _, path := range structurePaths {
if path != "slice" && path != "map" {
log.Fatalf(`--structure must be constructed either "slice" or "map"`)
}
}
v, err := loadJSON(args, opts.Root, structurePaths)
if err != nil {
log.Fatalf("failed to parse JSON: %s", err)
}
if opts.Fields != "" {
fields := strings.Split(opts.Fields, ",")
sort.Strings(fields)
filterFields(v, fields)
}
typ := detectTypeInStructure(v, structurePaths)
src, err := Generate(strings.Join(os.Args, " "), opts.Package, opts.TypeName, opts.VarName, typ, structurePaths, v)
if err != nil {
log.Fatalf("failed to format output source code: %s", err)
}
var out io.Writer
if opts.Output == "-" {
out = os.Stdout
} else {
f, err := os.Create(opts.Output)
if err != nil {
log.Fatalf("failed to open file: %s", err)
}
defer f.Close()
out = f
}
out.Write(src)
}
func loadJSON(filenames []string, root string, structurePaths []string) (interface{}, error) {
vs := make([]interface{}, 0, len(filenames))
pointer, err := gojsonpointer.NewJsonPointer(root)
if err != nil {
return nil, fmt.Errorf("invalid json pointer: %s", err)
}
for _, filename := range filenames {
f, err := os.Open(filename)
if err != nil {
log.Fatalf("failed to open file: %s", err)
}
defer f.Close()
var v interface{}
err = json.NewDecoder(f).Decode(&v)
if err != nil {
log.Fatalf("failed to decode JSON: %s", err)
}
v, _, err = pointer.Get(v)
if err != nil {
log.Fatalf("failed to get root value: %s", err)
}
vs = append(vs, v)
}
if err := validateStructures(vs, structurePaths); err != nil {
return nil, err
}
return mergeJSONs(vs, structurePaths), nil
}
func validateStructures(vs []interface{}, structurePaths []string) error {
for _, v := range vs {
if err := validateStructure(v, structurePaths); err != nil {
return err
}
}
return nil
}
func validateStructure(v interface{}, structurePaths []string) error {
if len(structurePaths) == 0 {
return nil
}
// TODO: explicit error message
head := structurePaths[0]
tail := structurePaths[1:]
switch head {
case "slice":
a, ok := v.([]interface{})
if !ok {
fmt.Errorf("structure path is slice, but got non-array value")
}
for _, e := range a {
if err := validateStructure(e, tail); err != nil {
return err
}
}
case "map":
m, ok := v.(map[string]interface{})
if !ok {
fmt.Errorf("structure path is map, but got non-object value")
}
for _, e := range m {
if err := validateStructure(e, tail); err != nil {
return err
}
}
}
return nil
}
func mergeJSONs(vs []interface{}, structurePaths []string) interface{} {
if len(structurePaths) == 0 {
return vs[len(vs)-1]
}
head := structurePaths[0]
tail := structurePaths[1:]
switch head {
case "slice":
ret := make([]interface{}, 0)
for _, v := range vs {
for _, e := range v.([]interface{}) {
ret = append(ret, e)
}
}
return ret
case "map":
keyMap := map[string]struct{}{}
for _, v := range vs {
for k := range v.(map[string]interface{}) {
keyMap[k] = struct{}{}
}
}
ret := make(map[string]interface{})
for key := range keyMap {
cs := make([]interface{}, 0, len(vs))
for _, v := range vs {
m := v.(map[string]interface{})
e, ok := m[key]
if ok {
cs = append(cs, e)
}
}
ret[key] = mergeJSONs(cs, tail)
}
return ret
}
panic(fmt.Sprintf("assertion error: unexpected structure type: %s", structurePaths[0]))
}
func filterFields(v interface{}, fields []string) {
fieldMap := map[string]bool{}
for _, field := range fields {
fieldMap[field] = true
}
a := v.([]interface{})
for _, obj := range a {
obj := obj.(map[string]interface{})
for key := range obj {
if !fieldMap[key] {
delete(obj, key)
}
}
}
}