codegen

package
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 16, 2021 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Overview

Package codegen provides functions to generate Go code from OpenAPI specifications.

Index

Constants

This section is empty.

Variables

View Source
var TemplateFunctions = template.FuncMap{
	"genParamArgs":               genParamArgs,
	"genParamNames":              genParamNames,
	"getResponseTypeDefinitions": getResponseTypeDefinitions,
	"genTaggedMiddleware":        getTaggedMiddlewares,
	"toStringArray":              toStringArray,

	"swaggerURIToChiURI": SwaggerURIToChiURI,

	"statusCode": responseNameToStatusCode,

	"ucFirst": snaker.ForceCamelIdentifier,
	"lower":   strings.ToLower,
	"title":   strings.Title,
}

TemplateFunctions generates the list of utlity and helpfer functions used by the templates.

Functions

func EscapePathElements

func EscapePathElements(path string) string

EscapePathElements escapes non path parameters in path and url encodes them.

func GenFieldsFromProperties

func GenFieldsFromProperties(props []Property) []string

GenFieldsFromProperties produces corresponding field names with JSON annotations

func GenStructFromAllOf

func GenStructFromAllOf(allOf []*openapi3.SchemaRef, path []string) (string, error)

GenStructFromAllOf function generates an object that is the union of the objects in the input array. In the case of Ref objects, we use an embedded struct, otherwise, we inline the fields.

func GenStructFromSchema

func GenStructFromSchema(schema Schema) string

GenStructFromSchema creates a struct definition from the given Schema. If the schema has additional properties, it is defined as a map[string]Type.

func Generate

func Generate(swagger *openapi3.T, packageName string, opts Options) (string, error)

Generate uses the Go templating engine to generate all of our server wrappers from the descriptions we've built up above from the schema objects.

func GenerateAdditionalPropertyBoilerplate

func GenerateAdditionalPropertyBoilerplate(t *template.Template, typeDefs []TypeDefinition) (string, error)

GenerateAdditionalPropertyBoilerplate creates any glue code for interfacing with additional properties and JSON marshaling.

func GenerateBodyDefinitions

func GenerateBodyDefinitions(operationID string, bodyOrRef *openapi3.RequestBodyRef) ([]RequestBodyDefinition, []TypeDefinition, error)

GenerateBodyDefinitions returns the Swagger body definitions into a list of our body definitions which will be used for code generation.

func GenerateChiServer

func GenerateChiServer(t *template.Template, operations []OperationDefinition) (string, error)

GenerateChiServer generates codee for the chi server for ops.

func GenerateConstants

func GenerateConstants(t *template.Template, ops []OperationDefinition) (string, error)

GenerateConstants creates operation ids, context keys, paths, etc. to be exported as constants

func GenerateEnumTypes

func GenerateEnumTypes(t *template.Template, types []TypeDefinition) (string, error)

GenerateEnumTypes makes types for any enums in types.

func GenerateEnums

func GenerateEnums(t *template.Template, types []TypeDefinition) (string, error)

GenerateEnums makes definitions for any enums defined in types.

func GenerateImports

func GenerateImports(t *template.Template, externalImports []string, packageName string) (string, error)

GenerateImports creates import statements and the package definition.

func GenerateInlinedSpec

func GenerateInlinedSpec(t *template.Template, importMapping importMap, swagger *openapi3.T) (string, error)

GenerateInlinedSpec generates a gzipped, base64 encoded JSON representation of the swagger definition, which is embedded inside the generated code.

func GenerateTemplates

func GenerateTemplates(templates []string, t *template.Template, ops interface{}) (string, error)

GenerateTemplates generates templates

func GenerateTypeDefinitions

func GenerateTypeDefinitions(t *template.Template, swagger *openapi3.T, ops []OperationDefinition, excludeSchemas []string) (string, error)

GenerateTypeDefinitions produces the type definitions in ops and executes the template.

func GenerateTypes

func GenerateTypes(t *template.Template, types []TypeDefinition) (string, error)

