gen

package
v0.0.0-...-6c20dd6 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2024 License: Apache-2.0 Imports: 39 Imported by: 0

Documentation

Index

Constants

View Source
const (
	KclNoneValue  = "None"
	KclTrueValue  = "True"
	KclFalseValue = "False"
)
View Source
const (
	ExtensionKclType        = "x-kcl-type"
	ExtensionKclDecorators  = "x-kcl-decorators"
	ExtensionKclUnionTypes  = "x-kcl-union-types"
	ExtensionKclDictKeyType = "x-kcl-dict-key-type"
)

Variables

View Source
var ErrNoKclFiles = errors.New("No input KCL files")

No kcl files

View Source
var (
	ErrNoSchemaFound = errors.New("no expected schema found")
)

Functions

func ExportOpenAPITypeToSchema

func ExportOpenAPITypeToSchema(ty *KclOpenAPIType) *openapi3.SchemaRef

ExportOpenAPITypeToSchema exports open api v3 schema ref from the kcl type.

func ExportOpenAPIV3Spec

func ExportOpenAPIV3Spec(pkgPath string) (*openapi3.T, error)

ExportOpenAPIV3Spec exports open api v3 spec of a kcl package

func ExportSwaggerV2SpecString

func ExportSwaggerV2SpecString(pkgPath string) (string, error)

ExportSwaggerV2SpecString exports swagger v2 spec of a kcl package

func GenGo

func GenGo(w io.Writer, filename string, src interface{}, opts *GenGoOptions) error

GenGo translate kcl schema type to go struct.

func GenKcl

func GenKcl(w io.Writer, filename string, src interface{}, opts *GenKclOptions) error

GenKcl translate other formats to kcl schema code. Now support go struct and json schema.

func GenProto

func GenProto(filename string, src interface{}, opt *Options) (string, error)

GenProto translate kcl schema type to protobuf message.

func GetPkgDir

func GetPkgDir(base string, pkgName string) string

func GetSchemaTypeMappingByPath

func GetSchemaTypeMappingByPath(root string) (map[string]map[string]*NamedKclType, error)

Get all schema type mapping within the root path.

func IsEmpty

func IsEmpty(rv reflect.Value) bool

func IsLitType

func IsLitType(typ *pb.KclType) (ok bool, basicTyp, litValue string)

func IsNil

func IsNil(val reflect.Value) bool

func IsSchema

func IsSchema(kt *NamedKclType) bool

IsSchema returns true if the type is schema.

func IsSchemaInstance

func IsSchemaInstance(kt *NamedKclType) bool

IsSchemaInstance returns true if the type is schema instance.

func IsSchemaNamed

func IsSchemaNamed(kt *NamedKclType, name string) bool

IsSchemaNamed returns true if the type is schema and the name is equal to the given name.

func IsSchemaType

func IsSchemaType(kt *NamedKclType) bool

IsSchemaType returns true if the type is schema type.

func IsZero

func IsZero(rv reflect.Value) bool

func KclTypeOfGo

func KclTypeOfGo(rv reflect.Value) (string, error)

func Marshal

func Marshal(v any) ([]byte, error)

Marshal returns a KCL representation of the Go value.

func MarshalTOML

func MarshalTOML(data *yaml.MapSlice) ([]byte, error)

Marshal returns a TOML representation of the Go value.

func MarshalYamlMapSliceToTOML

func MarshalYamlMapSliceToTOML(data *yaml.MapSlice) ([]byte, error)

MarshalYamlMapSliceToTOML convert an ordered yaml data to an ordered toml

func PackageName

func PackageName(pkgPath string, t *kcl.KclType) string

PackageName resolves the package name from the PkgPath and the PkgRoot of the type

func PtrTo

func PtrTo(t reflect.Type) reflect.Type

func Ref2SchemaId

func Ref2SchemaId(ref string) string

func SchemaId

func SchemaId(pkgPath string, t *kcl.KclType) string

func SchemaId2Ref

func SchemaId2Ref(id string) string

func SwaggerV2ToOpenAPIV3Spec

func SwaggerV2ToOpenAPIV3Spec(s *SwaggerV2Spec) *openapi3.T

SwaggerV2ToOpenAPIV3Spec converts swagger v2 spec to open api v3 spec.

