generator

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2024 License: Apache-2.0 Imports: 23 Imported by: 14

Documentation

Overview

Package generator .

Index

Constants

View Source
const (
	KitexGenPath = "kitex_gen"
	DefaultCodec = "thrift"

	BuildFileName       = "build.sh"
	BootstrapFileName   = "bootstrap.sh"
	ToolVersionFileName = "kitex_info.yaml"
	HandlerFileName     = "handler.go"
	MainFileName        = "main.go"
	ClientFileName      = "client.go"
	ServerFileName      = "server.go"
	InvokerFileName     = "invoker.go"
	ServiceFileName     = "*service.go"
	ExtensionFilename   = "extensions.yaml"

	DefaultThriftPluginTimeLimit = time.Minute

	// built in tpls
	MultipleServicesTpl = "multiple_services"
)

Constants .

Variables

View Source
var DefaultDelimiters = [2]string{"{{", "}}"}

Functions

func AddGlobalDependency

func AddGlobalDependency(ref, path string) bool

AddGlobalDependency adds dependency for all generators

func AddGlobalMiddleware

func AddGlobalMiddleware(mw Middleware)

AddGlobalMiddleware adds middleware for all generators

func AddTemplateFunc added in v0.9.0

func AddTemplateFunc(key string, f interface{})

func BackQuoted added in v0.7.2

func BackQuoted(s string) string

func FilterImports added in v0.5.0

func FilterImports(Imports map[string]map[string]bool, ms []*MethodInfo) map[string]map[string]bool

func HasFeature

func HasFeature(list []feature, key string) bool

HasFeature check whether a feature in the list

func ImportPathTo

func ImportPathTo(pkg string) string

ImportPathTo returns an import path to the specified package under kitex.

func NewCustomGenerator added in v0.5.0

func NewCustomGenerator(pkg *PackageInfo, basePath string) *customGenerator

func RegisterFeature

func RegisterFeature(key string)

RegisterFeature register a feature

func SetKitexImportPath

func SetKitexImportPath(path string)

SetKitexImportPath sets the import path of kitex. Must be called before generating code.

func SetTemplateExtension

func SetTemplateExtension(name, text string)

SetTemplateExtension .

func ToStreamxRef added in v0.12.0

func ToStreamxRef(protocol transport.Protocol) string

Types

type APIExtension added in v0.4.3

type APIExtension struct {
	// ImportPaths contains a list of import path that the file should add to the import list.
	// The paths must be registered with the TemplateExtension's Dependencies fields.
	ImportPaths []string `json:"import_paths,omitempty" yaml:"import_paths,omitempty"`

	// Code snippets to be inserted in the NewX function before assembling options.
	// It must be a template definition with a name identical to the one kitex uses.
	ExtendOption string `json:"extend_option,omitempty" yaml:"extend_option,omitempty"`

	// Code snippets to be appended to the file.
	// It must be a template definition with a name identical to the one kitex uses.
	ExtendFile string `json:"extend_file,omitempty" yaml:"extend_file,omitempty"`
}

APIExtension contains segments to extend an API template.

func (*APIExtension) Merge added in v0.5.0

func (a *APIExtension) Merge(other *APIExtension)

type Config

type Config struct {
	Verbose               bool
	GenerateMain          bool // whether stuff in the main package should be generated
	GenerateInvoker       bool // generate main.go with invoker when main package generate
	Version               string
	NoFastAPI             bool
	ModuleName            string
	ServiceName           string
	Use                   string
	IDLType               string
	Includes              util.StringSlice
	ThriftOptions         util.StringSlice
	ProtobufOptions       util.StringSlice
	Hessian2Options       util.StringSlice
	IDL                   string // the IDL file passed on the command line
	OutputPath            string // the output path for main pkg and kitex_gen
	PackagePrefix         string
	CombineService        bool // combine services to one service
	CopyIDL               bool
	ThriftPlugins         util.StringSlice
	ProtobufPlugins       util.StringSlice
	Features              []feature
	FrugalPretouch        bool
	ThriftPluginTimeLimit time.Duration
	CompilerPath          string // specify the path of thriftgo or protoc

	ExtensionFile string

	Record    bool
	RecordCmd []string

	TemplateDir string

	GenPath string

	DeepCopyAPI           bool
	Protocol              string
	HandlerReturnKeepResp bool

	NoDependencyCheck bool
	Rapid             bool
	LocalThriftgo     bool

	GenFrugal    bool
	FrugalStruct util.StringSlice
	NoRecurse    bool

	BuiltinTpl util.StringSlice // specify the built-in template to use
	StreamX    bool
	// contains filtered or unexported fields
}