GenerateTypes is a helper function to execute the templates for type defs.

func GenerateTypesForOperations

func GenerateTypesForOperations(t *template.Template, ops []OperationDefinition) (string, error)

GenerateTypesForOperations prooduces code all types used by ops.

func IsGoIdentity

func IsGoIdentity(str string) bool

IsGoIdentity checks if str is a valid go identifier.

func IsGoKeyword

func IsGoKeyword(str string) bool

IsGoKeyword checks if str is a reserved keyword. Returns whether the given string is a go keyword

func IsGoTypeReference

func IsGoTypeReference(ref string) bool

IsGoTypeReference checks if ref links to a valid go type. #/components/schemas/Foo -> true ./local/file.yml#/components/parameters/Bar -> true ./local/file.yml -> false

func IsPredeclaredGoIdentifier

func IsPredeclaredGoIdentifier(str string) bool

IsPredeclaredGoIdentifier returns whether str is a go indentifier.

func IsValidGoIdentity

func IsValidGoIdentity(str string) bool

IsValidGoIdentity checks if str can be used as a name of variable, constant, or type.

func IsWholeDocumentReference

func IsWholeDocumentReference(ref string) bool

IsWholeDocumentReference checks if ref is a whole document reference. #/components/schemas/Foo -> false ./local/file.yml#/components/parameters/Bar -> false ./local/file.yml -> true http://example.com/schemas/document.json -> true http://example.com/schemas/document.json#/Foo -> false

func LowercaseFirstCharacter

func LowercaseFirstCharacter(str string) string

LowercaseFirstCharacter lowercases te first character of str.

func OrderedParamsFromURI

func OrderedParamsFromURI(uri string) []string

OrderedParamsFromURI returns argument names in uri. Given /path/{param1}/{.param2*}/{?param3}, returns [param1, param2, param3]

func PathToTypeName

func PathToTypeName(path []string) string

PathToTypeName converts path to a go type name. It converts each entry in path to camel case and joins them with _.

func PropertiesEqual

func PropertiesEqual(a, b Property) bool

PropertiesEqual returns if a and b can be considered to be the same. a and b are the same if they have the same field name, same type, and are both required (or not).

func RefPathToGoType

func RefPathToGoType(refPath string) (string, error)

RefPathToGoType converts refPath to a Go type name. #/components/schemas/Foo -> Foo #/components/parameters/Bar -> Bar #/components/responses/Baz -> Baz Remote components (document.json#/Foo) are supported if they present in --import-mapping URL components (http://deepmap.com/schemas/document.json#/Foo) are supported if they present in --import-mapping Remote and URL also support standard local paths even though the spec doesn't mention them.

func ReplacePathParamsWithStr

func ReplacePathParamsWithStr(uri string) string

ReplacePathParamsWithStr replaces uri parameters with %s

func SanitizeCode

func SanitizeCode(goCode string) string

SanitizeCode runs sanitizers across the generated Go code to ensure the generated code will be able to compile.

func SanitizeEnumNames

func SanitizeEnumNames(enumNames []string) map[string]string

SanitizeEnumNames removes illegal and duplicates chars in enum names.

func SanitizeGoIdentity

func SanitizeGoIdentity(str string) string

SanitizeGoIdentity replaces illegal characters in str.

func SchemaHasAdditionalProperties

func SchemaHasAdditionalProperties(schema *openapi3.Schema) bool

SchemaHasAdditionalProperties checks if schema has additional properties.

According to the spec, additionalProperties may be true, false, or a schema. If not present, true is implied. If it's a schema, true is implied. If it's false, no additional properties are allowed. We're going to act a little differently, in that if you want additionalProperties code to be generated, you must specify an additionalProperties type If additionalProperties it true/false, this field will be non-nil.

func SchemaNameToTypeName

func SchemaNameToTypeName(name string) string

SchemaNameToTypeName converts name to a valid Go type name. It converts name to camel case and is valid in Go.

func SortedContentKeys

func SortedContentKeys(dict openapi3.Content) []string