Types

type CastingOption

type CastingOption int
const (
	OriginalName CastingOption = iota
	SnakeCase
	CamelCase
)

type Field

type Field struct {
	// contains filtered or unexported fields
}

func TypeFields

func TypeFields(t reflect.Type, v reflect.Value) []Field

TypeFields returns a list of fields.

type Format

type Format string
const (
	Html     Format = "html"
	Markdown Format = "md"
	OpenAPI  Format = "openapi"
)

type GenContext

type GenContext struct {
	// PackagePath is the package path to the package or module to generate docs for
	PackagePath string
	// Format is the doc format to output
	Format Format
	// Target is the target directory to output the docs
	Target string
	// IgnoreDeprecated defines whether to generate documentation for deprecated schemas
	IgnoreDeprecated bool
	// EscapeHtml defines whether to escape html symbols when the output format is markdown
	EscapeHtml bool
	// SchemaDocTmpl defines the content of the schemaDoc template
	SchemaDocTmpl string
	// PackageDocTmpl defines the content of the packageDoc template
	PackageDocTmpl string
	// SchemaListDocTmpl defines the content of the schemaListDoc template
	SchemaListDocTmpl string
	// Template is the doc render template
	Template *template.Template
}

GenContext defines the context during the generation

func (*GenContext) GenDoc

func (g *GenContext) GenDoc() error

GenDoc generate document files from KCL source files

func (*GenContext) RenderSwaggerV2

func (g *GenContext) RenderSwaggerV2(spec *SwaggerV2Spec) error

RenderSwaggerV2 renders swagger v2 definitions to generated documents.

type GenGoOptions

type GenGoOptions struct {
	Package    string
	AnyType    string
	UseValue   bool
	RenameFunc func(string) string
}

type GenKclOptions

type GenKclOptions struct {
	Mode                  Mode
	CastingOption         CastingOption
	UseIntegersForNumbers bool
}

type GenOpts

type GenOpts struct {
	// Path is the path to the directory or file to generate docs for
	Path string
	// Format is the doc format to output
	Format string
	// Target is the target directory to output the docs
	Target string
	// IgnoreDeprecated defines whether to generate documentation for deprecated schemas
	IgnoreDeprecated bool
	// EscapeHtml defines whether to escape html symbols when the output format is markdown
	EscapeHtml bool
	// TemplateDir defines the relative path from the package root to the template directory
	TemplateDir string
}

GenOpts is the user interface defines the doc generate options

func (*GenOpts) ValidateComplete

func (opts *GenOpts) ValidateComplete() (*GenContext, error)

type Generator

type Generator interface {
	GenFromSource(w io.Writer, filename string, src interface{}) error
	GenFromTypes(w io.Writer, types ...*pb.KclType)
	GenSchema(w io.Writer, typ *pb.KclType)
	GetTypeName(typ *pb.KclType) string
}

type KclExample

type KclExample struct {
	Summary     string `json:"summary,omitempty"`
	Description string `json:"description,omitempty"`
	Value       string `json:"value,omitempty"`
}

KclExample defines the example code snippet of the schema

type KclExtensions

type KclExtensions struct {
	XKclModelType   *XKclModelType    `json:"x-kcl-type,omitempty"`
	XKclDecorators  XKclDecorators    `json:"x-kcl-decorators,omitempty"`
	XKclUnionTypes  []*KclOpenAPIType `json:"x-kcl-union-types,omitempty"`
	XKclDictKeyType *KclOpenAPIType   `json:"x-kcl-dict-key-type,omitempty"` // dict key type
}

KclExtensions defines all the KCL specific extensions patched to OpenAPI

type KclModelImportInfo

type KclModelImportInfo struct {
	Package string `json:"package,omitempty"` // import package path
	Alias   string `json:"alias,omitempty"`   // import alias
}

KclModelImportInfo defines how to import the current type

type KclOpenAPIType

