forked from omissis/go-jsonschema
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate.go
223 lines (181 loc) · 5.73 KB
/
generate.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
package generator
import (
"errors"
"fmt"
"go/format"
"os"
"strings"
"github.com/andrew-farries/go-jsonschema/internal/x/text"
"github.com/andrew-farries/go-jsonschema/pkg/codegen"
"github.com/andrew-farries/go-jsonschema/pkg/schemas"
)
const (
varNamePlainStruct = "plain"
varNameRawMap = "raw"
interfaceTypeName = "interface{}"
)
var (
errSchemaHasNoRoot = errors.New("schema has no root")
errArrayPropertyItems = errors.New("array property must have 'items' set to a type")
errEnumArrCannotBeEmpty = errors.New("enum array cannot be empty")
errEnumNonPrimitiveVal = errors.New("enum has non-primitive value")
errMapURIToPackageName = errors.New("unable to map schema URI to Go package name")
errExpectedNamedType = errors.New("expected named type")
errUnsupportedRefFormat = errors.New("unsupported $ref format")
errConflictSameFile = errors.New("conflict: same file")
errDefinitionDoesNotExistInSchema = errors.New("definition does not exist in schema")
errCannotGenerateReferencedType = errors.New("cannot generate referenced type")
)
type Generator struct {
caser *text.Caser
config Config
inScope map[qualifiedDefinition]struct{}
outputs map[string]*output
schemaCacheByFileName map[string]*schemas.Schema
warner func(string)
formatters []formatter
fileLoader schemas.Loader
}
type qualifiedDefinition struct {
schema *schemas.Schema
name string
}
func New(config Config) (*Generator, error) {
formatters := []formatter{
&jsonFormatter{},
}
if config.ExtraImports {
formatters = append(formatters, &yamlFormatter{})
}
generator := &Generator{
caser: text.NewCaser(config.Capitalizations, config.ResolveExtensions),
config: config,
inScope: map[qualifiedDefinition]struct{}{},
outputs: map[string]*output{},
schemaCacheByFileName: map[string]*schemas.Schema{},
warner: config.Warner,
formatters: formatters,
}
generator.fileLoader = schemas.NewCachedLoader(
schemas.NewFileLoader(config.ResolveExtensions, config.YAMLExtensions),
generator.schemaCacheByFileName,
)
return generator, nil
}
func (g *Generator) Sources() map[string][]byte {
var maxLineLength uint = 80
sources := make(map[string]*strings.Builder, len(g.outputs))
for _, output := range g.outputs {
if output.file.FileName == "" {
continue
}
emitter := codegen.NewEmitter(maxLineLength)
output.file.Generate(emitter)
sb, ok := sources[output.file.FileName]
if !ok {
sb = &strings.Builder{}
sources[output.file.FileName] = sb
}
_, _ = sb.WriteString(emitter.String())
}
result := make(map[string][]byte, len(sources))
for f, sb := range sources {
source := []byte(sb.String())
src, err := format.Source(source)
if err != nil {
g.config.Warner(fmt.Sprintf("The generated code could not be formatted automatically; "+
"falling back to unformatted: %s", err))
src = source
}
result[f] = src
}
return result
}
func (g *Generator) DoFile(fileName string) error {
var err error
var schema *schemas.Schema
if fileName == "-" {
schema, err = schemas.FromJSONReader(os.Stdin)
if err != nil {
return fmt.Errorf("error parsing from standard input: %w", err)
}
} else {
schema, err = g.fileLoader.Load(fileName, "")
if err != nil {
return fmt.Errorf("error parsing from file %s: %w", fileName, err)
}
}
return g.addFile(fileName, schema)
}
func (g *Generator) addFile(fileName string, schema *schemas.Schema) error {
o, err := g.findOutputFileForSchemaID(schema.ID)
if err != nil {
return err
}
return (&schemaGenerator{
Generator: g,
schema: schema,
schemaFileName: fileName,
output: o,
}).generateRootType()
}
func (g *Generator) getRootTypeName(schema *schemas.Schema, fileName string) string {
for _, m := range g.config.SchemaMappings {
if m.SchemaID == schema.ID && m.RootType != "" {
return m.RootType
}
}
if g.config.StructNameFromTitle && schema.Title != "" {
return g.caser.Identifierize(schema.Title)
}
return g.caser.IdentifierFromFileName(fileName)
}
func (g *Generator) findOutputFileForSchemaID(id string) (*output, error) {
if o, ok := g.outputs[id]; ok {
return o, nil
}
for _, m := range g.config.SchemaMappings {
if m.SchemaID == id {
return g.beginOutput(id, m.OutputName, m.PackageName)
}
}
return g.beginOutput(id, g.config.DefaultOutputName, g.config.DefaultPackageName)
}
func (g *Generator) beginOutput(
id string,
outputName, packageName string,
) (*output, error) {
if packageName == "" {
return nil, fmt.Errorf("%w: %q", errMapURIToPackageName, id)
}
for _, o := range g.outputs {
if o.file.FileName == outputName && o.file.Package.QualifiedName != packageName {
return nil, fmt.Errorf(
"%w (%s) mapped to two different Go packages (%q and %q) for schema %q",
errConflictSameFile, o.file.FileName, o.file.Package.QualifiedName, packageName, id)
}
if o.file.FileName == outputName && o.file.Package.QualifiedName == packageName {
return o, nil
}
}
pkg := codegen.Package{
QualifiedName: packageName,
}
output := &output{
warner: g.warner,
file: &codegen.File{
FileName: outputName,
Package: pkg,
},
declsBySchema: map[*schemas.Type]*codegen.TypeDecl{},
declsByName: map[string]*codegen.TypeDecl{},
}
g.outputs[id] = output
return output, nil
}
func (g *Generator) makeEnumConstantName(typeName, value string) string {
if strings.ContainsAny(typeName[len(typeName)-1:], "0123456789") {
return typeName + "_" + g.caser.Identifierize(value)
}
return typeName + g.caser.Identifierize(value)
}