SortedContentKeys returns the keys of dict alphabetically.

func SortedOperationsKeys

func SortedOperationsKeys(dict map[string]*openapi3.Operation) []string

SortedOperationsKeys returns the keys of dict alphabetically.

func SortedParameterKeys

func SortedParameterKeys(dict map[string]*openapi3.ParameterRef) []string

SortedParameterKeys returns the keys of dict alphabetically.

func SortedPathsKeys

func SortedPathsKeys(dict openapi3.Paths) []string

SortedPathsKeys returns the keys of dict alphabetically.

func SortedRequestBodyKeys

func SortedRequestBodyKeys(dict map[string]*openapi3.RequestBodyRef) []string

SortedRequestBodyKeys returns the keys of dict alphabetically.

func SortedResponsesKeys

func SortedResponsesKeys(dict openapi3.Responses) []string

SortedResponsesKeys returns the keys of dict alphabetically.

func SortedSchemaKeys

func SortedSchemaKeys(dict map[string]*openapi3.SchemaRef) []string

SortedSchemaKeys returns the keys of dict in alphabetically.

func SortedSecurityRequirementKeys

func SortedSecurityRequirementKeys(dict openapi3.SecurityRequirement) []string

SortedSecurityRequirementKeys eturns the keys of dict alphabetically.

func SortedStringKeys

func SortedStringKeys(dict map[string]string) []string

SortedStringKeys returns the keys of dict alphabetically.

func StringInArray

func StringInArray(str string, strs []string) bool

StringInArray returns if strs contains str.

func StringToGoComment

func StringToGoComment(in string) string

StringToGoComment renders a possible multi-line string to a valid Go-Comment. Each line is prefixed as a comment.

func SwaggerURIToChiURI

func SwaggerURIToChiURI(uri string) string

SwaggerURIToChiURI converts uri to a Chi-style URI. It replaces all swagger parameters with {param}.

Valid input parameters are:

{param}
{param*}
{.param}
{.param*}
{;param}
{;param*}
{?param}
{?param*}

func ToCamelCase

func ToCamelCase(str string) string

ToCamelCase converts a string to camel case with proper Go initialisms.

func ToSnakeCase added in v0.1.1

func ToSnakeCase(str string) string

ToSnakeCase converts a string to snake case.

func UppercaseFirstCharacter

func UppercaseFirstCharacter(str string) string

UppercaseFirstCharacter uppercases the first character of str.

Types

type Constants

type Constants struct {
	// SecuritySchemeProviderNames holds all provider names for security schemes.
	SecuritySchemeProviderNames []string
	// EnumDefinitions holds type and value information for all enums
	EnumDefinitions []EnumDefinition
}

Constants holds the list of definitions that will be defined as constants.

type EnumDefinition

type EnumDefinition struct {
	Schema       Schema
	TypeName     string
	ValueWrapper string
}

EnumDefinition holds type information for enum

type FieldDescriptor

type FieldDescriptor struct {
	Required bool   // Is the schema required? If not, we'll pass by pointer
	GoType   string // The Go type needed to represent the json type.
	GoName   string // The Go compatible type name for the type
	JSONName string // The json type name for the type
	IsRef    bool   // Is this schema a reference to predefined object?
}

FieldDescriptor describes a field.

type OperationDefinition

type OperationDefinition struct {
	OperationID string // The operation_id description from Swagger, used to generate function names

	PathParams          []ParameterDefinition // Parameters in the path, eg, /path/:param
	HeaderParams        []ParameterDefinition // Parameters in HTTP headers
	QueryParams         []ParameterDefinition // Parameters in the query, /path?param
	CookieParams        []ParameterDefinition // Parameters in cookies
	TypeDefinitions     []TypeDefinition      // These are all the types we need to define for this operation
	SecurityDefinitions []SecurityDefinition  // These are the security providers
	BodyRequired        bool
	Bodies              []RequestBodyDefinition // The list of bodies for which to generate handlers.
	Summary             string                  // Summary string from Swagger, used to generate a comment
	Method              string                  // GET, POST, DELETE, etc.
	Path                string                  // The Swagger path for the operation, like /resource/{id}
	Middlewares         []string                // Sent as part of x-go-middlewares.
	Spec                *openapi3.Operation
}

