Documentation ¶
Overview ¶
Package codegen contains data structures and algorithms used by the Goa code generation tool.
In particular package codegen defines the data structure that represents a generated file (see File) which is composed of sections, each corresponding to a Go text template and accompanying data used to render the final code.
The package also includes functions that generate code to transform a given type into another (see GoTransform).
Index ¶
- Constants
- Variables
- func AddImport(section *SectionTemplate, imprts ...*ImportSpec)
- func AddServiceMetaTypeImports(header *SectionTemplate, svc *expr.ServiceExpr)
- func AttributeTags(_, att *expr.AttributeExpr) string
- func AttributeValidationCode(att *expr.AttributeExpr, put expr.UserType, attCtx *AttributeContext, ...) string
- func CamelCase(name string, firstUpper bool, acronym bool) string
- func CommandLine() string
- func Comment(elems ...string) string
- func CreateTempFile(t *testing.T, content string) string
- func FormatTestCode(t *testing.T, code string) string
- func GoNativeTypeName(t expr.DataType) string
- func Goify(str string, firstUpper bool) string
- func GoifyAtt(att *expr.AttributeExpr, name string, upper bool) string
- func Indent(s, prefix string) string
- func IsCompatible(a, b expr.DataType, actx, bctx string) error
- func KebabCase(name string) string
- func MapDepth(m *expr.Map) int
- func RegisterPlugin(name string, cmd string, pre PrepareFunc, p GenerateFunc)
- func RegisterPluginFirst(name string, cmd string, pre PrepareFunc, p GenerateFunc)
- func RegisterPluginLast(name string, cmd string, pre PrepareFunc, p GenerateFunc)
- func RunDSL(t *testing.T, dsl func()) *expr.RootExpr
- func RunPluginsPrepare(cmd, genpkg string, roots []eval.Root) error
- func SectionCode(t *testing.T, section *SectionTemplate) string
- func SectionCodeFromImportsAndMethods(t *testing.T, importSection, methodSection *SectionTemplate) string
- func SectionsCode(t *testing.T, sections []*SectionTemplate) string
- func SnakeCase(name string) string
- func TemplateFuncs() map[string]any
- func UnionValTypeName(unionName string) string
- func ValidationCode(att *expr.AttributeExpr, put expr.UserType, attCtx *AttributeContext, ...) string
- func Walk(a *expr.AttributeExpr, walker func(*expr.AttributeExpr) error) error
- func WalkMappedAttr(ma *expr.MappedAttributeExpr, it MappedAttributeWalker) error
- func WalkType(u expr.UserType, walker func(*expr.AttributeExpr) error) error
- func WrapText(text string, maxChars int) string
- type AttributeContext
- type AttributeScope
- func (*AttributeScope) Field(att *expr.AttributeExpr, name string, firstUpper bool) string
- func (a *AttributeScope) Name(att *expr.AttributeExpr, pkg string, ptr, useDefault bool) string
- func (a *AttributeScope) Ref(att *expr.AttributeExpr, pkg string) string
- func (a *AttributeScope) Scope() *NameScope
- type Attributor
- type File
- type GenerateFunc
- type Hasher
- type ImportSpec
- func GetMetaType(att *expr.AttributeExpr) (typeName string, importS *ImportSpec)
- func GetMetaTypeImports(att *expr.AttributeExpr) []*ImportSpec
- func GoaImport(rel string) *ImportSpec
- func GoaNamedImport(rel, name string) *ImportSpec
- func NewImport(name, path string) *ImportSpec
- func SimpleImport(path string) *ImportSpec
- type InitArgData
- type Location
- type MappedAttributeWalker
- type NameScope
- func (s *NameScope) GoFullTypeName(att *expr.AttributeExpr, pkg string) string
- func (s *NameScope) GoFullTypeRef(att *expr.AttributeExpr, pkg string) string
- func (s *NameScope) GoTypeDef(att *expr.AttributeExpr, ptr, useDefault bool) string
- func (s *NameScope) GoTypeName(att *expr.AttributeExpr) string
- func (s *NameScope) GoTypeNameWithDefaults(att *expr.AttributeExpr) string
- func (s *NameScope) GoTypeRef(att *expr.AttributeExpr) string
- func (s *NameScope) GoTypeRefWithDefaults(att *expr.AttributeExpr) string
- func (*NameScope) GoVar(varName string, dt expr.DataType) string
- func (s *NameScope) HashedUnique(key Hasher, name string, suffix ...string) string
- func (s *NameScope) Name(name string) string
- func (s *NameScope) Unique(name string, suffix ...string) string
- type PrepareFunc
- type Scoper
- type SectionTemplate
- type TransformAttrs
- type TransformFunctionData
- func AppendHelpers(oldH, newH []*TransformFunctionData) []*TransformFunctionData
- func GoTransform(source, target *expr.AttributeExpr, sourceVar, targetVar string, ...) (string, []*TransformFunctionData, error)
- func InitStructFields(args []*InitArgData, targetVar, sourcePkg, targetPkg string) (string, []*TransformFunctionData, error)
Constants ¶
const Gendir = "gen"
Gendir is the name of the subdirectory of the output directory that contains the generated files. This directory is wiped and re-written each time goa is run.
Variables ¶
var DesignVersion = goa.Major
DesignVersion contains the major component of the version of Goa used to author the design - either 2 or 3. This value is initialized when the generated tool is invoked by retrieving the information passed on the command line by the goa tool.
Functions ¶
func AddImport ¶
func AddImport(section *SectionTemplate, imprts ...*ImportSpec)
AddImport adds imports to a section template that was generated with Header.
func AddServiceMetaTypeImports ¶ added in v3.0.1
func AddServiceMetaTypeImports(header *SectionTemplate, svc *expr.ServiceExpr)
AddServiceMetaTypeImports adds meta type imports for each method of the service expr
func AttributeTags ¶
func AttributeTags(_, att *expr.AttributeExpr) string
AttributeTags computes the struct field tags from its metadata if any.
func AttributeValidationCode ¶ added in v3.12.0
func AttributeValidationCode(att *expr.AttributeExpr, put expr.UserType, attCtx *AttributeContext, req, alias bool, target, attName string) string
AttributeValidationCode produces Go code that runs the validations defined in the given attribute against the value held by the variable named target.
See ValidationCode for a description of the arguments.
func CamelCase ¶
CamelCase produces the CamelCase version of the given string. It removes any non letter and non digit character.
If firstUpper is true the first letter of the string is capitalized else the first letter is in lowercase.
If acronym is true and a part of the string is a common acronym then it keeps the part capitalized (firstUpper = true) (e.g. APIVersion) or lowercase (firstUpper = false) (e.g. apiVersion).
func CommandLine ¶
func CommandLine() string
CommandLine return the command used to run this process.
func Comment ¶
Comment produces line comments by concatenating the given strings and producing 80 characters long lines starting with "//".
func CreateTempFile ¶
CreateTempFile creates a temporary file and writes the given content. It is used only for testing.
func FormatTestCode ¶
FormatTestCode formats the given Go code. The code must correspond to the content of a valid Go source file (i.e. start with "package")
func GoNativeTypeName ¶
GoNativeTypeName returns the Go built-in type corresponding to the given primitive type. GoNativeType panics if t is not a primitive type.
func Goify ¶
Goify makes a valid Go identifier out of any string. It does that by removing any non letter and non digit character and by making sure the first character is a letter or "_". Goify produces a "CamelCase" version of the string, if firstUpper is true the first character of the identifier is uppercase otherwise it's lowercase.
func GoifyAtt ¶
func GoifyAtt(att *expr.AttributeExpr, name string, upper bool) string
GoifyAtt honors any struct:field:name meta set on the attribute and calls Goify with the tag value if present or the given name otherwise.
func Indent ¶
Indent inserts prefix at the beginning of each non-empty line of s. The end-of-line marker is NL.
func IsCompatible ¶
IsCompatible returns an error if a and b are not both objects, both arrays, both maps, both unions or one union and one object. actx and bctx are used to build the error message if any.
func RegisterPlugin ¶
func RegisterPlugin(name string, cmd string, pre PrepareFunc, p GenerateFunc)
RegisterPlugin adds the plugin to the list of plugins to be invoked with the given command.
func RegisterPluginFirst ¶
func RegisterPluginFirst(name string, cmd string, pre PrepareFunc, p GenerateFunc)
RegisterPluginFirst adds the plugin to the beginning of the list of plugins to be invoked with the given command. If more than one plugins are registered using this, the plugins will be sorted alphabetically by their names. If two plugins have same names, then they are sorted by registration order.
func RegisterPluginLast ¶
func RegisterPluginLast(name string, cmd string, pre PrepareFunc, p GenerateFunc)
RegisterPluginLast adds the plugin to the end of the list of plugins to be invoked with the given command. If more than one plugins are registered using this, the plugins will be sorted alphabetically by their names. If two plugins have same names, then they are sorted by registration order.
func RunPluginsPrepare ¶
RunPluginsPrepare executes the plugins prepare functions in the order they were registered.
func SectionCode ¶
func SectionCode(t *testing.T, section *SectionTemplate) string
SectionCode generates and formats the code for the given section.
func SectionCodeFromImportsAndMethods ¶
func SectionCodeFromImportsAndMethods(t *testing.T, importSection, methodSection *SectionTemplate) string
SectionCodeFromImportsAndMethods generates and formats the code for given import and method definition sections.
func SectionsCode ¶
func SectionsCode(t *testing.T, sections []*SectionTemplate) string
SectionsCode generates and formats the code for the given sections.
func SnakeCase ¶
SnakeCase produces the snake_case version of the given CamelCase string. News => news OldNews => old_news CNNNews => cnn_news
func TemplateFuncs ¶
TemplateFuncs lists common template helper functions.
func UnionValTypeName ¶ added in v3.7.0
UnionValTypeName returns the Go type name of the interface and method used to type the union.
func ValidationCode ¶
func ValidationCode(att *expr.AttributeExpr, put expr.UserType, attCtx *AttributeContext, req, alias, view bool, target string) string
ValidationCode produces Go code that runs the validations defined in the given attribute and its children recursively against the value held by the variable named target.
put is the parent UserType if any. It is used to compute proto oneof type names.
attCtx is the attribute context used to generate attribute name and reference in the validation code.
req indicates whether the attribute is required (true) or optional (false)
alias indicates whether the attribute is an alias user type attribute.
view indicates whether the attribute is a view type attribute. This only matters for union types: generated Goa view union types have a different layout than proto generated union types.
target is the variable name against which the validation code is generated
context is used to produce helpful messages in case of error.
func Walk ¶
func Walk(a *expr.AttributeExpr, walker func(*expr.AttributeExpr) error) error
Walk traverses the data structure recursively and calls the given function once on each attribute starting with a.
func WalkMappedAttr ¶
func WalkMappedAttr(ma *expr.MappedAttributeExpr, it MappedAttributeWalker) error
WalkMappedAttr iterates over the mapped attributes. It calls the given function giving each attribute as it iterates. WalkMappedAttr stops if there is no more attribute to iterate over or if the iterator function returns an error in which case it returns the error.
Types ¶
type AttributeContext ¶
type AttributeContext struct { // Pointer if true indicates that the attribute uses pointers to hold // primitive types even if they are required or has a default value. // It ignores UseDefault and IgnoreRequired properties. Pointer bool // IgnoreRequired if true indicates that the transport object // (proto) uses non-pointers to hold required attributes and // therefore do not need to be validated. IgnoreRequired bool // UseDefault if true indicates that the attribute uses non-pointers for // primitive types if they have default value. If false, the attribute with // primitive types are non-pointers if they are required, otherwise they // are pointers. UseDefault bool // Scope is the attribute scope. Scope Attributor // DefaultPkg is the default package name where the attribute // type is found. it can be overridden via struct:pkg:path meta. DefaultPkg string // IsInterface is true if the attribute is an interface (union type). // In this case assigning child attributes requires a type assertion. IsInterface bool }
AttributeContext contains properties which impacts the code generating behavior of an attribute.
func NewAttributeContext ¶
func NewAttributeContext(pointer, reqIgnore, useDefault bool, pkg string, scope *NameScope) *AttributeContext
NewAttributeContext initializes an attribute context.
func (*AttributeContext) Dup ¶
func (a *AttributeContext) Dup() *AttributeContext
Dup creates a shallow copy of the AttributeContext.
func (*AttributeContext) IsPrimitivePointer ¶
func (a *AttributeContext) IsPrimitivePointer(name string, att *expr.AttributeExpr) bool
IsPrimitivePointer returns true if the attribute with the given name is a primitive pointer in the given parent attribute.
func (*AttributeContext) Pkg ¶
func (a *AttributeContext) Pkg(att *expr.AttributeExpr) string
Pkg returns the package name of the given type.
type AttributeScope ¶
type AttributeScope struct {
// contains filtered or unexported fields
}
AttributeScope contains the scope of an attribute. It implements the Attributor interface.
func NewAttributeScope ¶ added in v3.1.0
func NewAttributeScope(scope *NameScope) *AttributeScope
NewAttributeScope initializes an attribute scope.
func (*AttributeScope) Field ¶
func (*AttributeScope) Field(att *expr.AttributeExpr, name string, firstUpper bool) string
Field returns a valid Go struct field name.
func (*AttributeScope) Name ¶
func (a *AttributeScope) Name(att *expr.AttributeExpr, pkg string, ptr, useDefault bool) string
Name returns the type name for the given attribute.
func (*AttributeScope) Ref ¶
func (a *AttributeScope) Ref(att *expr.AttributeExpr, pkg string) string
Ref returns the type name for the given attribute.
func (*AttributeScope) Scope ¶
func (a *AttributeScope) Scope() *NameScope
Scope returns the name scope.
type Attributor ¶
type Attributor interface { Scoper // Name generates a valid name for the given attribute type. ptr and // useDefault are used to generate inline struct type definitions. Name(att *expr.AttributeExpr, pkg string, ptr, useDefault bool) string // Ref generates a valid reference to the given attribute type. Ref(att *expr.AttributeExpr, pkg string) string // Field generates a valid data structure field identifier for the given // attribute and field name. If firstUpper is true then the field name // first letter is capitalized. Field(att *expr.AttributeExpr, name string, firstUpper bool) string }
Attributor defines the behavior of an attribute expression during code generation.
type File ¶
type File struct { // SectionTemplates is the list of file section templates in // order of rendering. SectionTemplates []*SectionTemplate // Path returns the file path relative to the output directory. Path string // SkipExist indicates whether the file should be skipped if one // already exists at the given path. SkipExist bool // FinalizeFunc is called after the file has been generated. It // is given the absolute path to the file as argument. FinalizeFunc func(string) error }
A File contains the logic to generate a complete file.
func RunPlugins ¶
RunPlugins executes the plugins registered with the given command in the order they were registered.
func (*File) Render ¶
Render executes the file section templates and writes the resulting bytes to an output file. The path of the output file is computed by appending the file path to dir. If a file already exists with the computed path then Render happens the smallest integer value greater than 1 to make it unique. Renders returns the computed path.
func (*File) Section ¶
func (f *File) Section(name string) []*SectionTemplate
Section returns the section templates with the given name or nil if not found.
type GenerateFunc ¶
GenerateFunc makes it possible to modify the files generated by the goa code generators and other plugins. A GenerateFunc accepts the Go import path of the "gen" package, the design roots as well as the currently generated files (produced initially by the goa generators and potentially modified by previously run plugins) and returns a new set of files.
type Hasher ¶
type Hasher interface { // Hash computes a unique instance hash suitable for indexing // in a map. Hash() string }
Hasher is the interface implemented by the objects that must be scoped.
type ImportSpec ¶
type ImportSpec struct { // Name of imported package if needed. Name string // Go import path of package. Path string }
ImportSpec defines a generated import statement.
func GetMetaType ¶ added in v3.0.9
func GetMetaType(att *expr.AttributeExpr) (typeName string, importS *ImportSpec)
GetMetaType retrieves the type and package defined by the struct:field:type metadata if any.
func GetMetaTypeImports ¶ added in v3.0.1
func GetMetaTypeImports(att *expr.AttributeExpr) []*ImportSpec
GetMetaTypeImports parses the attribute for all user defined imports
func GoaImport ¶ added in v3.0.1
func GoaImport(rel string) *ImportSpec
GoaImport creates an import for a Goa package.
func GoaNamedImport ¶ added in v3.0.1
func GoaNamedImport(rel, name string) *ImportSpec
GoaNamedImport creates an import for a Goa package with the given name.
func SimpleImport ¶
func SimpleImport(path string) *ImportSpec
SimpleImport creates an import with no explicit path component.
func (*ImportSpec) Code ¶
func (s *ImportSpec) Code() string
Code returns the Go import statement for the ImportSpec.
type InitArgData ¶ added in v3.1.0
type InitArgData struct { // Name is the argument name. Name string // Pointer if true indicates that the argument is a pointer. Pointer bool // Type is the argument type. Type expr.DataType // FieldName is the name of the field in the struct initialized by the // argument. FieldName string // FieldPointer if true indicates that the field in the struct is a // pointer. FieldPointer bool // FieldType is the type of the field in the struct. FieldType expr.DataType }
InitArgData contains the data needed to render code to initialize struct fields with the given arguments.
type Location ¶ added in v3.6.0
type Location struct { // FilePath is the path to the file. FilePath string // RelImportPath is the Go import path starting after the gen // folder. RelImportPath string }
Location defines a file location and import details.
func UserTypeLocation ¶ added in v3.6.0
UserTypeLocation returns the location of the user type if set via the struct:pkg:path metadata, nil otherwise..
func (*Location) PackageName ¶ added in v3.6.0
PackageName returns the package name of the given location.
type MappedAttributeWalker ¶
type MappedAttributeWalker func(name, elem string, required bool, a *expr.AttributeExpr) error
MappedAttributeWalker is the type of functions given to WalkMappedAttr. name is the name of the attribute, elem the name of the corresponding transport element (e.g. HTTP header). required is true if the attribute is required.
type NameScope ¶
type NameScope struct {
// contains filtered or unexported fields
}
NameScope defines a naming scope.
func (*NameScope) GoFullTypeName ¶
func (s *NameScope) GoFullTypeName(att *expr.AttributeExpr, pkg string) string
GoFullTypeName returns the Go type name of the given data type qualified with the given package name if applicable and if not the empty string.
func (*NameScope) GoFullTypeRef ¶
func (s *NameScope) GoFullTypeRef(att *expr.AttributeExpr, pkg string) string
GoFullTypeRef returns the Go code that refers to the Go type which matches the given attribute type defined in the given package if a user type.
func (*NameScope) GoTypeDef ¶
func (s *NameScope) GoTypeDef(att *expr.AttributeExpr, ptr, useDefault bool) string
GoTypeDef returns the Go code that defines a Go type which matches the data structure definition (the part that comes after `type foo`).
ptr if true indicates that the attribute must be stored in a pointer (except array and map types which are always non-pointers)
useDefault if true indicates that the attribute must not be a pointer if it has a default value.
func (*NameScope) GoTypeName ¶
func (s *NameScope) GoTypeName(att *expr.AttributeExpr) string
GoTypeName returns the Go type name of the given attribute type.
func (*NameScope) GoTypeNameWithDefaults ¶ added in v3.2.6
func (s *NameScope) GoTypeNameWithDefaults(att *expr.AttributeExpr) string
GoTypeNameWithDefaults returns the Go type name of the given attribute type. The result of this function differs from GoTypeName when the attribute type is an object (note: not a user type) and the name is thus an inline struct definition. In this case accounting for default values may cause child attributes to use non-pointer fields.
func (*NameScope) GoTypeRef ¶
func (s *NameScope) GoTypeRef(att *expr.AttributeExpr) string
GoTypeRef returns the Go code that refers to the Go type which matches the given attribute type.
func (*NameScope) GoTypeRefWithDefaults ¶ added in v3.2.6
func (s *NameScope) GoTypeRefWithDefaults(att *expr.AttributeExpr) string
GoTypeRefWithDefaults returns the Go code that refers to the Go type which matches the given attribute type. The result of this function differs from GoTypeRef when the attribute type is an object (note: not a user type) and the reference is thus an inline struct definition. In this case accounting for default values may cause child attributes to use non-pointer fields.
func (*NameScope) GoVar ¶
GoVar returns the Go code that returns the address of a variable of the Go type which matches the given attribute type.
func (*NameScope) HashedUnique ¶
HashedUnique builds the unique name for key using name and - if not unique - appending suffix and - if still not unique - a counter value. It returns the same value when called multiple times for a key returning the same hash.
func (*NameScope) Name ¶
Name returns a unique name for the given name by adding a counter value to the name until unique. It returns the same value when called multiple times for the same given name.
type PrepareFunc ¶
PrepareFunc makes it possible to modify the design roots before the files being generated by the goa code generators or other plugins.
type Scoper ¶
type Scoper interface {
Scope() *NameScope
}
Scoper provides a scope for generating unique names.
type SectionTemplate ¶
type SectionTemplate struct { // Name is the name reported when parsing the source fails. Name string // Source is used to create the text/template.Template that // renders the section text. Source string // FuncMap lists the functions used to render the templates. FuncMap map[string]any // Data used as input of template. Data any }
A SectionTemplate is a template and accompanying render data. The template format is described in the (stdlib) text/template package.
func Header ¶
func Header(title, pack string, imports []*ImportSpec) *SectionTemplate
Header returns a Go source file header section template.
type TransformAttrs ¶
type TransformAttrs struct {
// SourceCtx and TargetCtx are the source and target attribute context.
SourceCtx, TargetCtx *AttributeContext
// Prefix is the transform function helper prefix.
Prefix string
}
TransformAttrs are the attributes that help in the transformation.
type TransformFunctionData ¶
type TransformFunctionData struct { Name string ParamTypeRef string ResultTypeRef string Code string }
TransformFunctionData describes a helper function used to transform user types. These are necessary to prevent potential infinite recursion when a type attribute is defined recursively. For example:
var Recursive = Type("Recursive", func() { Attribute("r", "Recursive") }
Transforming this type requires generating an intermediary function:
func recursiveToRecursive(r *Recursive) *service.Recursive { var t service.Recursive if r.R != nil { t.R = recursiveToRecursive(r.R) } }
func AppendHelpers ¶
func AppendHelpers(oldH, newH []*TransformFunctionData) []*TransformFunctionData
AppendHelpers takes care of only appending helper functions from newH that are not already in oldH.
func GoTransform ¶
func GoTransform(source, target *expr.AttributeExpr, sourceVar, targetVar string, sourceCtx, targetCtx *AttributeContext, prefix string, newVar bool) (string, []*TransformFunctionData, error)
GoTransform produces Go code that initializes the data structure defined by target from an instance of the data structure described by source. The data structures can be objects, arrays or maps. The algorithm matches object fields by name and ignores object fields in target that don't have a match in source. The matching and generated code leverage mapped attributes so that attribute names may use the "name:elem" syntax to define the name of the design attribute and the name of the corresponding generated Go struct field. The object field may also differ in that they may be pointers in one case and not the other. The function returns an error if target is not compatible with source (different type, fields of different type etc).
As a special case GoTransform can map union types from and to object types with two attributes, one called "Value" which stores the value and one called "Type" which is of type string and contains the value type name (union types are otherwise implemented as a struct containing a single field: the current value - however having the kind explicitly stored is required to serialize to JSON for example).
source and target are the attributes used in the transformation
sourceVar and targetVar are the variable names used in the transformation
sourceCtx and targetCtx are the attribute contexts for the source and target attributes
prefix is the transformation helper function prefix
newVar if true initializes a target variable with the generated Go code using `:=` operator. If false, it assigns Go code to the target variable using `=`.
func InitStructFields ¶ added in v3.1.0
func InitStructFields(args []*InitArgData, targetVar, sourcePkg, targetPkg string) (string, []*TransformFunctionData, error)
InitStructFields produces Go code to initialize a struct and its fields from the given init arguments.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package cli contains helpers used by transport-specific command-line client generators for parsing the command-line flags to identify the service and the method to make a request along with the request payload to be sent.
|
Package cli contains helpers used by transport-specific command-line client generators for parsing the command-line flags to identify the service and the method to make a request along with the request payload to be sent. |
Package codegentest provides utilities to assist writing unit test for codegen packages.
|
Package codegentest provides utilities to assist writing unit test for codegen packages. |
Package example contains code generation algorithms to produce an example server and client implementation for the transports defined in the design.
|
Package example contains code generation algorithms to produce an example server and client implementation for the transports defined in the design. |
Package generator contains the code generation algorithms for a service server, client, and OpenAPI specification.
|
Package generator contains the code generation algorithms for a service server, client, and OpenAPI specification. |
Package service contains the code generation algorithms to produce code for the service and views packages and dummy implementation for the services defined in the design.
|
Package service contains the code generation algorithms to produce code for the service and views packages and dummy implementation for the services defined in the design. |