type KclOpenAPIType struct {
	Type                 SwaggerTypeName            `json:"type,omitempty"`                 // object, string, array, integer, number, bool
	Format               TypeFormat                 `json:"format,omitempty"`               // type format
	Default              string                     `json:"default,omitempty"`              // default value
	Enum                 []string                   `json:"enum,omitempty"`                 // enum values
	ReadOnly             bool                       `json:"readOnly,omitempty"`             // readonly
	Description          string                     `json:"description,omitempty"`          // description
	Properties           map[string]*KclOpenAPIType `json:"properties,omitempty"`           // schema properties
	Required             []string                   `json:"required,omitempty"`             // list of required schema property names
	Items                *KclOpenAPIType            `json:"items,omitempty"`                // list item type
	AdditionalProperties *KclOpenAPIType            `json:"additionalProperties,omitempty"` // dict value type
	Examples             map[string]KclExample      `json:"examples,omitempty"`             // examples
	ExternalDocs         string                     `json:"externalDocs,omitempty"`         // externalDocs
	Ref                  string                     `json:"ref,omitempty"`                  // reference to schema path
	BaseSchema           *KclOpenAPIType            `json:"baseSchema,omitempty"`
	ReferencedBy         []string                   `json:"referencedBy,omitempty"` // schemas referncing this schema
	*KclExtensions                                  // x-kcl- extensions
}

KclOpenAPIType defines the KCL representation of SchemaObject field in Swagger v2.0. And the mapping between kcl type and the Kcl OpenAPI type is:

## basic types

┌───────────────────────┬──────────────────────────────────────┐
│      KCL Types        │      KCL OpenAPI Types (format)      │
├───────────────────────┼──────────────────────────────────────┤
│       str             │         string                       │
├───────────────────────┼──────────────────────────────────────┤
│       int             │        integer(int64)                │
├───────────────────────┼──────────────────────────────────────┤
│      float            │         number(float)                │
├───────────────────────┼──────────────────────────────────────┤
│       bool            │             bool                     │
├───────────────────────┼──────────────────────────────────────┤
│   number_multiplier   │    string(units.NumberMultiplier)    │
└───────────────────────┴──────────────────────────────────────┘

## Composite Types

┌───────────────────────┬───────────────────────────────────────────────────────────────────────────────┐
│      KCL Types        │      KCL OpenAPI Types (format)                                               │
├───────────────────────┼───────────────────────────────────────────────────────────────────────────────┤
│       list            │   type:array, items: itemType                                                 │
├───────────────────────┼───────────────────────────────────────────────────────────────────────────────┤
│       dict            │   type: object, additionalProperties: valueType, x-kcl-dict-key-type: keyType │
├───────────────────────┼───────────────────────────────────────────────────────────────────────────────┤
│      union            │   type: object, x-kcl-union-types: unionTypes                                 │
├───────────────────────┼───────────────────────────────────────────────────────────────────────────────┤
│      schema           │   type: object, properties: propertyTypes, required, x-kcl-type               │
├───────────────────────┼───────────────────────────────────────────────────────────────────────────────┤
│    nested schema      │   type: object, ref: jsonRefPath                                              │
└───────────────────────┴───────────────────────────────────────────────────────────────────────────────┘

func GetKclOpenAPIType

func GetKclOpenAPIType(pkgPath string, from *kcl.KclType, nested bool) *KclOpenAPIType

GetKclOpenAPIType converts the kcl.KclType(the representation of Type in KCL API) to KclOpenAPIType(the representation of Type in KCL Open API)

func (*KclOpenAPIType) GetAnyEnum

func (tpe *KclOpenAPIType) GetAnyEnum() []interface{}

func (*KclOpenAPIType) GetExtensionsMapping

func (tpe *KclOpenAPIType) GetExtensionsMapping() map[string]interface{}

func (*KclOpenAPIType) GetKclTypeName

func (tpe *KclOpenAPIType) GetKclTypeName(omitAny bool, addLink bool, escapeHtml bool) string

GetKclTypeName get the string representation of a KclOpenAPIType

func (*KclOpenAPIType) GetSchemaPkgDir

func (tpe *KclOpenAPIType) GetSchemaPkgDir(base string) string

type KclPackage

type KclPackage struct {
	Name        string `json:"name,omitempty"`        // kcl package name
	Version     string `json:"version,omitempty"`     // kcl package version
	Description string `json:"description,omitempty"` // summary of the kcl package

	SchemaList     []*KclOpenAPIType `json:"schemaList,omitempty"`     // the schema list sorted by name in the KCL package
	SubPackageList []*KclPackage     `json:"subPackageList,omitempty"` // the sub package list sorted by name in the KCL package
	// contains filtered or unexported fields
}