OperationDefinition represents an Operation.

func OperationDefinitions

func OperationDefinitions(swagger *openapi3.T) ([]OperationDefinition, error)

OperationDefinitions returns all operations for a swagger definition.

func (*OperationDefinition) AllParams

func (o *OperationDefinition) AllParams() []ParameterDefinition

AllParams returns all params.

func (*OperationDefinition) GetResponseTypeDefinitions

func (o *OperationDefinition) GetResponseTypeDefinitions() ([]ResponseTypeDefinition, error)

GetResponseTypeDefinitions produces a list of type definitions for a given Operation for the response types which we know how to parse. These will be turned into fields on a response object for automatic deserialization of responses.

func (*OperationDefinition) Params

Params returns the list of all parameters except Path parameters. Path parameters are handled differently from the rest, since they're mandatory.

func (*OperationDefinition) RequiresParamObject

func (o *OperationDefinition) RequiresParamObject() bool

RequiresParamObject returns if any path parameters exist. If we have parameters other than path parameters, they're bundled into an object.

func (*OperationDefinition) SummaryAsComment

func (o *OperationDefinition) SummaryAsComment() string

SummaryAsComment returns the summary as a multiline comment for o.

type Options

type Options struct {
	GenerateServer bool              // GenerateChiServer specifies whether to generate chi server boilerplate
	GenerateTypes  bool              // GenerateTypes specifies whether to generate type definitions
	EmbedSpec      bool              // Whether to embed the swagger spec in the generated code
	SkipFmt        bool              // Whether to skip go imports on the generated code
	SkipPrune      bool              // Whether to skip pruning unused components on the generated code
	AliasTypes     bool              // Whether to alias types if possible
	IncludeTags    []string          // Only include operations that have one of these tags. Ignored when empty.
	ExcludeTags    []string          // Exclude operations that have one of these tags. Ignored when empty.
	UserTemplates  map[string]string // Override built-in templates from user-provided files
	ImportMapping  map[string]string // ImportMapping specifies the golang package path for each external reference
	ExcludeSchemas []string          // Exclude from generation schemas with given names. Ignored when empty.
}

Options defines the optional code to generate.

Most callers to this package will use Generate.

type ParameterDefinition

type ParameterDefinition struct {
	ParamName string // The original json parameter name, eg param_name
	In        string // Where the parameter is defined - path, header, cookie, query
	Required  bool   // Is this a required parameter?
	Spec      *openapi3.Parameter
	Schema    Schema
}

ParameterDefinition is a definition for a parameter.

func DescribeParameters

func DescribeParameters(params openapi3.Parameters, path []string) ([]ParameterDefinition, error)

DescribeParameters generates descriptors based on params and path. This makes it a lot easier to traverse the data in the template engine.

func FilterParameterDefinitionByType

func FilterParameterDefinitionByType(params []ParameterDefinition, in string) []ParameterDefinition

FilterParameterDefinitionByType returns params which match the the type with in.

func SortParamsByPath

func SortParamsByPath(path string, in []ParameterDefinition) ([]ParameterDefinition, error)

SortParamsByPath sorts in to match those in the path URI.

func (*ParameterDefinition) Explode

func (pd *ParameterDefinition) Explode() bool

Explode returns if pd.Spec is explode. If Explode is nil, it determines Explode based on pd.Spec.In.

func (ParameterDefinition) GoName

func (pd ParameterDefinition) GoName() string

GoName returns the Go name of pd.ParamName.

func (ParameterDefinition) GoVariableName

func (pd ParameterDefinition) GoVariableName() string

GoVariableName returns a safe version of the name of pd's GoName.

func (ParameterDefinition) IndirectOptional

func (pd ParameterDefinition) IndirectOptional() bool

IndirectOptional returns if pd is optiona, directlry or indirectly.