Config .

func (*Config) AddFeature

func (c *Config) AddFeature(key string) bool

AddFeature add registered feature to config

func (*Config) ApplyExtension added in v0.4.3

func (c *Config) ApplyExtension() error

ApplyExtension applies template extension.

func (*Config) IsUsingMultipleServicesTpl added in v0.11.0

func (c *Config) IsUsingMultipleServicesTpl() bool

func (*Config) Pack

func (c *Config) Pack() (res []string)

Pack packs the Config into a slice of "key=val" strings.

func (*Config) Unpack

func (c *Config) Unpack(args []string) error

Unpack restores the Config from a slice of "key=val" strings.

type File

type File struct {
	Name    string
	Content string
}

File .

type Generator

type Generator interface {
	GenerateService(pkg *PackageInfo) ([]*File, error)
	GenerateMainPackage(pkg *PackageInfo) ([]*File, error)
	GenerateCustomPackage(pkg *PackageInfo) ([]*File, error)
}

Generator generates the codes of main package and scripts for building a server based on kitex.

func NewGenerator

func NewGenerator(config *Config, middlewares []Middleware) Generator

NewGenerator .

type HandleFunc

type HandleFunc func(*Task, *PackageInfo) (*File, error)

HandleFunc used generator

type MethodInfo

type MethodInfo struct {
	PkgInfo
	ServiceName            string
	Name                   string
	RawName                string
	Oneway                 bool
	Void                   bool
	Args                   []*Parameter
	ArgsLength             int
	Resp                   *Parameter
	Exceptions             []*Parameter
	ArgStructName          string
	ResStructName          string
	IsResponseNeedRedirect bool // int -> int*
	GenArgResultStruct     bool
	ClientStreaming        bool
	ServerStreaming        bool
	Streaming              *streaming.Streaming
	StreamX                bool
}

MethodInfo .

type Middleware

type Middleware func(HandleFunc) HandleFunc

Middleware used generator

type PackageInfo

type PackageInfo struct {
	Namespace    string            // a dot-separated string for generating service package under kitex_gen
	Dependencies map[string]string // package name => import path, used for searching imports
	*ServiceInfo                   // the target service
	Services     []*ServiceInfo    // all services defined in a IDL for multiple services scenario

	// the following fields will be filled and used by the generator
	Codec            string
	NoFastAPI        bool
	Version          string
	RealServiceName  string
	Imports          map[string]map[string]bool // import path => alias
	ExternalKitexGen string
	Features         []feature
	FrugalPretouch   bool
	Module           string
	Protocol         transport.Protocol
	IDLName          string
	ServerPkg        string
}

PackageInfo contains information to generate a package for a service.

func (*PackageInfo) AddImport

func (p *PackageInfo) AddImport(pkg, path string)

AddImport .

func (*PackageInfo) AddImports

func (p *PackageInfo) AddImports(pkgs ...string)

AddImports .

func (*PackageInfo) UpdateImportPath added in v0.11.0

func (p *PackageInfo) UpdateImportPath(pkg, newPath string)

UpdateImportPath changed the mapping between alias -> import path For instance:

Original import: alias "original_path"
Invocation:      UpdateImport("alias", "new_path")
New import:      alias "new_path"

if pkg == newPath, then alias would be removed in import sentence:

Original import: context "path/to/custom/context"
Invocation:      UpdateImport("context", "context")
New import:      context

type Parameter

type Parameter struct {
	Deps    []PkgInfo
	Name    string
	RawName string
	Type    string // *PkgA.StructB
}

Parameter .

type PkgInfo

type PkgInfo struct {
	PkgName    string
	PkgRefName string
	ImportPath string
}

PkgInfo .

type ServiceInfo

type ServiceInfo struct {
	PkgInfo
	ServiceName           string
	RawServiceName        string
	ServiceTypeName       func() string
	Base                  *ServiceInfo
	Methods               []*MethodInfo
	CombineServices       []*ServiceInfo
	HasStreaming          bool
	ServiceFilePath       string
	Protocol              string
	HandlerReturnKeepResp bool
	UseThriftReflection   bool
	// for multiple services scenario, the reference name for the service
	RefName string
	// identify whether this service would generate a corresponding handler.
	GenerateHandler bool
	// whether to generate StreamX interface code
	StreamX bool
}