KclPackage contains package information of package metadata(such as name, version, description, ...) and exported models(such as schemas)

type Marshaler

type Marshaler interface {
	MarshalKcl() ([]byte, error)
}

Marshaler is the interface implemented by types that can marshal themselves into valid KCL.

type Mode

type Mode int

Mode is the mode of kcl schema code generation.

const (
	ModeAuto Mode = iota
	ModeGoStruct
	ModeJsonSchema
	ModeTerraformSchema
	ModeJson
	ModeYaml
	ModeToml
	ModeProto
	ModeTextProto
)

type NamedKclType

type NamedKclType struct {
	*gpyrpc.KclType
	Name    string
	RelPath string
}

An additional field 'Name' is added to the original 'KclType'.

'Name' is the name of the kcl type.

'RelPath' is the relative path to the package home path.

type Options

type Options struct {
	GoPackage string
	PbPackage string
}

type SpecInfo

type SpecInfo struct {
	Title       string `json:"title"`
	Version     string `json:"version"`
	Description string `json:"description,omitempty"`
}

SpecInfo defines KCL package info

type SwaggerTypeName

type SwaggerTypeName string

SwaggerTypeName defines possible values of "type" field in Swagger v2.0 spec

const (
	Object  SwaggerTypeName = "object"
	String  SwaggerTypeName = "string"
	Array   SwaggerTypeName = "array"
	Integer SwaggerTypeName = "integer"
	Number  SwaggerTypeName = "number"
	Bool    SwaggerTypeName = "bool"
)

type SwaggerV2Spec

type SwaggerV2Spec struct {
	Definitions map[string]*KclOpenAPIType `json:"definitions"`
	Paths       map[string]interface{}     `json:"paths"`
	Swagger     string                     `json:"swagger"`
	Info        SpecInfo                   `json:"info"`
}

SwaggerV2Spec defines KCL OpenAPI Spec based on Swagger v2.0

func ExportSwaggerV2Spec

func ExportSwaggerV2Spec(path string) (*SwaggerV2Spec, error)

ExportSwaggerV2Spec extracts the swagger v2 representation of a kcl package without the external dependencies in kcl.mod

type TagOptions

type TagOptions struct {
	// contains filtered or unexported fields
}

func GetTagOptions

func GetTagOptions(tag reflect.StructTag) TagOptions

type TextProtoGenerator

type TextProtoGenerator struct {
	// contains filtered or unexported fields
}

func (*TextProtoGenerator) Gen

func (d *TextProtoGenerator) Gen(filename string, src any, schema *kcl.KclType) (*config, error)

Parse parses the given textproto bytes and converts them to KCL configs. Note fields in the textproto that have no corresponding field in schema are ignored.

func (*TextProtoGenerator) GenFromSchemaFile

func (d *TextProtoGenerator) GenFromSchemaFile(filename string, src any, schemaFile string, schemaSrc any, schemaName string) (*config, error)

ParseFromSchemaFile parses the given textproto bytes and converts them to KCL configs with the schema file. Note fields in the textproto that have no corresponding field in schema are ignored.

type TypeFormat

type TypeFormat string

TypeFormat defines possible values of "format" field in Swagger v2.0 spec

const (
	Int64            TypeFormat = "int64"
	Float            TypeFormat = "float"
	NumberMultiplier TypeFormat = "units.NumberMultiplier"
)

type XKclDecorator

type XKclDecorator struct {
	Name      string            `json:"name,omitempty"`
	Arguments []string          `json:"arguments,omitempty"`
	Keywords  map[string]string `json:"keywords,omitempty"`
}

XKclDecorator definition

type XKclDecorators

type XKclDecorators []*XKclDecorator

XKclDecorators defines the `x-kcl-decorators` extension

type XKclModelType

type XKclModelType struct {
	Type   string              `json:"type,omitempty"`   // schema short name
	Import *KclModelImportInfo `json:"import,omitempty"` // import information
}

XKclModelType defines the `x-kcl-type` extension

Jump to

Keyboard shortcuts

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