func (*ParameterDefinition) IsJSON

func (pd *ParameterDefinition) IsJSON() bool

IsJSON returns if pd.Spec.Content contains application/json.

func (*ParameterDefinition) IsPassThrough

func (pd *ParameterDefinition) IsPassThrough() bool

IsPassThrough returns if pd is passthrough.

func (*ParameterDefinition) IsStyled

func (pd *ParameterDefinition) IsStyled() bool

IsStyled returns if pdf.Spec.Schema is not nil.

func (*ParameterDefinition) JSONTag

func (pd *ParameterDefinition) JSONTag() string

JSONTag returns the tag for pd. It includes omitempty if it is required.

func (*ParameterDefinition) Style

func (pd *ParameterDefinition) Style() string

Style returns pd.Spec.Style. If not provided, it determines the Style based on pd.Spec.In.

func (ParameterDefinition) TypeDef

func (pd ParameterDefinition) TypeDef() string

TypeDef returns the type definition for a parameter without the leading '*' for optionl types.

type ParameterDefinitions

type ParameterDefinitions []ParameterDefinition

ParameterDefinitions is a slice of ParameterDefinition.

func (ParameterDefinitions) FindByName

func (p ParameterDefinitions) FindByName(name string) *ParameterDefinition

FindByName finds a definition by name.

type Property

type Property struct {
	Description    string
	JSONFieldName  string
	Schema         Schema
	Required       bool
	Nullable       bool
	ExtensionProps *openapi3.ExtensionProps
}

Property represents an OpenAPI property.

func (Property) GoFieldName

func (p Property) GoFieldName() string

GoFieldName returns the Go name of p.

func (Property) GoTypeDef

func (p Property) GoTypeDef() string

GoTypeDef returns the go type of p.

type RefWrapper

type RefWrapper struct {
	Ref       string
	HasValue  bool
	SourceRef interface{}
}

RefWrapper represents a ref wrapped with more information.

type RequestBodyDefinition

type RequestBodyDefinition struct {
	Required bool
	Schema   Schema

	// When we generate type names, we need a Tag for it, such as JSON, in
	// which case we will produce "JSONBody".
	NameTag string

	// This is the content type corresponding to the body, eg, application/json
	ContentType string

	// Whether this is the default body type. For an operation named OpFoo, we
	// will not add suffixes like OpFooJSONBody for this one.
	Default bool
}

RequestBodyDefinition describes a request body

func (RequestBodyDefinition) CustomType

func (r RequestBodyDefinition) CustomType() bool

CustomType returns if body is a custom inline type, or pre-defined. TODO: clean up the templates code, it can be simpler.

func (RequestBodyDefinition) Suffix

func (r RequestBodyDefinition) Suffix() string

Suffix returns "With{r.nameTag}Body" Operation DoFoo would be suffixed with DoFooWithXMLBody.

func (RequestBodyDefinition) TypeDef

func (r RequestBodyDefinition) TypeDef(opID string) *TypeDefinition

TypeDef returns the Go type definition for a request body

type ResponseTypeDefinition

type ResponseTypeDefinition struct {
	TypeDefinition
	// The content type name where this is used, eg, application/json
	ContentTypeName string

	// The type name of a response model.
	ResponseName string
}

ResponseTypeDefinition is an extension of TypeDefinition, specifically for response unmarshaling.

type Schema

type Schema struct {
	GoType  string // The Go type needed to represent the schema
	RefType string // If the type has a type name, this is set

	ArrayType *Schema // The schema of array element

	EnumValues map[string]string // Enum values

	Properties               []Property       // For an object, the fields with names
	HasAdditionalProperties  bool             // Whether we support additional properties
	AdditionalPropertiesType *Schema          // And if we do, their type
	AdditionalTypes          []TypeDefinition // We may need to generate auxiliary helper types, stored here

	SkipOptionalPointer bool // Some types don't need a * in front when they're optional
	Bindable            bool // Indicates whether this type can implement render.Binder

	Description string // The description of the element

	// The original OpenAPIv3 Schema.
	OAPISchema *openapi3.Schema
}