ServiceInfo .

func (*ServiceInfo) AllMethods

func (s *ServiceInfo) AllMethods() (ms []*MethodInfo)

AllMethods returns all methods that the service have.

func (*ServiceInfo) FixHasStreamingForExtendedService added in v0.9.0

func (s *ServiceInfo) FixHasStreamingForExtendedService()

FixHasStreamingForExtendedService updates the HasStreaming field for extended services.

func (*ServiceInfo) HasStreamingRecursive added in v0.9.0

func (s *ServiceInfo) HasStreamingRecursive() bool

HasStreamingRecursive recursively check if the service has streaming method

type Task

type Task struct {
	Name string
	Path string
	Text string
	*template.Template
	Ext *APIExtension
}

Task .

func (*Task) Build

func (t *Task) Build() error

Build .

func (*Task) Render

func (t *Task) Render(data interface{}) (*File, error)

Render .

func (*Task) RenderString added in v0.5.0

func (t *Task) RenderString(data interface{}) (string, error)

type Template added in v0.5.0

type Template struct {
	// The generated path and its filename. For example: biz/test.go
	// will generate test.go in biz directory.
	Path string `yaml:"path,omitempty"`
	// Render template content, currently only supports go template syntax
	Body string `yaml:"body,omitempty"`
	// define update behavior
	UpdateBehavior *Update `yaml:"update_behavior,omitempty"`
	// If set this field, kitex will generate file by cycle. For example:
	// test_a/test_b/{{ .Name}}_test.go
	LoopMethod bool `yaml:"loop_method,omitempty"`
	// If both set this field and combine-service, kitex will generate service by cycle.
	LoopService bool `yaml:"loop_service,omitempty"`
}

type TemplateExtension added in v0.4.3

type TemplateExtension struct {
	// FeatureNames registers some names to the scope for the code generating phrase, where templates can use the `HasFeature` function to query.
	FeatureNames []string `json:"feature_names,omitempty" yaml:"feature_names,omitempty"`

	// EnableFeatures marks on which features that `HasFeature` queries should return true.
	EnableFeatures []string `json:"enable_features,omitempty" yaml:"enable_features,omitempty"`

	// Dependencies is a mapping from import path to package names/aliases.
	Dependencies map[string]string `json:"dependencies,omitempty" yaml:"dependencies,omitempty"`

	// Extension for client.go .
	ExtendClient *APIExtension `json:"extend_client,omitempty" yaml:"extend_client,omitempty"`

	// Extension for server.go .
	ExtendServer *APIExtension `json:"extend_server,omitempty" yaml:"extend_server,omitempty"`

	// Extension for invoker.go .
	ExtendInvoker *APIExtension `json:"extend_invoker,omitempty" yaml:"extend_invoker,omitempty"`
}

TemplateExtension extends templates that generates files in *service packages.

func (*TemplateExtension) FromJSONFile added in v0.4.3

func (p *TemplateExtension) FromJSONFile(filename string) error

FromJSONFile unmarshals a TemplateExtension with JSON format from the given file.

func (*TemplateExtension) FromYAMLFile added in v0.5.0

func (p *TemplateExtension) FromYAMLFile(filename string) error

FromYAMLFile unmarshals a TemplateExtension with YAML format from the given file.

func (*TemplateExtension) Merge added in v0.5.0

func (p *TemplateExtension) Merge(other *TemplateExtension)

func (*TemplateExtension) ToJSONFile added in v0.4.3

func (p *TemplateExtension) ToJSONFile(filename string) error

ToJSONFile marshals a TemplateExtension to the given file in JSON format.

func (*TemplateExtension) ToYAMLFile added in v0.5.0

func (p *TemplateExtension) ToYAMLFile(filename string) error

type Update added in v0.5.0

type Update struct {
	// update type: skip / cover / append. Default is skip.
	// If `LoopMethod` is true, only Type field is effect and no append behavior.
	Type string `yaml:"type,omitempty"`
	// Match key in append type. If the rendered key exists in the file, the method will be skipped.
	Key string `yaml:"key,omitempty"`
	// Append template. Use it to render append content.
	AppendTpl string `yaml:"append_tpl,omitempty"`
	// Append import template. Use it to render import content to append.
	ImportTpl []string `yaml:"import_tpl,omitempty"`
}

Jump to

Keyboard shortcuts

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