...

Source file src/github.com/openshift/api/openapi/cmd/models-schema/main.go

Documentation: github.com/openshift/api/openapi/cmd/models-schema

     1  package main
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"os"
     7  	"strings"
     8  
     9  	"github.com/openshift/api/openapi/generated_openapi"
    10  	"k8s.io/kube-openapi/pkg/common"
    11  	"k8s.io/kube-openapi/pkg/validation/spec"
    12  )
    13  
    14  // Outputs openAPI schema JSON containing the schema definitions in zz_generated.openapi.go.
    15  // pulled from model_schema command of k/k
    16  func main() {
    17  	err := output()
    18  	if err != nil {
    19  		os.Stderr.WriteString(fmt.Sprintf("Failed: %v", err))
    20  		os.Exit(1)
    21  	}
    22  }
    23  
    24  func output() error {
    25  	refFunc := func(name string) spec.Ref {
    26  		return spec.MustCreateRef(fmt.Sprintf("#/definitions/%s", friendlyName(name)))
    27  	}
    28  	defs := generated_openapi.GetOpenAPIDefinitions(refFunc)
    29  	schemaDefs := make(map[string]spec.Schema, len(defs))
    30  	for k, v := range defs {
    31  		// Replace top-level schema with v2 if a v2 schema is embedded
    32  		// so that the output of this program is always in OpenAPI v2.
    33  		// This is done by looking up an extension that marks the embedded v2
    34  		// schema, and, if the v2 schema is found, make it the resulting schema for
    35  		// the type.
    36  		if schema, ok := v.Schema.Extensions[common.ExtensionV2Schema]; ok {
    37  			if v2Schema, isOpenAPISchema := schema.(spec.Schema); isOpenAPISchema {
    38  				schemaDefs[friendlyName(k)] = v2Schema
    39  				continue
    40  			}
    41  		}
    42  
    43  		schemaDefs[friendlyName(k)] = v.Schema
    44  	}
    45  	data, err := json.Marshal(&spec.Swagger{
    46  		SwaggerProps: spec.SwaggerProps{
    47  			Definitions: schemaDefs,
    48  			Info: &spec.Info{
    49  				InfoProps: spec.InfoProps{
    50  					Title:   "Kubernetes",
    51  					Version: "unversioned",
    52  				},
    53  			},
    54  			Swagger: "2.0",
    55  		},
    56  	})
    57  	if err != nil {
    58  		return fmt.Errorf("error serializing api definitions: %w", err)
    59  	}
    60  	os.Stdout.Write(data)
    61  	return nil
    62  }
    63  
    64  // From vendor/k8s.io/apiserver/pkg/endpoints/openapi/openapi.go
    65  func friendlyName(name string) string {
    66  	nameParts := strings.Split(name, "/")
    67  	// Reverse first part. e.g., io.k8s... instead of k8s.io...
    68  	if len(nameParts) > 0 && strings.Contains(nameParts[0], ".") {
    69  		parts := strings.Split(nameParts[0], ".")
    70  		for i, j := 0, len(parts)-1; i < j; i, j = i+1, j-1 {
    71  			parts[i], parts[j] = parts[j], parts[i]
    72  		}
    73  		nameParts[0] = strings.Join(parts, ".")
    74  	}
    75  	return strings.Join(nameParts, ".")
    76  }
    77  

View as plain text