Schema represents an OpenAPI type definition.

func GenerateGoSchema

func GenerateGoSchema(sref *openapi3.SchemaRef, path []string) (Schema, error)

GenerateGoSchema generates the schema for sref. If it cannot properly resolve the type of sref, it returns map[string]interface{} or interface{}.

func MergeSchemas

func MergeSchemas(allOf []*openapi3.SchemaRef, path []string) (Schema, error)

MergeSchemas merges all the fields in the schemas supplied together.

func (Schema) AdditionalTypeDefs

func (s Schema) AdditionalTypeDefs() []TypeDefinition

AdditionalTypeDefs returns all type definitions of the properties of s, and then any additional types in s.

func (Schema) IsRef

func (s Schema) IsRef() bool

IsRef returns if s references another type.

func (*Schema) MergeProperty

func (s *Schema) MergeProperty(p Property) error

MergeProperty adds p to the properties of s. p must not already be a property in the schema.

func (Schema) TypeDecl

func (s Schema) TypeDecl() string

TypeDecl returns the Go type needed to represent the schema. If s has a reference, it returns the type of the reference.

type SchemaDescriptor

type SchemaDescriptor struct {
	Fields                   []FieldDescriptor
	HasAdditionalProperties  bool
	AdditionalPropertiesType string
}

SchemaDescriptor describes a Schema, a type definition.

type SecurityDefinition

type SecurityDefinition struct {
	ProviderName string
	Scopes       []string
}

SecurityDefinition represents an OpenAPI security definition.

func DescribeSecurityDefinition

func DescribeSecurityDefinition(srs openapi3.SecurityRequirements) []SecurityDefinition

DescribeSecurityDefinition returns all security definitions in srs.

type TypeDefinition

type TypeDefinition struct {
	// The name of the type, eg, type <...> Person
	TypeName string

	// The name of the corresponding JSON description, as it will sometimes
	// differ due to invalid characters.
	JSONName string

	// This is the Schema wrapper is used to populate the type description
	Schema Schema
}

TypeDefinition describes a Go type definition in generated code.

Let's use this example schema: components:

schemas:
  Person:
    type: object
    properties:
    name:
      type: string

func GenerateParamsTypes

func GenerateParamsTypes(op OperationDefinition) []TypeDefinition

GenerateParamsTypes defines the schema for a parameters definition object which encapsulates all the query, header and cookie parameters for an operation.

func GenerateTypeDefsForOperation

func GenerateTypeDefsForOperation(op OperationDefinition) []TypeDefinition

GenerateTypeDefsForOperation returns the type definitions for op.

func GenerateTypesForParameters

func GenerateTypesForParameters(t *template.Template, params map[string]*openapi3.ParameterRef) ([]TypeDefinition, error)

GenerateTypesForParameters creates type definitions for any custom types defined in the components/parameters section of the Swagger spec.

func GenerateTypesForRequestBodies

func GenerateTypesForRequestBodies(t *template.Template, bodies map[string]*openapi3.RequestBodyRef) ([]TypeDefinition, error)

GenerateTypesForRequestBodies creates definitions for any custom types defined in the components/requestBodies section of the Swagger spec.

func GenerateTypesForResponses

func GenerateTypesForResponses(t *template.Template, responses openapi3.Responses) ([]TypeDefinition, error)

GenerateTypesForResponses makes definitions for any custom types defined in the components/responses section of the Swagger spec.

func GenerateTypesForSchemas

func GenerateTypesForSchemas(t *template.Template, schemas map[string]*openapi3.SchemaRef, excludeSchemas []string) ([]TypeDefinition, error)

GenerateTypesForSchemas creates type definitions for any custom types defined in the components/schemas section of the Swagger spec.

func (*TypeDefinition) CanAlias

func (t *TypeDefinition) CanAlias() bool

CanAlias returns whether the name of the type can be aliased. It can be aliased if t's Schema is a reference or an array to a reference.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL