forked from go-swagger/go-swagger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.go
1895 lines (1652 loc) · 59.8 KB
/
model.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015 go-swagger maintainers
//
// 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 (
"encoding/json"
"errors"
"fmt"
"log"
"os"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"github.com/go-openapi/analysis"
"github.com/go-openapi/loads"
"github.com/go-openapi/spec"
"github.com/go-openapi/swag"
)
const asMethod = "()"
/*
Rewrite specification document first:
* anonymous objects
* tuples
* extensible objects (properties + additionalProperties)
* AllOfs when they match the rewrite criteria (not a nullable allOf)
Find string enums and generate specialized idiomatic enum with them
Every action that happens tracks the path which is a linked list of refs
*/
// GenerateDefinition generates a model file for a schema definition.
func GenerateDefinition(modelNames []string, opts *GenOpts) error {
if opts == nil {
return errors.New("gen opts are required")
}
if opts.TemplateDir != "" {
if err := templates.LoadDir(opts.TemplateDir); err != nil {
return err
}
}
if err := opts.CheckOpts(); err != nil {
return err
}
// Load the spec
specPath, specDoc, err := loadSpec(opts.Spec)
if err != nil {
return err
}
if len(modelNames) == 0 {
for k := range specDoc.Spec().Definitions {
modelNames = append(modelNames, k)
}
}
for _, modelName := range modelNames {
// lookup schema
model, ok := specDoc.Spec().Definitions[modelName]
if !ok {
return fmt.Errorf("model %q not found in definitions given by %q", modelName, specPath)
}
// generate files
generator := definitionGenerator{
Name: modelName,
Model: model,
SpecDoc: specDoc,
Target: filepath.Join(
opts.Target,
filepath.FromSlash(opts.LanguageOpts.ManglePackagePath(opts.ModelPackage, ""))),
opts: opts,
}
if err := generator.Generate(); err != nil {
return err
}
}
return nil
}
type definitionGenerator struct {
Name string
Model spec.Schema
SpecDoc *loads.Document
Target string
opts *GenOpts
}
func (m *definitionGenerator) Generate() error {
mod, err := makeGenDefinition(m.Name, m.Target, m.Model, m.SpecDoc, m.opts)
if err != nil {
return fmt.Errorf("could not generate definitions for model %s on target %s: %v", m.Name, m.Target, err)
}
if m.opts.DumpData {
bb, _ := json.MarshalIndent(swag.ToDynamicJSON(mod), "", " ")
fmt.Fprintln(os.Stdout, string(bb))
return nil
}
if m.opts.IncludeModel {
log.Println("including additional model")
if err := m.generateModel(mod); err != nil {
return fmt.Errorf("could not generate model: %v", err)
}
}
log.Println("generated model", m.Name)
return nil
}
func (m *definitionGenerator) generateModel(g *GenDefinition) error {
debugLog("rendering definitions for %+v", *g)
return m.opts.renderDefinition(g)
}
func makeGenDefinition(name, pkg string, schema spec.Schema, specDoc *loads.Document, opts *GenOpts) (*GenDefinition, error) {
gd, err := makeGenDefinitionHierarchy(name, pkg, "", schema, specDoc, opts)
if err == nil && gd != nil {
// before yielding the schema to the renderer, we check if the top-level Validate method gets some content
// this means that the immediate content of the top level definitions has at least one validation.
//
// If none is found at this level and that no special case where no Validate() method is exposed at all
// (e.g. io.ReadCloser and interface{} types and their aliases), then there is an empty Validate() method which
// just return nil (the object abides by the runtime.Validatable interface, but knows it has nothing to validate).
//
// We do this at the top level because of the possibility of aliased types which always bubble up validation to types which
// are referring to them. This results in correct but inelegant code with empty validations.
gd.GenSchema.HasValidations = shallowValidationLookup(gd.GenSchema)
}
return gd, err
}
func shallowValidationLookup(sch GenSchema) bool {
// scan top level need for validations
//
// NOTE: this supersedes the previous NeedsValidation flag
// With the introduction of this shallow lookup, it is no more necessary
// to establish a distinction between HasValidations (e.g. carries on validations)
// and NeedsValidation (e.g. should have a Validate method with something in it).
// The latter was almost not used anyhow.
if sch.IsArray && sch.HasValidations {
return true
}
if sch.IsStream || sch.IsInterface { // these types have no validation - aliased types on those do not implement the Validatable interface
return false
}
if sch.Required || sch.IsCustomFormatter && !sch.IsStream {
return true
}
if sch.MaxLength != nil || sch.MinLength != nil || sch.Pattern != "" || sch.MultipleOf != nil || sch.Minimum != nil || sch.Maximum != nil || len(sch.Enum) > 0 || len(sch.ItemsEnum) > 0 {
return true
}
for _, a := range sch.AllOf {
if a.HasValidations {
return true
}
}
for _, p := range sch.Properties {
// Using a base type within another structure triggers validation of the base type.
// The discriminator property in the base type definition itself does not.
if (p.HasValidations || p.Required) && !(sch.IsBaseType && p.Name == sch.DiscriminatorField) || (p.IsAliased || p.IsComplexObject) && !(p.IsInterface || p.IsStream) {
return true
}
}
if sch.IsTuple && (sch.AdditionalItems != nil && (sch.AdditionalItems.HasValidations || sch.AdditionalItems.Required)) {
return true
}
if sch.HasAdditionalProperties && (sch.AdditionalProperties.IsInterface || sch.AdditionalProperties.IsStream) {
return false
}
if sch.HasAdditionalProperties && (sch.AdditionalProperties.HasValidations || sch.AdditionalProperties.Required || sch.AdditionalProperties.IsAliased && !(sch.AdditionalProperties.IsInterface || sch.AdditionalProperties.IsStream)) {
return true
}
if sch.IsAliased && (sch.IsPrimitive && sch.HasValidations) { // non primitive aliased have either other attributes with validation (above) or shall not validate
return true
}
if sch.HasBaseType || sch.IsSubType {
return true
}
return false
}
func makeGenDefinitionHierarchy(name, pkg, container string, schema spec.Schema, specDoc *loads.Document, opts *GenOpts) (*GenDefinition, error) {
// Check if model is imported from external package using x-go-type
_, external := schema.Extensions[xGoType]
receiver := "m"
// models are resolved in the current package
resolver := newTypeResolver("", specDoc)
resolver.ModelName = name
analyzed := analysis.New(specDoc.Spec())
di := discriminatorInfo(analyzed)
pg := schemaGenContext{
Path: "",
Name: name,
Receiver: receiver,
IndexVar: "i",
ValueExpr: receiver,
Schema: schema,
Required: false,
TypeResolver: resolver,
Named: true,
ExtraSchemas: make(map[string]GenSchema),
Discrimination: di,
Container: container,
IncludeValidator: opts.IncludeValidator,
IncludeModel: opts.IncludeModel,
}
if err := pg.makeGenSchema(); err != nil {
return nil, fmt.Errorf("could not generate schema for %s: %v", name, err)
}
dsi, ok := di.Discriminators["#/definitions/"+name]
if ok {
// when these 2 are true then the schema will render as an interface
pg.GenSchema.IsBaseType = true
pg.GenSchema.IsExported = true
pg.GenSchema.DiscriminatorField = dsi.FieldName
if pg.GenSchema.Discriminates == nil {
pg.GenSchema.Discriminates = make(map[string]string)
}
pg.GenSchema.Discriminates[name] = dsi.GoType
pg.GenSchema.DiscriminatorValue = name
for _, v := range dsi.Children {
pg.GenSchema.Discriminates[v.FieldValue] = v.GoType
}
for j := range pg.GenSchema.Properties {
if !strings.HasSuffix(pg.GenSchema.Properties[j].ValueExpression, asMethod) {
pg.GenSchema.Properties[j].ValueExpression += asMethod
}
}
}
dse, ok := di.Discriminated["#/definitions/"+name]
if ok {
pg.GenSchema.DiscriminatorField = dse.FieldName
pg.GenSchema.DiscriminatorValue = dse.FieldValue
pg.GenSchema.IsSubType = true
knownProperties := make(map[string]struct{})
// find the referenced definitions
// check if it has a discriminator defined
// when it has a discriminator get the schema and run makeGenSchema for it.
// replace the ref with this new genschema
swsp := specDoc.Spec()
for i, ss := range schema.AllOf {
ref := ss.Ref
for ref.String() != "" {
var rsch *spec.Schema
var err error
rsch, err = spec.ResolveRef(swsp, &ref)
if err != nil {
return nil, err
}
ref = rsch.Ref
if rsch != nil && rsch.Ref.String() != "" {
ref = rsch.Ref
continue
}
ref = spec.Ref{}
if rsch != nil && rsch.Discriminator != "" {
gs, err := makeGenDefinitionHierarchy(strings.TrimPrefix(ss.Ref.String(), "#/definitions/"), pkg, pg.GenSchema.Name, *rsch, specDoc, opts)
if err != nil {
return nil, err
}
gs.GenSchema.IsBaseType = true
gs.GenSchema.IsExported = true
pg.GenSchema.AllOf[i] = gs.GenSchema
schPtr := &(pg.GenSchema.AllOf[i])
if schPtr.AdditionalItems != nil {
schPtr.AdditionalItems.IsBaseType = true
}
if schPtr.AdditionalProperties != nil {
schPtr.AdditionalProperties.IsBaseType = true
}
for j := range schPtr.Properties {
schPtr.Properties[j].IsBaseType = true
knownProperties[schPtr.Properties[j].Name] = struct{}{}
}
}
}
}
// dedupe the fields
alreadySeen := make(map[string]struct{})
for i, ss := range pg.GenSchema.AllOf {
var remainingProperties GenSchemaList
for _, p := range ss.Properties {
if _, ok := knownProperties[p.Name]; !ok || ss.IsBaseType {
if _, seen := alreadySeen[p.Name]; !seen {
remainingProperties = append(remainingProperties, p)
alreadySeen[p.Name] = struct{}{}
}
}
}
pg.GenSchema.AllOf[i].Properties = remainingProperties
}
}
defaultImports := []string{
"github.com/go-openapi/errors",
"github.com/go-openapi/runtime",
"github.com/go-openapi/swag",
"github.com/go-openapi/validate",
}
return &GenDefinition{
GenCommon: GenCommon{
Copyright: opts.Copyright,
TargetImportPath: filepath.ToSlash(opts.LanguageOpts.baseImport(opts.Target)),
},
Package: opts.LanguageOpts.ManglePackageName(path.Base(filepath.ToSlash(pkg)), "definitions"),
GenSchema: pg.GenSchema,
DependsOn: pg.Dependencies,
DefaultImports: defaultImports,
ExtraSchemas: gatherExtraSchemas(pg.ExtraSchemas),
Imports: findImports(&pg.GenSchema),
External: external,
}, nil
}
func findImports(sch *GenSchema) map[string]string {
imp := map[string]string{}
t := sch.resolvedType
if t.Pkg != "" && t.PkgAlias != "" {
imp[t.PkgAlias] = t.Pkg
}
if sch.Items != nil {
sub := findImports(sch.Items)
for k, v := range sub {
imp[k] = v
}
}
if sch.AdditionalItems != nil {
sub := findImports(sch.AdditionalItems)
for k, v := range sub {
imp[k] = v
}
}
if sch.Object != nil {
sub := findImports(sch.Object)
for k, v := range sub {
imp[k] = v
}
}
if sch.Properties != nil {
for _, p := range sch.Properties {
sub := findImports(&p)
for k, v := range sub {
imp[k] = v
}
}
}
if sch.AdditionalProperties != nil {
sub := findImports(sch.AdditionalProperties)
for k, v := range sub {
imp[k] = v
}
}
if sch.AllOf != nil {
for _, p := range sch.AllOf {
sub := findImports(&p)
for k, v := range sub {
imp[k] = v
}
}
}
return imp
}
type schemaGenContext struct {
Required bool
AdditionalProperty bool
Untyped bool
Named bool
RefHandled bool
IsVirtual bool
IsTuple bool
IncludeValidator bool
IncludeModel bool
Index int
Path string
Name string
ParamName string
Accessor string
Receiver string
IndexVar string
KeyVar string
ValueExpr string
Container string
Schema spec.Schema
TypeResolver *typeResolver
GenSchema GenSchema
Dependencies []string
ExtraSchemas map[string]GenSchema
Discriminator *discor
Discriminated *discee
Discrimination *discInfo
}
func (sg *schemaGenContext) NewSliceBranch(schema *spec.Schema) *schemaGenContext {
debugLog("new slice branch %s (model: %s)", sg.Name, sg.TypeResolver.ModelName)
pg := sg.shallowClone()
indexVar := pg.IndexVar
if pg.Path == "" {
pg.Path = "strconv.Itoa(" + indexVar + ")"
} else {
pg.Path = pg.Path + "+ \".\" + strconv.Itoa(" + indexVar + ")"
}
// check who is parent, if it's a base type then rewrite the value expression
if sg.Discrimination != nil && sg.Discrimination.Discriminators != nil {
_, rewriteValueExpr := sg.Discrimination.Discriminators["#/definitions/"+sg.TypeResolver.ModelName]
if (pg.IndexVar == "i" && rewriteValueExpr) || sg.GenSchema.ElemType.IsBaseType {
if !sg.GenSchema.IsAliased {
pg.ValueExpr = sg.Receiver + "." + swag.ToJSONName(sg.GenSchema.Name) + "Field"
} else {
pg.ValueExpr = sg.Receiver
}
}
}
sg.GenSchema.IsBaseType = sg.GenSchema.ElemType.HasDiscriminator
pg.IndexVar = indexVar + "i"
pg.ValueExpr = pg.ValueExpr + "[" + indexVar + "]"
pg.Schema = *schema
pg.Required = false
if sg.IsVirtual {
pg.TypeResolver = sg.TypeResolver.NewWithModelName(sg.TypeResolver.ModelName)
}
// when this is an anonymous complex object, this needs to become a ref
return pg
}
func (sg *schemaGenContext) NewAdditionalItems(schema *spec.Schema) *schemaGenContext {
debugLog("new additional items\n")
pg := sg.shallowClone()
indexVar := pg.IndexVar
pg.Name = sg.Name + " items"
itemsLen := 0
if sg.Schema.Items != nil {
itemsLen = sg.Schema.Items.Len()
}
var mod string
if itemsLen > 0 {
mod = "+" + strconv.Itoa(itemsLen)
}
if pg.Path == "" {
pg.Path = "strconv.Itoa(" + indexVar + mod + ")"
} else {
pg.Path = pg.Path + "+ \".\" + strconv.Itoa(" + indexVar + mod + ")"
}
pg.IndexVar = indexVar
pg.ValueExpr = sg.ValueExpr + "." + pascalize(sg.GoName()) + "Items[" + indexVar + "]"
pg.Schema = spec.Schema{}
if schema != nil {
pg.Schema = *schema
}
pg.Required = false
return pg
}
func (sg *schemaGenContext) NewTupleElement(schema *spec.Schema, index int) *schemaGenContext {
debugLog("New tuple element\n")
pg := sg.shallowClone()
if pg.Path == "" {
pg.Path = "\"" + strconv.Itoa(index) + "\""
} else {
pg.Path = pg.Path + "+ \".\"+\"" + strconv.Itoa(index) + "\""
}
pg.ValueExpr = pg.ValueExpr + ".P" + strconv.Itoa(index)
pg.Required = true
pg.IsTuple = true
pg.Schema = *schema
return pg
}
func (sg *schemaGenContext) NewStructBranch(name string, schema spec.Schema) *schemaGenContext {
debugLog("new struct branch %s (parent %s)", sg.Name, sg.Container)
pg := sg.shallowClone()
if sg.Path == "" {
pg.Path = fmt.Sprintf("%q", name)
} else {
pg.Path = pg.Path + "+\".\"+" + fmt.Sprintf("%q", name)
}
pg.Name = name
pg.ValueExpr = pg.ValueExpr + "." + pascalize(goName(&schema, name))
pg.Schema = schema
for _, fn := range sg.Schema.Required {
if name == fn {
pg.Required = true
break
}
}
debugLog("made new struct branch %s (parent %s)", pg.Name, pg.Container)
return pg
}
func (sg *schemaGenContext) shallowClone() *schemaGenContext {
debugLog("cloning context %s\n", sg.Name)
pg := new(schemaGenContext)
*pg = *sg
if pg.Container == "" {
pg.Container = sg.Name
}
pg.GenSchema = GenSchema{}
pg.Dependencies = nil
pg.Named = false
pg.Index = 0
pg.IsTuple = false
pg.IncludeValidator = sg.IncludeValidator
pg.IncludeModel = sg.IncludeModel
return pg
}
func (sg *schemaGenContext) NewCompositionBranch(schema spec.Schema, index int) *schemaGenContext {
debugLog("new composition branch %s (parent: %s, index: %d)", sg.Name, sg.Container, index)
pg := sg.shallowClone()
pg.Schema = schema
pg.Name = "AO" + strconv.Itoa(index)
if sg.Name != sg.TypeResolver.ModelName {
pg.Name = sg.Name + pg.Name
}
pg.Index = index
debugLog("made new composition branch %s (parent: %s)", pg.Name, pg.Container)
return pg
}
func (sg *schemaGenContext) NewAdditionalProperty(schema spec.Schema) *schemaGenContext {
debugLog("new additional property %s (expr: %s)", sg.Name, sg.ValueExpr)
pg := sg.shallowClone()
pg.Schema = schema
if pg.KeyVar == "" {
pg.ValueExpr = sg.ValueExpr
}
pg.KeyVar += "k"
pg.ValueExpr += "[" + pg.KeyVar + "]"
pg.Path = pg.KeyVar
pg.GenSchema.Suffix = "Value"
if sg.Path != "" {
pg.Path = sg.Path + "+\".\"+" + pg.KeyVar
}
// propagates the special IsNullable override for maps of slices and
// maps of aliased types.
pg.GenSchema.IsMapNullOverride = sg.GenSchema.IsMapNullOverride
return pg
}
func hasSliceValidations(model *spec.Schema) (hasSliceValidations bool) {
hasSliceValidations = model.MaxItems != nil || model.MinItems != nil || model.UniqueItems || len(model.Enum) > 0
return
}
func hasValidations(model *spec.Schema, isRequired bool) (hasValidation bool) {
// NOTE: needsValidation has gone deprecated and is replaced by top-level's shallowValidationLookup()
hasNumberValidation := model.Maximum != nil || model.Minimum != nil || model.MultipleOf != nil
hasStringValidation := model.MaxLength != nil || model.MinLength != nil || model.Pattern != ""
hasEnum := len(model.Enum) > 0
// since this was added to deal with discriminator, we'll fix this when testing discriminated types
simpleObject := len(model.Properties) > 0 && model.Discriminator == ""
// lift validations from allOf branches
hasAllOfValidation := false
for _, s := range model.AllOf {
hasAllOfValidation = hasValidations(&s, false)
hasAllOfValidation = s.Ref.String() != "" || hasAllOfValidation
if hasAllOfValidation {
break
}
}
hasValidation = hasNumberValidation || hasStringValidation || hasSliceValidations(model) || hasEnum || simpleObject || hasAllOfValidation || isRequired
return
}
// handleFormatConflicts handles all conflicting model properties when a format is set
func handleFormatConflicts(model *spec.Schema) {
switch model.Format {
case "date", "datetime", "uuid", "bsonobjectid", "base64", "duration":
model.MinLength = nil
model.MaxLength = nil
model.Pattern = ""
// more cases should be inserted here if they arise
}
}
func (sg *schemaGenContext) schemaValidations() sharedValidations {
model := sg.Schema
// resolve any conflicting properties if the model has a format
handleFormatConflicts(&model)
isRequired := sg.Required
if model.Default != nil || model.ReadOnly {
// when readOnly or default is specified, this disables Required validation (Swagger-specific)
isRequired = false
}
hasSliceValidations := model.MaxItems != nil || model.MinItems != nil || model.UniqueItems || len(model.Enum) > 0
hasValidations := hasValidations(&model, isRequired)
s := sharedValidationsFromSchema(model, sg.Required)
s.HasValidations = hasValidations
s.HasSliceValidations = hasSliceValidations
return s
}
func mergeValidation(other *schemaGenContext) bool {
// NOTE: NeesRequired and NeedsValidation are deprecated
if other.GenSchema.AdditionalProperties != nil && other.GenSchema.AdditionalProperties.HasValidations {
return true
}
if other.GenSchema.AdditionalItems != nil && other.GenSchema.AdditionalItems.HasValidations {
return true
}
for _, sch := range other.GenSchema.AllOf {
if sch.HasValidations {
return true
}
}
return other.GenSchema.HasValidations
}
func (sg *schemaGenContext) MergeResult(other *schemaGenContext, liftsRequired bool) {
sg.GenSchema.HasValidations = sg.GenSchema.HasValidations || mergeValidation(other)
if liftsRequired && other.GenSchema.AdditionalProperties != nil && other.GenSchema.AdditionalProperties.Required {
sg.GenSchema.Required = true
}
if liftsRequired && other.GenSchema.Required {
sg.GenSchema.Required = other.GenSchema.Required
}
if other.GenSchema.HasBaseType {
sg.GenSchema.HasBaseType = other.GenSchema.HasBaseType
}
sg.Dependencies = append(sg.Dependencies, other.Dependencies...)
// lift extra schemas
for k, v := range other.ExtraSchemas {
sg.ExtraSchemas[k] = v
}
if other.GenSchema.IsMapNullOverride {
sg.GenSchema.IsMapNullOverride = true
}
}
func (sg *schemaGenContext) buildProperties() error {
debugLog("building properties %s (parent: %s)", sg.Name, sg.Container)
for k, v := range sg.Schema.Properties {
debugLogAsJSON("building property %s[%q] (tup: %t) (BaseType: %t)",
sg.Name, k, sg.IsTuple, sg.GenSchema.IsBaseType, sg.Schema)
debugLog("property %s[%q] (tup: %t) HasValidations: %t)",
sg.Name, k, sg.IsTuple, sg.GenSchema.HasValidations)
// check if this requires de-anonymizing, if so lift this as a new struct and extra schema
tpe, err := sg.TypeResolver.ResolveSchema(&v, true, sg.IsTuple || containsString(sg.Schema.Required, k))
if sg.Schema.Discriminator == k {
tpe.IsNullable = false
}
if err != nil {
return err
}
vv := v
var hasValidation bool
if tpe.IsComplexObject && tpe.IsAnonymous && len(v.Properties) > 0 {
// this is an anonymous complex construct: build a new new type for it
pg := sg.makeNewStruct(sg.Name+swag.ToGoName(k), v)
pg.IsTuple = sg.IsTuple
if sg.Path != "" {
pg.Path = sg.Path + "+ \".\"+" + fmt.Sprintf("%q", k)
} else {
pg.Path = fmt.Sprintf("%q", k)
}
if err := pg.makeGenSchema(); err != nil {
return err
}
if v.Discriminator != "" {
pg.GenSchema.IsBaseType = true
pg.GenSchema.IsExported = true
pg.GenSchema.HasBaseType = true
}
vv = *spec.RefProperty("#/definitions/" + pg.Name)
hasValidation = pg.GenSchema.HasValidations
sg.ExtraSchemas[pg.Name] = pg.GenSchema
// NOTE: MergeResult lifts validation status and extra schemas
sg.MergeResult(pg, false)
}
emprop := sg.NewStructBranch(k, vv)
emprop.IsTuple = sg.IsTuple
if err := emprop.makeGenSchema(); err != nil {
return err
}
// whatever the validations says, if we have an interface{}, do not validate
// NOTE: this may be the case when the type is left empty and we get a Enum validation.
if emprop.GenSchema.IsInterface || emprop.GenSchema.IsStream {
emprop.GenSchema.HasValidations = false
} else if hasValidation || emprop.GenSchema.HasValidations || emprop.GenSchema.Required || emprop.GenSchema.IsAliased || len(emprop.GenSchema.AllOf) > 0 {
emprop.GenSchema.HasValidations = true
sg.GenSchema.HasValidations = true
}
// generates format validation on property
emprop.GenSchema.HasValidations = emprop.GenSchema.HasValidations || (tpe.IsCustomFormatter && !tpe.IsStream) || (tpe.IsArray && tpe.ElemType.IsCustomFormatter && !tpe.ElemType.IsStream)
if emprop.Schema.Ref.String() != "" {
// expand the schema of this property, so we take informed decisions about its type
ref := emprop.Schema.Ref
var sch *spec.Schema
for ref.String() != "" {
var rsch *spec.Schema
var err error
specDoc := sg.TypeResolver.Doc
rsch, err = spec.ResolveRef(specDoc.Spec(), &ref)
if err != nil {
return err
}
ref = rsch.Ref
if rsch != nil && rsch.Ref.String() != "" {
ref = rsch.Ref
continue
}
ref = spec.Ref{}
sch = rsch
}
if emprop.Discrimination != nil {
if _, ok := emprop.Discrimination.Discriminators[emprop.Schema.Ref.String()]; ok {
emprop.GenSchema.IsBaseType = true
emprop.GenSchema.IsNullable = false
emprop.GenSchema.HasBaseType = true
}
if _, ok := emprop.Discrimination.Discriminated[emprop.Schema.Ref.String()]; ok {
emprop.GenSchema.IsSubType = true
}
}
// set property name
var nm = filepath.Base(emprop.Schema.Ref.GetURL().Fragment)
tr := sg.TypeResolver.NewWithModelName(goName(&emprop.Schema, swag.ToGoName(nm)))
ttpe, err := tr.ResolveSchema(sch, false, true)
if err != nil {
return err
}
if ttpe.IsAliased {
emprop.GenSchema.IsAliased = true
}
// lift validations
hv := hasValidations(sch, false)
// include format validation, excluding binary
hv = hv || (ttpe.IsCustomFormatter && !ttpe.IsStream) || (ttpe.IsArray && ttpe.ElemType.IsCustomFormatter && !ttpe.ElemType.IsStream)
// a base type property is always validated against the base type
// exception: for the base type definition itself (see shallowValidationLookup())
if (hv || emprop.GenSchema.IsBaseType) && !(emprop.GenSchema.IsInterface || emprop.GenSchema.IsStream) {
emprop.GenSchema.HasValidations = true
}
if ttpe.HasAdditionalItems && sch.AdditionalItems.Schema != nil {
// when AdditionalItems specifies a Schema, there is a validation
// check if we stepped upon an exeption
child, err := tr.ResolveSchema(sch.AdditionalItems.Schema, false, true)
if err != nil {
return err
}
if !child.IsInterface && !child.IsStream {
emprop.GenSchema.HasValidations = true
}
}
if ttpe.IsMap && sch.AdditionalProperties != nil && sch.AdditionalProperties.Schema != nil {
// when AdditionalProperties specifies a Schema, there is a validation
// check if we stepped upon an exeption
child, err := tr.ResolveSchema(sch.AdditionalProperties.Schema, false, true)
if err != nil {
return err
}
if !child.IsInterface && !child.IsStream {
emprop.GenSchema.HasValidations = true
}
}
}
if sg.Schema.Discriminator == k {
// this is the discriminator property:
// it is required, but forced as non-nullable,
// since we never fill it with a zero-value
// TODO: when no other property than discriminator, there is no validation
emprop.GenSchema.IsNullable = false
}
if emprop.GenSchema.IsBaseType {
sg.GenSchema.HasBaseType = true
}
sg.MergeResult(emprop, false)
// when discriminated, data is accessed via a getter func
if emprop.GenSchema.HasDiscriminator {
emprop.GenSchema.ValueExpression += asMethod
}
emprop.GenSchema.Extensions = emprop.Schema.Extensions
// set custom serializer tag
if customTag, found := emprop.Schema.Extensions[xGoCustomTag]; found {
emprop.GenSchema.CustomTag = customTag.(string)
}
sg.GenSchema.Properties = append(sg.GenSchema.Properties, emprop.GenSchema)
}
sort.Sort(sg.GenSchema.Properties)
return nil
}
func (sg *schemaGenContext) buildAllOf() error {
if len(sg.Schema.AllOf) == 0 {
return nil
}
var hasArray, hasNonArray int
sort.Sort(sg.GenSchema.AllOf)
if sg.Container == "" {
sg.Container = sg.Name
}
debugLogAsJSON("building all of for %d entries", len(sg.Schema.AllOf), sg.Schema)
for i, sch := range sg.Schema.AllOf {
tpe, ert := sg.TypeResolver.ResolveSchema(&sch, sch.Ref.String() == "", false)
if ert != nil {
return ert
}
// check for multiple arrays in allOf branches.
// Although a valid JSON-Schema construct, it is not suited for serialization.
// This is the same if we attempt to serialize an array with another object.
// We issue a generation warning on this.
if tpe.IsArray {
hasArray++
} else {
hasNonArray++
}
debugLogAsJSON("trying", sch)
if (tpe.IsAnonymous && len(sch.AllOf) > 0) || (sch.Ref.String() == "" && !tpe.IsComplexObject && (tpe.IsArray || tpe.IsInterface || tpe.IsPrimitive)) {
// cases where anonymous structures cause the creation of a new type:
// - nested allOf: this one is itself a AllOf: build a new type for it
// - anonymous simple types for edge cases: array, primitive, interface{}
// NOTE: when branches are aliased or anonymous, the nullable property in the branch type is lost.
name := swag.ToVarName(goName(&sch, sg.Name+"AllOf"+strconv.Itoa(i)))
debugLog("building anonymous nested allOf in %s: %s", sg.Name, name)
ng := sg.makeNewStruct(name, sch)
if err := ng.makeGenSchema(); err != nil {
return err
}
newsch := spec.RefProperty("#/definitions/" + ng.Name)
sg.Schema.AllOf[i] = *newsch
pg := sg.NewCompositionBranch(*newsch, i)
if err := pg.makeGenSchema(); err != nil {
return err
}
// lift extra schemas & validations from new type
pg.MergeResult(ng, true)
// lift validations when complex or ref'ed:
// - parent always calls its Validatable child
// - child may or may not have validations
//
// Exception: child is not Validatable when interface or stream
if !pg.GenSchema.IsInterface && !pg.GenSchema.IsStream {
sg.GenSchema.HasValidations = true
}
// add the newly created type to the list of schemas to be rendered inline
pg.ExtraSchemas[ng.Name] = ng.GenSchema
sg.MergeResult(pg, true)
sg.GenSchema.AllOf = append(sg.GenSchema.AllOf, pg.GenSchema)
continue
}
comprop := sg.NewCompositionBranch(sch, i)
if err := comprop.makeGenSchema(); err != nil {
return err
}
if comprop.GenSchema.IsMap && comprop.GenSchema.HasAdditionalProperties && comprop.GenSchema.AdditionalProperties != nil && !comprop.GenSchema.IsInterface {
// the anonymous branch is a map for AdditionalProperties: rewrite value expression
comprop.GenSchema.ValueExpression = comprop.GenSchema.ValueExpression + "." + comprop.Name
comprop.GenSchema.AdditionalProperties.ValueExpression = comprop.GenSchema.ValueExpression + "[" + comprop.GenSchema.AdditionalProperties.KeyVar + "]"
}
// lift validations when complex or ref'ed
if (comprop.GenSchema.IsComplexObject || comprop.Schema.Ref.String() != "") && !(comprop.GenSchema.IsInterface || comprop.GenSchema.IsStream) {
comprop.GenSchema.HasValidations = true
}
sg.MergeResult(comprop, true)
sg.GenSchema.AllOf = append(sg.GenSchema.AllOf, comprop.GenSchema)
}
if hasArray > 1 || (hasArray > 0 && hasNonArray > 0) {
log.Printf("warning: cannot generate serializable allOf with conflicting array definitions in %s", sg.Container)
}
sg.GenSchema.IsNullable = true
// prevent IsAliased to bubble up (e.g. when a single branch is itself aliased)
sg.GenSchema.IsAliased = sg.GenSchema.IsAliased && len(sg.GenSchema.AllOf) < 2
return nil
}
type mapStack struct {
Type *spec.Schema
Next *mapStack
Previous *mapStack
ValueRef *schemaGenContext
Context *schemaGenContext
NewObj *schemaGenContext
}
func newMapStack(context *schemaGenContext) (first, last *mapStack, err error) {
ms := &mapStack{
Type: &context.Schema,
Context: context,
}
l := ms
for l.HasMore() {
tpe, err := l.Context.TypeResolver.ResolveSchema(l.Type.AdditionalProperties.Schema, true, true)
if err != nil {
return nil, nil, err
}
if !tpe.IsMap {
//reached the end of the rabbit hole
if tpe.IsComplexObject && tpe.IsAnonymous {
// found an anonymous object: create the struct from a newly created definition
nw := l.Context.makeNewStruct(l.Context.Name+" Anon", *l.Type.AdditionalProperties.Schema)
sch := spec.RefProperty("#/definitions/" + nw.Name)
l.NewObj = nw
l.Type.AdditionalProperties.Schema = sch
l.ValueRef = l.Context.NewAdditionalProperty(*sch)
}
// other cases where to stop are: a $ref or a simple object
break
}
// continue digging for maps