| 1 |
/* |
| 2 |
Copyright 2016 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package generators |
| 18 |
|
| 19 |
import ( |
| 20 |
"bytes" |
| 21 |
"encoding/json" |
| 22 |
"fmt" |
| 23 |
"io" |
| 24 |
"path" |
| 25 |
"reflect" |
| 26 |
"regexp" |
| 27 |
"sort" |
| 28 |
"strings" |
| 29 |
|
| 30 |
"k8s.io/gengo/v2" |
| 31 |
"k8s.io/gengo/v2/generator" |
| 32 |
"k8s.io/gengo/v2/namer" |
| 33 |
"k8s.io/gengo/v2/types" |
| 34 |
openapi "k8s.io/kube-openapi/pkg/common" |
| 35 |
"k8s.io/kube-openapi/pkg/validation/spec" |
| 36 |
|
| 37 |
"k8s.io/klog/v2" |
| 38 |
) |
| 39 |
|
| 40 |
// This is the comment tag that carries parameters for open API generation. |
| 41 |
const tagName = "k8s:openapi-gen" |
| 42 |
const markerPrefix = "+k8s:validation:" |
| 43 |
const tagOptional = "optional" |
| 44 |
const tagRequired = "required" |
| 45 |
const tagDefault = "default" |
| 46 |
|
| 47 |
// Known values for the tag. |
| 48 |
const ( |
| 49 |
tagValueTrue = "true" |
| 50 |
tagValueFalse = "false" |
| 51 |
) |
| 52 |
|
| 53 |
// Used for temporary validation of patch struct tags. |
| 54 |
// TODO: Remove patch struct tag validation because they we are now consuming OpenAPI on server. |
| 55 |
var tempPatchTags = [...]string{ |
| 56 |
"patchMergeKey", |
| 57 |
"patchStrategy", |
| 58 |
} |
| 59 |
|
| 60 |
func getOpenAPITagValue(comments []string) []string { |
| 61 |
return gengo.ExtractCommentTags("+", comments)[tagName] |
| 62 |
} |
| 63 |
|
| 64 |
func getSingleTagsValue(comments []string, tag string) (string, error) { |
| 65 |
tags, ok := gengo.ExtractCommentTags("+", comments)[tag] |
| 66 |
if !ok || len(tags) == 0 { |
| 67 |
return "", nil |
| 68 |
} |
| 69 |
if len(tags) > 1 { |
| 70 |
return "", fmt.Errorf("multiple values are not allowed for tag %s", tag) |
| 71 |
} |
| 72 |
return tags[0], nil |
| 73 |
} |
| 74 |
|
| 75 |
func hasOpenAPITagValue(comments []string, value string) bool { |
| 76 |
tagValues := getOpenAPITagValue(comments) |
| 77 |
for _, val := range tagValues { |
| 78 |
if val == value { |
| 79 |
return true |
| 80 |
} |
| 81 |
} |
| 82 |
return false |
| 83 |
} |
| 84 |
|
| 85 |
// isOptional returns error if the member has +optional and +required in |
| 86 |
// its comments. If +optional is present it returns true. If +required is present |
| 87 |
// it returns false. Otherwise, it returns true if `omitempty` JSON tag is present |
| 88 |
func isOptional(m *types.Member) (bool, error) { |
| 89 |
hasOptionalCommentTag := gengo.ExtractCommentTags( |
| 90 |
"+", m.CommentLines)[tagOptional] != nil |
| 91 |
hasRequiredCommentTag := gengo.ExtractCommentTags( |
| 92 |
"+", m.CommentLines)[tagRequired] != nil |
| 93 |
if hasOptionalCommentTag && hasRequiredCommentTag { |
| 94 |
return false, fmt.Errorf("member %s cannot be both optional and required", m.Name) |
| 95 |
} else if hasRequiredCommentTag { |
| 96 |
return false, nil |
| 97 |
} else if hasOptionalCommentTag { |
| 98 |
return true, nil |
| 99 |
} |
| 100 |
|
| 101 |
// If neither +optional nor +required is present in the comments, |
| 102 |
// infer optional from the json tags. |
| 103 |
return hasOmitemptyTag(m), nil |
| 104 |
} |
| 105 |
|
| 106 |
func apiTypeFilterFunc(c *generator.Context, t *types.Type) bool { |
| 107 |
// There is a conflict between this codegen and codecgen, we should avoid types generated for codecgen |
| 108 |
if strings.HasPrefix(t.Name.Name, "codecSelfer") { |
| 109 |
return false |
| 110 |
} |
| 111 |
pkg := c.Universe.Package(t.Name.Package) |
| 112 |
if hasOpenAPITagValue(pkg.Comments, tagValueTrue) { |
| 113 |
return !hasOpenAPITagValue(t.CommentLines, tagValueFalse) |
| 114 |
} |
| 115 |
if hasOpenAPITagValue(t.CommentLines, tagValueTrue) { |
| 116 |
return true |
| 117 |
} |
| 118 |
return false |
| 119 |
} |
| 120 |
|
| 121 |
const ( |
| 122 |
specPackagePath = "k8s.io/kube-openapi/pkg/validation/spec" |
| 123 |
openAPICommonPackagePath = "k8s.io/kube-openapi/pkg/common" |
| 124 |
) |
| 125 |
|
| 126 |
// openApiGen produces a file with auto-generated OpenAPI functions. |
| 127 |
type openAPIGen struct { |
| 128 |
generator.GoGenerator |
| 129 |
// TargetPackage is the package that will get GetOpenAPIDefinitions function returns all open API definitions. |
| 130 |
targetPackage string |
| 131 |
imports namer.ImportTracker |
| 132 |
} |
| 133 |
|
| 134 |
func newOpenAPIGen(outputFilename string, targetPackage string) generator.Generator { |
| 135 |
return &openAPIGen{ |
| 136 |
GoGenerator: generator.GoGenerator{ |
| 137 |
OutputFilename: outputFilename, |
| 138 |
}, |
| 139 |
imports: generator.NewImportTrackerForPackage(targetPackage), |
| 140 |
targetPackage: targetPackage, |
| 141 |
} |
| 142 |
} |
| 143 |
|
| 144 |
const nameTmpl = "schema_$.type|private$" |
| 145 |
|
| 146 |
func (g *openAPIGen) Namers(c *generator.Context) namer.NameSystems { |
| 147 |
// Have the raw namer for this file track what it imports. |
| 148 |
return namer.NameSystems{ |
| 149 |
"raw": namer.NewRawNamer(g.targetPackage, g.imports), |
| 150 |
"private": &namer.NameStrategy{ |
| 151 |
Join: func(pre string, in []string, post string) string { |
| 152 |
return strings.Join(in, "_") |
| 153 |
}, |
| 154 |
PrependPackageNames: 4, // enough to fully qualify from k8s.io/api/... |
| 155 |
}, |
| 156 |
} |
| 157 |
} |
| 158 |
|
| 159 |
func (g *openAPIGen) Imports(c *generator.Context) []string { |
| 160 |
importLines := []string{} |
| 161 |
for _, singleImport := range g.imports.ImportLines() { |
| 162 |
importLines = append(importLines, singleImport) |
| 163 |
} |
| 164 |
return importLines |
| 165 |
} |
| 166 |
|
| 167 |
func argsFromType(t *types.Type) generator.Args { |
| 168 |
return generator.Args{ |
| 169 |
"type": t, |
| 170 |
"ReferenceCallback": types.Ref(openAPICommonPackagePath, "ReferenceCallback"), |
| 171 |
"OpenAPIDefinition": types.Ref(openAPICommonPackagePath, "OpenAPIDefinition"), |
| 172 |
"SpecSchemaType": types.Ref(specPackagePath, "Schema"), |
| 173 |
} |
| 174 |
} |
| 175 |
|
| 176 |
func (g *openAPIGen) Init(c *generator.Context, w io.Writer) error { |
| 177 |
sw := generator.NewSnippetWriter(w, c, "$", "$") |
| 178 |
sw.Do("func GetOpenAPIDefinitions(ref $.ReferenceCallback|raw$) map[string]$.OpenAPIDefinition|raw$ {\n", argsFromType(nil)) |
| 179 |
sw.Do("return map[string]$.OpenAPIDefinition|raw${\n", argsFromType(nil)) |
| 180 |
|
| 181 |
for _, t := range c.Order { |
| 182 |
err := newOpenAPITypeWriter(sw, c).generateCall(t) |
| 183 |
if err != nil { |
| 184 |
return err |
| 185 |
} |
| 186 |
} |
| 187 |
|
| 188 |
sw.Do("}\n", nil) |
| 189 |
sw.Do("}\n\n", nil) |
| 190 |
|
| 191 |
return sw.Error() |
| 192 |
} |
| 193 |
|
| 194 |
func (g *openAPIGen) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error { |
| 195 |
klog.V(5).Infof("generating for type %v", t) |
| 196 |
sw := generator.NewSnippetWriter(w, c, "$", "$") |
| 197 |
err := newOpenAPITypeWriter(sw, c).generate(t) |
| 198 |
if err != nil { |
| 199 |
return err |
| 200 |
} |
| 201 |
return sw.Error() |
| 202 |
} |
| 203 |
|
| 204 |
func getJsonTags(m *types.Member) []string { |
| 205 |
jsonTag := reflect.StructTag(m.Tags).Get("json") |
| 206 |
if jsonTag == "" { |
| 207 |
return []string{} |
| 208 |
} |
| 209 |
return strings.Split(jsonTag, ",") |
| 210 |
} |
| 211 |
|
| 212 |
func getReferableName(m *types.Member) string { |
| 213 |
jsonTags := getJsonTags(m) |
| 214 |
if len(jsonTags) > 0 { |
| 215 |
if jsonTags[0] == "-" { |
| 216 |
return "" |
| 217 |
} else { |
| 218 |
return jsonTags[0] |
| 219 |
} |
| 220 |
} else { |
| 221 |
return m.Name |
| 222 |
} |
| 223 |
} |
| 224 |
|
| 225 |
func hasOmitemptyTag(m *types.Member) bool { |
| 226 |
jsonTag, _ := reflect.StructTag(m.Tags).Lookup("json") |
| 227 |
return strings.HasSuffix(jsonTag, ",omitempty") || strings.Contains(jsonTag, ",omitempty,") |
| 228 |
} |
| 229 |
|
| 230 |
func shouldInlineMembers(m *types.Member) bool { |
| 231 |
jsonTag, jsonTagExists := reflect.StructTag(m.Tags).Lookup("json") |
| 232 |
return m.Embedded && jsonTagExists && (jsonTag == "" || strings.HasPrefix(jsonTag, ",")) |
| 233 |
} |
| 234 |
|
| 235 |
type openAPITypeWriter struct { |
| 236 |
*generator.SnippetWriter |
| 237 |
context *generator.Context |
| 238 |
refTypes map[string]*types.Type |
| 239 |
enumContext *enumContext |
| 240 |
GetDefinitionInterface *types.Type |
| 241 |
} |
| 242 |
|
| 243 |
func newOpenAPITypeWriter(sw *generator.SnippetWriter, c *generator.Context) openAPITypeWriter { |
| 244 |
return openAPITypeWriter{ |
| 245 |
SnippetWriter: sw, |
| 246 |
context: c, |
| 247 |
refTypes: map[string]*types.Type{}, |
| 248 |
enumContext: newEnumContext(c), |
| 249 |
} |
| 250 |
} |
| 251 |
|
| 252 |
func methodReturnsValue(mt *types.Type, pkg, name string) bool { |
| 253 |
if len(mt.Signature.Parameters) != 0 || len(mt.Signature.Results) != 1 { |
| 254 |
return false |
| 255 |
} |
| 256 |
r := mt.Signature.Results[0] |
| 257 |
return r.Type.Name.Name == name && r.Type.Name.Package == pkg |
| 258 |
} |
| 259 |
|
| 260 |
func hasOpenAPIV3DefinitionMethod(t *types.Type) bool { |
| 261 |
for mn, mt := range t.Methods { |
| 262 |
if mn != "OpenAPIV3Definition" { |
| 263 |
continue |
| 264 |
} |
| 265 |
return methodReturnsValue(mt, openAPICommonPackagePath, "OpenAPIDefinition") |
| 266 |
} |
| 267 |
return false |
| 268 |
} |
| 269 |
|
| 270 |
func hasOpenAPIDefinitionMethod(t *types.Type) bool { |
| 271 |
for mn, mt := range t.Methods { |
| 272 |
if mn != "OpenAPIDefinition" { |
| 273 |
continue |
| 274 |
} |
| 275 |
return methodReturnsValue(mt, openAPICommonPackagePath, "OpenAPIDefinition") |
| 276 |
} |
| 277 |
return false |
| 278 |
} |
| 279 |
|
| 280 |
func hasOpenAPIDefinitionMethods(t *types.Type) bool { |
| 281 |
var hasSchemaTypeMethod, hasOpenAPISchemaFormat bool |
| 282 |
for mn, mt := range t.Methods { |
| 283 |
switch mn { |
| 284 |
case "OpenAPISchemaType": |
| 285 |
hasSchemaTypeMethod = methodReturnsValue(mt, "", "[]string") |
| 286 |
case "OpenAPISchemaFormat": |
| 287 |
hasOpenAPISchemaFormat = methodReturnsValue(mt, "", "string") |
| 288 |
} |
| 289 |
} |
| 290 |
return hasSchemaTypeMethod && hasOpenAPISchemaFormat |
| 291 |
} |
| 292 |
|
| 293 |
func hasOpenAPIV3OneOfMethod(t *types.Type) bool { |
| 294 |
for mn, mt := range t.Methods { |
| 295 |
if mn != "OpenAPIV3OneOfTypes" { |
| 296 |
continue |
| 297 |
} |
| 298 |
return methodReturnsValue(mt, "", "[]string") |
| 299 |
} |
| 300 |
return false |
| 301 |
} |
| 302 |
|
| 303 |
func hasOpenAPIModelName(t *types.Type) bool { |
| 304 |
for mn, mt := range t.Methods { |
| 305 |
if mn != "OpenAPIModelName" { |
| 306 |
continue |
| 307 |
} |
| 308 |
return methodReturnsValue(mt, "", "string") |
| 309 |
} |
| 310 |
return false |
| 311 |
} |
| 312 |
|
| 313 |
func (g openAPITypeWriter) shouldUseOpenAPIModelName(t *types.Type) bool { |
| 314 |
// Finds non-generated OpenAPIModelName() functions. |
| 315 |
// Generated OpenAPIModelName() are ignored due to the 'ignore_autogenerated' build tag |
| 316 |
// but are handled below by checking for use of the +k8s:openapi-model-package. |
| 317 |
// This approach allows code generators to be called in any order. |
| 318 |
if hasOpenAPIModelName(t) { |
| 319 |
return true |
| 320 |
} |
| 321 |
|
| 322 |
value, err := extractOpenAPISchemaNamePackage(t.CommentLines) |
| 323 |
if err != nil { |
| 324 |
klog.Fatalf("Type %v: invalid %s:%v", t, tagModelPackage, err) |
| 325 |
} |
| 326 |
if value != "" { |
| 327 |
return true |
| 328 |
} |
| 329 |
pkg := g.context.Universe.Package(t.Name.Package) |
| 330 |
value, err = extractOpenAPISchemaNamePackage(pkg.Comments) |
| 331 |
if err != nil { |
| 332 |
klog.Fatalf("Package %v: invalid %s:%v", pkg, tagModelPackage, err) |
| 333 |
} |
| 334 |
return value != "" |
| 335 |
} |
| 336 |
|
| 337 |
// typeShortName returns short package name (e.g. the name x appears in package x definition) dot type name. |
| 338 |
func typeShortName(t *types.Type) string { |
| 339 |
// `path` vs. `filepath` because packages use '/' |
| 340 |
return path.Base(t.Name.Package) + "." + t.Name.Name |
| 341 |
} |
| 342 |
|
| 343 |
func (g openAPITypeWriter) generateMembers(t *types.Type, required []string) ([]string, error) { |
| 344 |
var err error |
| 345 |
for t.Kind == types.Pointer { // fast-forward to effective type containing members |
| 346 |
t = t.Elem |
| 347 |
} |
| 348 |
for _, m := range t.Members { |
| 349 |
if hasOpenAPITagValue(m.CommentLines, tagValueFalse) { |
| 350 |
continue |
| 351 |
} |
| 352 |
if shouldInlineMembers(&m) { |
| 353 |
required, err = g.generateMembers(m.Type, required) |
| 354 |
if err != nil { |
| 355 |
return required, err |
| 356 |
} |
| 357 |
continue |
| 358 |
} |
| 359 |
name := getReferableName(&m) |
| 360 |
if name == "" { |
| 361 |
continue |
| 362 |
} |
| 363 |
if isOptional, err := isOptional(&m); err != nil { |
| 364 |
klog.Errorf("Error when generating: %v, %v\n", name, m) |
| 365 |
return required, err |
| 366 |
} else if !isOptional { |
| 367 |
required = append(required, name) |
| 368 |
} |
| 369 |
if err = g.generateProperty(&m, t); err != nil { |
| 370 |
klog.Errorf("Error when generating: %v, %v\n", name, m) |
| 371 |
return required, err |
| 372 |
} |
| 373 |
} |
| 374 |
return required, nil |
| 375 |
} |
| 376 |
|
| 377 |
func (g openAPITypeWriter) generateCall(t *types.Type) error { |
| 378 |
// Only generate for struct type and ignore the rest |
| 379 |
switch t.Kind { |
| 380 |
case types.Struct: |
| 381 |
if namer.IsPrivateGoName(t.Name.Name) { // skip private types |
| 382 |
return nil |
| 383 |
} |
| 384 |
|
| 385 |
args := argsFromType(t) |
| 386 |
|
| 387 |
if g.shouldUseOpenAPIModelName(t) { |
| 388 |
g.Do("$.|raw${}.OpenAPIModelName(): ", t) |
| 389 |
} else { |
| 390 |
// Legacy case: use the "canonical type name" |
| 391 |
g.Do("\"$.$\": ", t.Name) |
| 392 |
} |
| 393 |
|
| 394 |
hasV2Definition := hasOpenAPIDefinitionMethod(t) |
| 395 |
hasV2DefinitionTypeAndFormat := hasOpenAPIDefinitionMethods(t) |
| 396 |
hasV3Definition := hasOpenAPIV3DefinitionMethod(t) |
| 397 |
|
| 398 |
switch { |
| 399 |
case hasV2DefinitionTypeAndFormat: |
| 400 |
g.Do(nameTmpl+"(ref),\n", args) |
| 401 |
case hasV2Definition && hasV3Definition: |
| 402 |
g.Do("common.EmbedOpenAPIDefinitionIntoV2Extension($.type|raw${}.OpenAPIV3Definition(), $.type|raw${}.OpenAPIDefinition()),\n", args) |
| 403 |
case hasV2Definition: |
| 404 |
g.Do("$.type|raw${}.OpenAPIDefinition(),\n", args) |
| 405 |
case hasV3Definition: |
| 406 |
g.Do("$.type|raw${}.OpenAPIV3Definition(),\n", args) |
| 407 |
default: |
| 408 |
g.Do(nameTmpl+"(ref),\n", args) |
| 409 |
} |
| 410 |
} |
| 411 |
return g.Error() |
| 412 |
} |
| 413 |
|
| 414 |
// Generates Go code to represent an OpenAPI schema. May be refactored in |
| 415 |
// the future to take more responsibility as we transition from an on-line |
| 416 |
// approach to parsing the comments to spec.Schema |
| 417 |
func (g openAPITypeWriter) generateSchema(s *spec.Schema) error { |
| 418 |
if !reflect.DeepEqual(s.SchemaProps, spec.SchemaProps{}) { |
| 419 |
g.Do("SchemaProps: spec.SchemaProps{\n", nil) |
| 420 |
err := g.generateValueValidations(&s.SchemaProps) |
| 421 |
if err != nil { |
| 422 |
return err |
| 423 |
} |
| 424 |
|
| 425 |
if len(s.Properties) > 0 { |
| 426 |
g.Do("Properties: map[string]spec.Schema{\n", nil) |
| 427 |
|
| 428 |
// Sort property names to generate deterministic output |
| 429 |
keys := []string{} |
| 430 |
for k := range s.Properties { |
| 431 |
keys = append(keys, k) |
| 432 |
} |
| 433 |
sort.Strings(keys) |
| 434 |
|
| 435 |
for _, k := range keys { |
| 436 |
v := s.Properties[k] |
| 437 |
g.Do("$.$: {\n", fmt.Sprintf("%#v", k)) |
| 438 |
err := g.generateSchema(&v) |
| 439 |
if err != nil { |
| 440 |
return err |
| 441 |
} |
| 442 |
g.Do("},\n", nil) |
| 443 |
} |
| 444 |
g.Do("},\n", nil) |
| 445 |
} |
| 446 |
|
| 447 |
if s.AdditionalProperties != nil && s.AdditionalProperties.Schema != nil { |
| 448 |
g.Do("AdditionalProperties: &spec.SchemaOrBool{\n", nil) |
| 449 |
g.Do("Allows: true,\n", nil) |
| 450 |
g.Do("Schema: &spec.Schema{\n", nil) |
| 451 |
err := g.generateSchema(s.AdditionalProperties.Schema) |
| 452 |
if err != nil { |
| 453 |
return err |
| 454 |
} |
| 455 |
g.Do("},\n", nil) |
| 456 |
g.Do("},\n", nil) |
| 457 |
} |
| 458 |
|
| 459 |
if s.Items != nil && s.Items.Schema != nil { |
| 460 |
g.Do("Items: &spec.SchemaOrArray{\n", nil) |
| 461 |
g.Do("Schema: &spec.Schema{\n", nil) |
| 462 |
err := g.generateSchema(s.Items.Schema) |
| 463 |
if err != nil { |
| 464 |
return err |
| 465 |
} |
| 466 |
g.Do("},\n", nil) |
| 467 |
g.Do("},\n", nil) |
| 468 |
} |
| 469 |
|
| 470 |
g.Do("},\n", nil) |
| 471 |
} |
| 472 |
|
| 473 |
if len(s.Extensions) > 0 { |
| 474 |
g.Do("VendorExtensible: spec.VendorExtensible{\nExtensions: spec.Extensions{\n", nil) |
| 475 |
|
| 476 |
// Sort extension keys to generate deterministic output |
| 477 |
keys := []string{} |
| 478 |
for k := range s.Extensions { |
| 479 |
keys = append(keys, k) |
| 480 |
} |
| 481 |
sort.Strings(keys) |
| 482 |
|
| 483 |
for _, k := range keys { |
| 484 |
v := s.Extensions[k] |
| 485 |
g.Do("$.key$: $.value$,\n", map[string]interface{}{ |
| 486 |
"key": fmt.Sprintf("%#v", k), |
| 487 |
"value": fmt.Sprintf("%#v", v), |
| 488 |
}) |
| 489 |
} |
| 490 |
g.Do("},\n},\n", nil) |
| 491 |
} |
| 492 |
|
| 493 |
return nil |
| 494 |
} |
| 495 |
|
| 496 |
func (g openAPITypeWriter) generateValueValidations(vs *spec.SchemaProps) error { |
| 497 |
|
| 498 |
if vs == nil { |
| 499 |
return nil |
| 500 |
} |
| 501 |
args := generator.Args{ |
| 502 |
"ptrTo": &types.Type{ |
| 503 |
Name: types.Name{ |
| 504 |
Package: "k8s.io/utils/ptr", |
| 505 |
Name: "To", |
| 506 |
}}, |
| 507 |
"spec": vs, |
| 508 |
} |
| 509 |
if vs.Minimum != nil { |
| 510 |
g.Do("Minimum: $.ptrTo|raw$[float64]($.spec.Minimum$),\n", args) |
| 511 |
} |
| 512 |
if vs.Maximum != nil { |
| 513 |
g.Do("Maximum: $.ptrTo|raw$[float64]($.spec.Maximum$),\n", args) |
| 514 |
} |
| 515 |
if vs.ExclusiveMinimum { |
| 516 |
g.Do("ExclusiveMinimum: true,\n", args) |
| 517 |
} |
| 518 |
if vs.ExclusiveMaximum { |
| 519 |
g.Do("ExclusiveMaximum: true,\n", args) |
| 520 |
} |
| 521 |
if vs.MinLength != nil { |
| 522 |
g.Do("MinLength: $.ptrTo|raw$[int64]($.spec.MinLength$),\n", args) |
| 523 |
} |
| 524 |
if vs.MaxLength != nil { |
| 525 |
g.Do("MaxLength: $.ptrTo|raw$[int64]($.spec.MaxLength$),\n", args) |
| 526 |
} |
| 527 |
|
| 528 |
if vs.MinProperties != nil { |
| 529 |
g.Do("MinProperties: $.ptrTo|raw$[int64]($.spec.MinProperties$),\n", args) |
| 530 |
} |
| 531 |
if vs.MaxProperties != nil { |
| 532 |
g.Do("MaxProperties: $.ptrTo|raw$[int64]($.spec.MaxProperties$),\n", args) |
| 533 |
} |
| 534 |
if len(vs.Pattern) > 0 { |
| 535 |
p, err := json.Marshal(vs.Pattern) |
| 536 |
if err != nil { |
| 537 |
return err |
| 538 |
} |
| 539 |
g.Do("Pattern: $.$,\n", string(p)) |
| 540 |
} |
| 541 |
if vs.MultipleOf != nil { |
| 542 |
g.Do("MultipleOf: $.ptrTo|raw$[float64]($.spec.MultipleOf$),\n", args) |
| 543 |
} |
| 544 |
if vs.MinItems != nil { |
| 545 |
g.Do("MinItems: $.ptrTo|raw$[int64]($.spec.MinItems$),\n", args) |
| 546 |
} |
| 547 |
if vs.MaxItems != nil { |
| 548 |
g.Do("MaxItems: $.ptrTo|raw$[int64]($.spec.MaxItems$),\n", args) |
| 549 |
} |
| 550 |
if vs.UniqueItems { |
| 551 |
g.Do("UniqueItems: true,\n", nil) |
| 552 |
} |
| 553 |
|
| 554 |
if len(vs.AllOf) > 0 { |
| 555 |
g.Do("AllOf: []spec.Schema{\n", nil) |
| 556 |
for _, s := range vs.AllOf { |
| 557 |
g.Do("{\n", nil) |
| 558 |
if err := g.generateSchema(&s); err != nil { |
| 559 |
return err |
| 560 |
} |
| 561 |
g.Do("},\n", nil) |
| 562 |
} |
| 563 |
g.Do("},\n", nil) |
| 564 |
} |
| 565 |
|
| 566 |
return nil |
| 567 |
} |
| 568 |
|
| 569 |
func (g openAPITypeWriter) generate(t *types.Type) error { |
| 570 |
// Only generate for struct type and ignore the rest |
| 571 |
switch t.Kind { |
| 572 |
case types.Struct: |
| 573 |
validationSchema, err := ParseCommentTags(t, t.CommentLines, markerPrefix) |
| 574 |
if err != nil { |
| 575 |
return fmt.Errorf("failed parsing comment tags for %v: %w", t.String(), err) |
| 576 |
} |
| 577 |
|
| 578 |
hasV2Definition := hasOpenAPIDefinitionMethod(t) |
| 579 |
hasV2DefinitionTypeAndFormat := hasOpenAPIDefinitionMethods(t) |
| 580 |
hasV3OneOfTypes := hasOpenAPIV3OneOfMethod(t) |
| 581 |
hasV3Definition := hasOpenAPIV3DefinitionMethod(t) |
| 582 |
|
| 583 |
if hasV2Definition || (hasV3Definition && !hasV2DefinitionTypeAndFormat) { |
| 584 |
// already invoked directly |
| 585 |
return nil |
| 586 |
} |
| 587 |
|
| 588 |
args := argsFromType(t) |
| 589 |
g.Do("func "+nameTmpl+"(ref $.ReferenceCallback|raw$) $.OpenAPIDefinition|raw$ {\n", args) |
| 590 |
switch { |
| 591 |
case hasV2DefinitionTypeAndFormat && hasV3Definition: |
| 592 |
g.Do("return common.EmbedOpenAPIDefinitionIntoV2Extension($.type|raw${}.OpenAPIV3Definition(), $.OpenAPIDefinition|raw${\n"+ |
| 593 |
"Schema: spec.Schema{\n"+ |
| 594 |
"SchemaProps: spec.SchemaProps{\n", args) |
| 595 |
g.generateDescription(t.CommentLines) |
| 596 |
g.Do("Type:$.type|raw${}.OpenAPISchemaType(),\n"+ |
| 597 |
"Format:$.type|raw${}.OpenAPISchemaFormat(),\n", args) |
| 598 |
err = g.generateValueValidations(&validationSchema.SchemaProps) |
| 599 |
if err != nil { |
| 600 |
return err |
| 601 |
} |
| 602 |
g.Do("},\n", nil) |
| 603 |
if err := g.generateStructExtensions(t, validationSchema.Extensions); err != nil { |
| 604 |
return err |
| 605 |
} |
| 606 |
g.Do("},\n", nil) |
| 607 |
g.Do("})\n}\n\n", args) |
| 608 |
return nil |
| 609 |
case hasV2DefinitionTypeAndFormat && hasV3OneOfTypes: |
| 610 |
// generate v3 def. |
| 611 |
g.Do("return common.EmbedOpenAPIDefinitionIntoV2Extension($.OpenAPIDefinition|raw${\n"+ |
| 612 |
"Schema: spec.Schema{\n"+ |
| 613 |
"SchemaProps: spec.SchemaProps{\n", args) |
| 614 |
g.generateDescription(t.CommentLines) |
| 615 |
g.Do("OneOf:common.GenerateOpenAPIV3OneOfSchema($.type|raw${}.OpenAPIV3OneOfTypes()),\n"+ |
| 616 |
"Format:$.type|raw${}.OpenAPISchemaFormat(),\n", args) |
| 617 |
err = g.generateValueValidations(&validationSchema.SchemaProps) |
| 618 |
if err != nil { |
| 619 |
return err |
| 620 |
} |
| 621 |
g.Do("},\n", nil) |
| 622 |
if err := g.generateStructExtensions(t, validationSchema.Extensions); err != nil { |
| 623 |
return err |
| 624 |
} |
| 625 |
g.Do("},\n", nil) |
| 626 |
g.Do("},", args) |
| 627 |
// generate v2 def. |
| 628 |
g.Do("$.OpenAPIDefinition|raw${\n"+ |
| 629 |
"Schema: spec.Schema{\n"+ |
| 630 |
"SchemaProps: spec.SchemaProps{\n", args) |
| 631 |
g.generateDescription(t.CommentLines) |
| 632 |
g.Do("Type:$.type|raw${}.OpenAPISchemaType(),\n"+ |
| 633 |
"Format:$.type|raw${}.OpenAPISchemaFormat(),\n", args) |
| 634 |
err = g.generateValueValidations(&validationSchema.SchemaProps) |
| 635 |
if err != nil { |
| 636 |
return err |
| 637 |
} |
| 638 |
g.Do("},\n", nil) |
| 639 |
if err := g.generateStructExtensions(t, validationSchema.Extensions); err != nil { |
| 640 |
return err |
| 641 |
} |
| 642 |
g.Do("},\n", nil) |
| 643 |
g.Do("})\n}\n\n", args) |
| 644 |
return nil |
| 645 |
case hasV2DefinitionTypeAndFormat: |
| 646 |
g.Do("return $.OpenAPIDefinition|raw${\n"+ |
| 647 |
"Schema: spec.Schema{\n"+ |
| 648 |
"SchemaProps: spec.SchemaProps{\n", args) |
| 649 |
g.generateDescription(t.CommentLines) |
| 650 |
g.Do("Type:$.type|raw${}.OpenAPISchemaType(),\n"+ |
| 651 |
"Format:$.type|raw${}.OpenAPISchemaFormat(),\n", args) |
| 652 |
err = g.generateValueValidations(&validationSchema.SchemaProps) |
| 653 |
if err != nil { |
| 654 |
return err |
| 655 |
} |
| 656 |
g.Do("},\n", nil) |
| 657 |
if err := g.generateStructExtensions(t, validationSchema.Extensions); err != nil { |
| 658 |
return err |
| 659 |
} |
| 660 |
g.Do("},\n", nil) |
| 661 |
g.Do("}\n}\n\n", args) |
| 662 |
return nil |
| 663 |
case hasV3OneOfTypes: |
| 664 |
// having v3 oneOf types without custom v2 type or format does not make sense. |
| 665 |
return fmt.Errorf("type %q has v3 one of types but not v2 type or format", t.Name) |
| 666 |
} |
| 667 |
|
| 668 |
g.Do("return $.OpenAPIDefinition|raw${\nSchema: spec.Schema{\nSchemaProps: spec.SchemaProps{\n", args) |
| 669 |
g.generateDescription(t.CommentLines) |
| 670 |
g.Do("Type: []string{\"object\"},\n", nil) |
| 671 |
err = g.generateValueValidations(&validationSchema.SchemaProps) |
| 672 |
if err != nil { |
| 673 |
return err |
| 674 |
} |
| 675 |
|
| 676 |
// write members into a temporary buffer, in order to postpone writing out the Properties field. We only do |
| 677 |
// that if it is not empty. |
| 678 |
propertiesBuf := bytes.Buffer{} |
| 679 |
bsw := g |
| 680 |
bsw.SnippetWriter = generator.NewSnippetWriter(&propertiesBuf, g.context, "$", "$") |
| 681 |
required, err := bsw.generateMembers(t, []string{}) |
| 682 |
if err != nil { |
| 683 |
return err |
| 684 |
} |
| 685 |
if propertiesBuf.Len() > 0 { |
| 686 |
g.Do("Properties: map[string]$.SpecSchemaType|raw${\n", args) |
| 687 |
g.Do(strings.Replace(propertiesBuf.String(), "$", "$\"$\"$", -1), nil) // escape $ (used as delimiter of the templates) |
| 688 |
g.Do("},\n", nil) |
| 689 |
} |
| 690 |
|
| 691 |
if len(required) > 0 { |
| 692 |
g.Do("Required: []string{\"$.$\"},\n", strings.Join(required, "\",\"")) |
| 693 |
} |
| 694 |
g.Do("},\n", nil) |
| 695 |
if err := g.generateStructExtensions(t, validationSchema.Extensions); err != nil { |
| 696 |
return err |
| 697 |
} |
| 698 |
g.Do("},\n", nil) |
| 699 |
|
| 700 |
// Map order is undefined, sort them or we may get a different file generated each time. |
| 701 |
keys := []string{} |
| 702 |
for k := range g.refTypes { |
| 703 |
keys = append(keys, k) |
| 704 |
} |
| 705 |
sort.Strings(keys) |
| 706 |
deps := []string{} |
| 707 |
for _, k := range keys { |
| 708 |
v := g.refTypes[k] |
| 709 |
if t.Kind != types.Struct { |
| 710 |
continue |
| 711 |
} |
| 712 |
if t, _ := openapi.OpenAPITypeFormat(v.String()); t != "" { |
| 713 |
// This is a known type, we do not need a reference to it |
| 714 |
// Will eliminate special case of time.Time |
| 715 |
continue |
| 716 |
} |
| 717 |
deps = append(deps, k) |
| 718 |
} |
| 719 |
if len(deps) > 0 { |
| 720 |
g.Do("Dependencies: []string{\n", args) |
| 721 |
for _, k := range deps { |
| 722 |
t := g.refTypes[k] |
| 723 |
if g.shouldUseOpenAPIModelName(t) { |
| 724 |
g.Do("$.|raw${}.OpenAPIModelName(),", t) |
| 725 |
} else { |
| 726 |
g.Do("\"$.$\",", k) |
| 727 |
} |
| 728 |
} |
| 729 |
g.Do("},\n", nil) |
| 730 |
} |
| 731 |
g.Do("}\n}\n\n", nil) |
| 732 |
} |
| 733 |
return nil |
| 734 |
} |
| 735 |
|
| 736 |
func (g openAPITypeWriter) generateStructExtensions(t *types.Type, otherExtensions map[string]interface{}) error { |
| 737 |
extensions, errors := parseExtensions(t.CommentLines) |
| 738 |
// Initially, we will only log struct extension errors. |
| 739 |
if len(errors) > 0 { |
| 740 |
for _, e := range errors { |
| 741 |
klog.Errorf("[%s]: %s\n", t.String(), e) |
| 742 |
} |
| 743 |
} |
| 744 |
unions, errors := parseUnions(t) |
| 745 |
if len(errors) > 0 { |
| 746 |
for _, e := range errors { |
| 747 |
klog.Errorf("[%s]: %s\n", t.String(), e) |
| 748 |
} |
| 749 |
} |
| 750 |
|
| 751 |
// TODO(seans3): Validate struct extensions here. |
| 752 |
g.emitExtensions(extensions, unions, otherExtensions) |
| 753 |
return nil |
| 754 |
} |
| 755 |
|
| 756 |
func (g openAPITypeWriter) generateMemberExtensions(m *types.Member, parent *types.Type, otherExtensions map[string]interface{}) error { |
| 757 |
extensions, parseErrors := parseExtensions(m.CommentLines) |
| 758 |
validationErrors := validateMemberExtensions(extensions, m) |
| 759 |
errors := append(parseErrors, validationErrors...) |
| 760 |
// Initially, we will only log member extension errors. |
| 761 |
if len(errors) > 0 { |
| 762 |
errorPrefix := fmt.Sprintf("[%s] %s:", parent.String(), m.String()) |
| 763 |
for _, e := range errors { |
| 764 |
klog.V(2).Infof("%s %s\n", errorPrefix, e) |
| 765 |
} |
| 766 |
} |
| 767 |
g.emitExtensions(extensions, nil, otherExtensions) |
| 768 |
return nil |
| 769 |
} |
| 770 |
|
| 771 |
func (g openAPITypeWriter) emitExtensions(extensions []extension, unions []union, otherExtensions map[string]interface{}) { |
| 772 |
// If any extensions exist, then emit code to create them. |
| 773 |
if len(extensions) == 0 && len(unions) == 0 && len(otherExtensions) == 0 { |
| 774 |
return |
| 775 |
} |
| 776 |
g.Do("VendorExtensible: spec.VendorExtensible{\nExtensions: spec.Extensions{\n", nil) |
| 777 |
for _, extension := range extensions { |
| 778 |
g.Do("\"$.$\": ", extension.xName) |
| 779 |
if extension.hasMultipleValues() || extension.isAlwaysArrayFormat() { |
| 780 |
g.Do("[]interface{}{\n", nil) |
| 781 |
} |
| 782 |
for _, value := range extension.values { |
| 783 |
g.Do("\"$.$\",\n", value) |
| 784 |
} |
| 785 |
if extension.hasMultipleValues() || extension.isAlwaysArrayFormat() { |
| 786 |
g.Do("},\n", nil) |
| 787 |
} |
| 788 |
} |
| 789 |
if len(unions) > 0 { |
| 790 |
g.Do("\"x-kubernetes-unions\": []interface{}{\n", nil) |
| 791 |
for _, u := range unions { |
| 792 |
u.emit(g) |
| 793 |
} |
| 794 |
g.Do("},\n", nil) |
| 795 |
} |
| 796 |
|
| 797 |
if len(otherExtensions) > 0 { |
| 798 |
// Sort extension keys to generate deterministic output |
| 799 |
keys := []string{} |
| 800 |
for k := range otherExtensions { |
| 801 |
keys = append(keys, k) |
| 802 |
} |
| 803 |
sort.Strings(keys) |
| 804 |
|
| 805 |
for _, k := range keys { |
| 806 |
v := otherExtensions[k] |
| 807 |
g.Do("$.key$: $.value$,\n", map[string]interface{}{ |
| 808 |
"key": fmt.Sprintf("%#v", k), |
| 809 |
"value": fmt.Sprintf("%#v", v), |
| 810 |
}) |
| 811 |
} |
| 812 |
} |
| 813 |
|
| 814 |
g.Do("},\n},\n", nil) |
| 815 |
} |
| 816 |
|
| 817 |
// TODO(#44005): Move this validation outside of this generator (probably to policy verifier) |
| 818 |
func (g openAPITypeWriter) validatePatchTags(m *types.Member, parent *types.Type) error { |
| 819 |
// TODO: Remove patch struct tag validation because they we are now consuming OpenAPI on server. |
| 820 |
for _, tagKey := range tempPatchTags { |
| 821 |
structTagValue := reflect.StructTag(m.Tags).Get(tagKey) |
| 822 |
commentTagValue, err := getSingleTagsValue(m.CommentLines, tagKey) |
| 823 |
if err != nil { |
| 824 |
return err |
| 825 |
} |
| 826 |
if structTagValue != commentTagValue { |
| 827 |
return fmt.Errorf("Tags in comment and struct should match for member (%s) of (%s)", |
| 828 |
m.Name, parent.Name.String()) |
| 829 |
} |
| 830 |
} |
| 831 |
return nil |
| 832 |
} |
| 833 |
|
| 834 |
func defaultFromComments(comments []string, commentPath string, t *types.Type) (interface{}, *types.Name, error) { |
| 835 |
var tag string |
| 836 |
|
| 837 |
for { |
| 838 |
var err error |
| 839 |
tag, err = getSingleTagsValue(comments, tagDefault) |
| 840 |
if err != nil { |
| 841 |
return nil, nil, err |
| 842 |
} |
| 843 |
|
| 844 |
if t == nil || len(tag) > 0 { |
| 845 |
break |
| 846 |
} |
| 847 |
|
| 848 |
comments = t.CommentLines |
| 849 |
commentPath = t.Name.Package |
| 850 |
switch t.Kind { |
| 851 |
case types.Pointer: |
| 852 |
t = t.Elem |
| 853 |
case types.Alias: |
| 854 |
t = t.Underlying |
| 855 |
default: |
| 856 |
t = nil |
| 857 |
} |
| 858 |
} |
| 859 |
|
| 860 |
if tag == "" { |
| 861 |
return nil, nil, nil |
| 862 |
} |
| 863 |
|
| 864 |
var i interface{} |
| 865 |
if id, ok := parseSymbolReference(tag, commentPath); ok { |
| 866 |
klog.V(5).Infof("%v, %v", id, commentPath) |
| 867 |
return nil, &id, nil |
| 868 |
} else if err := json.Unmarshal([]byte(tag), &i); err != nil { |
| 869 |
return nil, nil, fmt.Errorf("failed to unmarshal default: %v", err) |
| 870 |
} |
| 871 |
return i, nil, nil |
| 872 |
} |
| 873 |
|
| 874 |
var refRE = regexp.MustCompile(`^ref\((?P<reference>[^"]+)\)$`) |
| 875 |
var refREIdentIndex = refRE.SubexpIndex("reference") |
| 876 |
|
| 877 |
// parseSymbolReference looks for strings that match one of the following: |
| 878 |
// - ref(Ident) |
| 879 |
// - ref(pkgpath.Ident) |
| 880 |
// If the input string matches either of these, it will return the (optional) |
| 881 |
// pkgpath, the Ident, and true. Otherwise it will return empty strings and |
| 882 |
// false. |
| 883 |
// |
| 884 |
// This is borrowed from k8s.io/code-generator. |
| 885 |
func parseSymbolReference(s, sourcePackage string) (types.Name, bool) { |
| 886 |
matches := refRE.FindStringSubmatch(s) |
| 887 |
if len(matches) < refREIdentIndex || matches[refREIdentIndex] == "" { |
| 888 |
return types.Name{}, false |
| 889 |
} |
| 890 |
|
| 891 |
contents := matches[refREIdentIndex] |
| 892 |
name := types.ParseFullyQualifiedName(contents) |
| 893 |
if len(name.Package) == 0 { |
| 894 |
name.Package = sourcePackage |
| 895 |
} |
| 896 |
return name, true |
| 897 |
} |
| 898 |
|
| 899 |
func implementsCustomUnmarshalling(t *types.Type) bool { |
| 900 |
switch t.Kind { |
| 901 |
case types.Pointer: |
| 902 |
unmarshaller, isUnmarshaller := t.Elem.Methods["UnmarshalJSON"] |
| 903 |
return isUnmarshaller && unmarshaller.Signature.Receiver.Kind == types.Pointer |
| 904 |
case types.Struct: |
| 905 |
_, isUnmarshaller := t.Methods["UnmarshalJSON"] |
| 906 |
return isUnmarshaller |
| 907 |
default: |
| 908 |
return false |
| 909 |
} |
| 910 |
} |
| 911 |
|
| 912 |
func mustEnforceDefault(t *types.Type, omitEmpty bool) (interface{}, error) { |
| 913 |
// Treat types with custom unmarshalling as a value |
| 914 |
// (Can be alias, struct, or pointer) |
| 915 |
if implementsCustomUnmarshalling(t) { |
| 916 |
// Since Go JSON deserializer always feeds `null` when present |
| 917 |
// to structs with custom UnmarshalJSON, the zero value for |
| 918 |
// these structs is also null. |
| 919 |
// |
| 920 |
// In general, Kubernetes API types with custom marshalling should |
| 921 |
// marshal their empty values to `null`. |
| 922 |
return nil, nil |
| 923 |
} |
| 924 |
|
| 925 |
switch t.Kind { |
| 926 |
case types.Alias: |
| 927 |
return mustEnforceDefault(t.Underlying, omitEmpty) |
| 928 |
case types.Pointer, types.Map, types.Slice, types.Array, types.Interface: |
| 929 |
return nil, nil |
| 930 |
case types.Struct: |
| 931 |
if len(t.Members) == 1 && t.Members[0].Embedded { |
| 932 |
// Treat a struct with a single embedded member the same as an alias |
| 933 |
return mustEnforceDefault(t.Members[0].Type, omitEmpty) |
| 934 |
} |
| 935 |
|
| 936 |
return map[string]interface{}{}, nil |
| 937 |
case types.Builtin: |
| 938 |
if !omitEmpty { |
| 939 |
if zero, ok := openapi.OpenAPIZeroValue(t.String()); ok { |
| 940 |
return zero, nil |
| 941 |
} else { |
| 942 |
return nil, fmt.Errorf("please add type %v to getOpenAPITypeFormat function", t) |
| 943 |
} |
| 944 |
} |
| 945 |
return nil, nil |
| 946 |
default: |
| 947 |
return nil, fmt.Errorf("not sure how to enforce default for %v", t.Kind) |
| 948 |
} |
| 949 |
} |
| 950 |
|
| 951 |
func (g openAPITypeWriter) generateDefault(comments []string, t *types.Type, omitEmpty bool, commentOwningType *types.Type) error { |
| 952 |
def, ref, err := defaultFromComments(comments, commentOwningType.Name.Package, t) |
| 953 |
if err != nil { |
| 954 |
return err |
| 955 |
} |
| 956 |
if enforced, err := mustEnforceDefault(t, omitEmpty); err != nil { |
| 957 |
return err |
| 958 |
} else if enforced != nil { |
| 959 |
if def == nil { |
| 960 |
def = enforced |
| 961 |
} else if !reflect.DeepEqual(def, enforced) { |
| 962 |
enforcedJson, _ := json.Marshal(enforced) |
| 963 |
return fmt.Errorf("invalid default value (%#v) for non-pointer/non-omitempty. If specified, must be: %v", def, string(enforcedJson)) |
| 964 |
} |
| 965 |
} |
| 966 |
if def != nil { |
| 967 |
g.Do("Default: $.$,\n", fmt.Sprintf("%#v", def)) |
| 968 |
} else if ref != nil { |
| 969 |
g.Do("Default: $.|raw$,\n", &types.Type{Name: *ref}) |
| 970 |
} |
| 971 |
return nil |
| 972 |
} |
| 973 |
|
| 974 |
func (g openAPITypeWriter) generateDescription(CommentLines []string) { |
| 975 |
var buffer bytes.Buffer |
| 976 |
delPrevChar := func() { |
| 977 |
if buffer.Len() > 0 { |
| 978 |
buffer.Truncate(buffer.Len() - 1) // Delete the last " " or "\n" |
| 979 |
} |
| 980 |
} |
| 981 |
|
| 982 |
for _, line := range CommentLines { |
| 983 |
// Ignore all lines after --- |
| 984 |
if line == "---" { |
| 985 |
break |
| 986 |
} |
| 987 |
line = strings.TrimRight(line, " ") |
| 988 |
leading := strings.TrimLeft(line, " ") |
| 989 |
switch { |
| 990 |
case len(line) == 0: // Keep paragraphs |
| 991 |
delPrevChar() |
| 992 |
buffer.WriteString("\n\n") |
| 993 |
case strings.HasPrefix(leading, "TODO"): // Ignore one line TODOs |
| 994 |
case strings.HasPrefix(leading, "+"): // Ignore instructions to go2idl |
| 995 |
default: |
| 996 |
if strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t") { |
| 997 |
delPrevChar() |
| 998 |
line = "\n" + line + "\n" // Replace it with newline. This is useful when we have a line with: "Example:\n\tJSON-something..." |
| 999 |
} else { |
| 1000 |
line += " " |
| 1001 |
} |
| 1002 |
buffer.WriteString(line) |
| 1003 |
} |
| 1004 |
} |
| 1005 |
|
| 1006 |
postDoc := strings.TrimSpace(buffer.String()) |
| 1007 |
if len(postDoc) > 0 { |
| 1008 |
g.Do("Description: $.$,\n", fmt.Sprintf("%#v", postDoc)) |
| 1009 |
} |
| 1010 |
} |
| 1011 |
|
| 1012 |
func (g openAPITypeWriter) generateProperty(m *types.Member, parent *types.Type) error { |
| 1013 |
name := getReferableName(m) |
| 1014 |
if name == "" { |
| 1015 |
return nil |
| 1016 |
} |
| 1017 |
validationSchema, err := ParseCommentTags(m.Type, m.CommentLines, markerPrefix) |
| 1018 |
if err != nil { |
| 1019 |
return err |
| 1020 |
} |
| 1021 |
if err := g.validatePatchTags(m, parent); err != nil { |
| 1022 |
return err |
| 1023 |
} |
| 1024 |
g.Do("\"$.$\": {\n", name) |
| 1025 |
if err := g.generateMemberExtensions(m, parent, validationSchema.Extensions); err != nil { |
| 1026 |
return err |
| 1027 |
} |
| 1028 |
g.Do("SchemaProps: spec.SchemaProps{\n", nil) |
| 1029 |
var extraComments []string |
| 1030 |
if enumType, isEnum := g.enumContext.EnumType(m.Type); isEnum { |
| 1031 |
extraComments = enumType.DescriptionLines() |
| 1032 |
} |
| 1033 |
g.generateDescription(append(m.CommentLines, extraComments...)) |
| 1034 |
jsonTags := getJsonTags(m) |
| 1035 |
if len(jsonTags) > 1 && jsonTags[1] == "string" { |
| 1036 |
g.generateSimpleProperty("string", "") |
| 1037 |
g.Do("},\n},\n", nil) |
| 1038 |
return nil |
| 1039 |
} |
| 1040 |
omitEmpty := hasOmitemptyTag(m) |
| 1041 |
if err := g.generateDefault(m.CommentLines, m.Type, omitEmpty, parent); err != nil { |
| 1042 |
return fmt.Errorf("failed to generate default in %v: %v: %v", parent, m.Name, err) |
| 1043 |
} |
| 1044 |
err = g.generateValueValidations(&validationSchema.SchemaProps) |
| 1045 |
if err != nil { |
| 1046 |
return err |
| 1047 |
} |
| 1048 |
t := resolveAliasAndPtrType(m.Type) |
| 1049 |
// If we can get a openAPI type and format for this type, we consider it to be simple property |
| 1050 |
typeString, format := openapi.OpenAPITypeFormat(t.String()) |
| 1051 |
if typeString != "" { |
| 1052 |
g.generateSimpleProperty(typeString, format) |
| 1053 |
if enumType, isEnum := g.enumContext.EnumType(m.Type); isEnum { |
| 1054 |
// original type is an enum, add "Enum: " and the values |
| 1055 |
g.Do("Enum: []interface{}{$.$},\n", strings.Join(enumType.ValueStrings(), ", ")) |
| 1056 |
} |
| 1057 |
g.Do("},\n},\n", nil) |
| 1058 |
return nil |
| 1059 |
} |
| 1060 |
switch t.Kind { |
| 1061 |
case types.Builtin: |
| 1062 |
return fmt.Errorf("please add type %v to getOpenAPITypeFormat function", t) |
| 1063 |
case types.Map: |
| 1064 |
if err := g.generateMapProperty(t); err != nil { |
| 1065 |
return fmt.Errorf("failed to generate map property in %v: %v: %v", parent, m.Name, err) |
| 1066 |
} |
| 1067 |
case types.Slice, types.Array: |
| 1068 |
if err := g.generateSliceProperty(t); err != nil { |
| 1069 |
return fmt.Errorf("failed to generate slice property in %v: %v: %v", parent, m.Name, err) |
| 1070 |
} |
| 1071 |
case types.Struct: |
| 1072 |
g.generateReferenceProperty(t) |
| 1073 |
case types.Interface: |
| 1074 |
// Don't generate references to interfaces since we don't declare them |
| 1075 |
default: |
| 1076 |
return fmt.Errorf("cannot generate spec for type %v", t) |
| 1077 |
} |
| 1078 |
g.Do("},\n},\n", nil) |
| 1079 |
return g.Error() |
| 1080 |
} |
| 1081 |
|
| 1082 |
func (g openAPITypeWriter) generateSimpleProperty(typeString, format string) { |
| 1083 |
g.Do("Type: []string{\"$.$\"},\n", typeString) |
| 1084 |
g.Do("Format: \"$.$\",\n", format) |
| 1085 |
} |
| 1086 |
|
| 1087 |
func (g openAPITypeWriter) generateReferenceProperty(t *types.Type) { |
| 1088 |
g.refTypes[t.Name.String()] = t |
| 1089 |
if g.shouldUseOpenAPIModelName(t) { |
| 1090 |
g.Do("Ref: ref($.|raw${}.OpenAPIModelName()),\n", t) |
| 1091 |
} else { |
| 1092 |
g.Do("Ref: ref(\"$.$\"),\n", t.Name.String()) |
| 1093 |
} |
| 1094 |
} |
| 1095 |
|
| 1096 |
func resolvePtrType(t *types.Type) *types.Type { |
| 1097 |
var prev *types.Type |
| 1098 |
for prev != t { |
| 1099 |
prev = t |
| 1100 |
if t.Kind == types.Pointer { |
| 1101 |
t = t.Elem |
| 1102 |
} |
| 1103 |
} |
| 1104 |
return t |
| 1105 |
} |
| 1106 |
|
| 1107 |
func resolveAliasAndPtrType(t *types.Type) *types.Type { |
| 1108 |
var prev *types.Type |
| 1109 |
for prev != t { |
| 1110 |
prev = t |
| 1111 |
if t.Kind == types.Alias { |
| 1112 |
t = t.Underlying |
| 1113 |
} |
| 1114 |
if t.Kind == types.Pointer { |
| 1115 |
t = t.Elem |
| 1116 |
} |
| 1117 |
} |
| 1118 |
return t |
| 1119 |
} |
| 1120 |
|
| 1121 |
func (g openAPITypeWriter) generateMapProperty(t *types.Type) error { |
| 1122 |
keyType := resolveAliasAndPtrType(t.Key) |
| 1123 |
elemType := resolveAliasAndPtrType(t.Elem) |
| 1124 |
|
| 1125 |
// According to OpenAPI examples, only map from string is supported |
| 1126 |
if keyType.Name.Name != "string" { |
| 1127 |
return fmt.Errorf("map with non-string keys are not supported by OpenAPI in %v", t) |
| 1128 |
} |
| 1129 |
|
| 1130 |
g.Do("Type: []string{\"object\"},\n", nil) |
| 1131 |
g.Do("AdditionalProperties: &spec.SchemaOrBool{\nAllows: true,\nSchema: &spec.Schema{\nSchemaProps: spec.SchemaProps{\n", nil) |
| 1132 |
typeString, format := openapi.OpenAPITypeFormat(elemType.String()) |
| 1133 |
if typeString != "" { |
| 1134 |
g.generateSimpleProperty(typeString, format) |
| 1135 |
if enumType, isEnum := g.enumContext.EnumType(t.Elem); isEnum { |
| 1136 |
// original type is an enum, add "Enum: " and the values |
| 1137 |
g.Do("Enum: []interface{}{$.$},\n", strings.Join(enumType.ValueStrings(), ", ")) |
| 1138 |
} |
| 1139 |
g.Do("},\n},\n},\n", nil) |
| 1140 |
return nil |
| 1141 |
} |
| 1142 |
switch elemType.Kind { |
| 1143 |
case types.Builtin: |
| 1144 |
return fmt.Errorf("please add type %v to getOpenAPITypeFormat function", elemType) |
| 1145 |
case types.Struct: |
| 1146 |
g.generateReferenceProperty(elemType) |
| 1147 |
case types.Slice, types.Array: |
| 1148 |
if err := g.generateSliceProperty(elemType); err != nil { |
| 1149 |
return err |
| 1150 |
} |
| 1151 |
case types.Map: |
| 1152 |
if err := g.generateMapProperty(elemType); err != nil { |
| 1153 |
return err |
| 1154 |
} |
| 1155 |
default: |
| 1156 |
return fmt.Errorf("map Element kind %v is not supported in %v", elemType.Kind, t.Name) |
| 1157 |
} |
| 1158 |
g.Do("},\n},\n},\n", nil) |
| 1159 |
return nil |
| 1160 |
} |
| 1161 |
|
| 1162 |
func (g openAPITypeWriter) generateSliceProperty(t *types.Type) error { |
| 1163 |
elemType := resolveAliasAndPtrType(t.Elem) |
| 1164 |
g.Do("Type: []string{\"array\"},\n", nil) |
| 1165 |
g.Do("Items: &spec.SchemaOrArray{\nSchema: &spec.Schema{\nSchemaProps: spec.SchemaProps{\n", nil) |
| 1166 |
typeString, format := openapi.OpenAPITypeFormat(elemType.String()) |
| 1167 |
if typeString != "" { |
| 1168 |
g.generateSimpleProperty(typeString, format) |
| 1169 |
if enumType, isEnum := g.enumContext.EnumType(t.Elem); isEnum { |
| 1170 |
// original type is an enum, add "Enum: " and the values |
| 1171 |
g.Do("Enum: []interface{}{$.$},\n", strings.Join(enumType.ValueStrings(), ", ")) |
| 1172 |
} |
| 1173 |
g.Do("},\n},\n},\n", nil) |
| 1174 |
return nil |
| 1175 |
} |
| 1176 |
switch elemType.Kind { |
| 1177 |
case types.Builtin: |
| 1178 |
return fmt.Errorf("please add type %v to getOpenAPITypeFormat function", elemType) |
| 1179 |
case types.Struct: |
| 1180 |
g.generateReferenceProperty(elemType) |
| 1181 |
case types.Slice, types.Array: |
| 1182 |
if err := g.generateSliceProperty(elemType); err != nil { |
| 1183 |
return err |
| 1184 |
} |
| 1185 |
case types.Map: |
| 1186 |
if err := g.generateMapProperty(elemType); err != nil { |
| 1187 |
return err |
| 1188 |
} |
| 1189 |
default: |
| 1190 |
return fmt.Errorf("slice Element kind %v is not supported in %v", elemType.Kind, t) |
| 1191 |
} |
| 1192 |
g.Do("},\n},\n},\n", nil) |
| 1193 |
return nil |
| 1194 |
} |