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 include functions that can generate code that transforms a given type into another (see GoTransform).
Index ¶
- Constants
- func AddImport(section *SectionTemplate, imprts ...*ImportSpec)
- func AddServiceMetaTypeImports(header *SectionTemplate, svc *expr.ServiceExpr)
- func AttributeTags(parent, att *expr.AttributeExpr) 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 Diff(t *testing.T, s1, s2 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 RecursiveValidationCode(att *expr.AttributeExpr, attCtx *AttributeContext, req bool, target string) string
- 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 RunDSLWithFunc(t *testing.T, dsl func(), fn 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 *SectionTemplate, methodSection *SectionTemplate) string
- func SectionsCode(t *testing.T, sections []*SectionTemplate) string
- func SnakeCase(name string) string
- func TemplateFuncs() map[string]interface{}
- func ValidationCode(att *expr.AttributeExpr, attCtx *AttributeContext, req bool, ...) 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
- type Attributor
- type File
- type GenerateFunc
- type Hasher
- type ImportSpec
- 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) GoTypeRef(att *expr.AttributeExpr) string
- func (s *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
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 ¶
This section is empty.
Functions ¶
func AddImport ¶
func AddImport(section *SectionTemplate, imprts ...*ImportSpec)
AddImport adds imports to a section template that was generated with Header.
func AddServiceMetaTypeImports ¶
func AddServiceMetaTypeImports(header *SectionTemplate, svc *expr.ServiceExpr)
AddServiceMetaTypeImports adds meta type imports for each method of the service expr
func AttributeTags ¶
func AttributeTags(parent, att *expr.AttributeExpr) string
AttributeTags computes the struct field tags from its metadata if any.
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 Diff ¶
Diff returns a diff between s1 and s2. It uses the diff tool if installed otherwise degrades to using the dmp package.
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 or both the same primitive type. actx and bctx are used to build the error message if any.
func RecursiveValidationCode ¶
func RecursiveValidationCode(att *expr.AttributeExpr, attCtx *AttributeContext, req bool, target string) string
RecursiveValidationCode 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. See ValidationCode for a description of the arguments and their effects.
attCtx is the Attributor for the given attribute which is used to generate attribute name and reference in the validation code.
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 RunDSLWithFunc ¶
RunDSLWithFunc returns the DSL root resulting from running the given DSL. It executes a function to add any top-level types to the design Root before running the DSL.
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 *SectionTemplate, 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 TemplateFuncs ¶
func TemplateFuncs() map[string]interface{}
TemplateFuncs lists common template helper functions.
func ValidationCode ¶
func ValidationCode(att *expr.AttributeExpr, attCtx *AttributeContext, req bool, target, context string) string
ValidationCode produces Go code that runs the validations defined in the given attribute definition if any against the content of the variable named target. The generated code assumes that there is a pre-existing "err" variable of type error. It initializes that variable in case a validation fails.
attCtx is the attribute context
req indicates whether the attribute is required (true) or optional (false)
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 attribute uses non-pointers // to hold optional attributes (i.e. attributes that are not required). 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 // Pkg is the package name where the attribute type is found. Pkg string // Scope is the attribute scope. Scope Attributor }
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) IsRequired ¶
func (a *AttributeContext) IsRequired(name string, att *expr.AttributeExpr) bool
IsRequired returns true if the attribute with given name is a required attribute in the parent. If IgnoreRequired is set to true, IsRequired always returns false.
type AttributeScope ¶
type AttributeScope struct {
// contains filtered or unexported fields
}
AttributeScope contains the scope of an attribute. It implements the Attributor interface.
func (*AttributeScope) Field ¶
func (a *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) 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. Name(att *expr.AttributeExpr, pkg string) 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 the field name's 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 GetMetaTypeImports ¶
func GetMetaTypeImports(att *expr.AttributeExpr) []*ImportSpec
GetMetaTypeImports parses the attribute for all user defined imports
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 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) 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) 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]interface{} // Data used as input of template. Data interface{} }
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) (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 function returns an error if target is not compatible with source (different type, fields of different type etc).
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
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 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. |