goa: goa.design/goa/codegen Index | Files | Directories

package codegen

import "goa.design/goa/codegen"

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

Package Files

doc.go file.go funcs.go go_transform.go goify.go header.go import.go plugin.go scope.go testing.go transformer.go types.go validation.go walk.go

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.

func AddImport Uses

func AddImport(section *SectionTemplate, imprts ...*ImportSpec)

AddImport adds imports to a section template that was generated with Header.

func AddServiceMetaTypeImports Uses

func AddServiceMetaTypeImports(header *SectionTemplate, svc *expr.ServiceExpr)

AddServiceMetaTypeImports adds meta type imports for each method of the service expr

func AttributeTags Uses

func AttributeTags(parent, att *expr.AttributeExpr) string

AttributeTags computes the struct field tags from its metadata if any.

func CamelCase Uses

func CamelCase(name string, firstUpper bool, acronym bool) string

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 Uses

func CommandLine() string

CommandLine return the command used to run this process.

func Comment Uses

func Comment(elems ...string) string

Comment produces line comments by concatenating the given strings and producing 80 characters long lines starting with "//".

func CreateTempFile Uses

func CreateTempFile(t *testing.T, content string) string

CreateTempFile creates a temporary file and writes the given content. It is used only for testing.

func Diff Uses

func Diff(t *testing.T, s1, s2 string) string

Diff returns a diff between s1 and s2. It uses the diff tool if installed otherwise degrades to using the dmp package.

func FormatTestCode Uses

func FormatTestCode(t *testing.T, code string) string

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 Uses

func GoNativeTypeName(t expr.DataType) string

GoNativeTypeName returns the Go built-in type corresponding to the given primitive type. GoNativeType panics if t is not a primitive type.

func Goify Uses

func Goify(str string, firstUpper bool) string

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 Uses

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 Uses

func Indent(s, prefix string) string

Indent inserts prefix at the beginning of each non-empty line of s. The end-of-line marker is NL.

func IsCompatible Uses

func IsCompatible(a, b expr.DataType, actx, bctx string) error

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 KebabCase Uses

func KebabCase(name string) string

KebabCase produces the kebab-case version of the given CamelCase string.

func MapDepth Uses

func MapDepth(m *expr.Map) int

MapDepth returns the level of nested maps. For unnested maps, it returns 0.

func RecursiveValidationCode Uses

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 Uses

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 Uses

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 Uses

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 RunDSL Uses

func RunDSL(t *testing.T, dsl func()) *expr.RootExpr

RunDSL returns the DSL root resulting from running the given DSL.

func RunDSLWithFunc Uses

func RunDSLWithFunc(t *testing.T, dsl func(), fn func()) *expr.RootExpr

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 Uses

func RunPluginsPrepare(cmd, genpkg string, roots []eval.Root) error

RunPluginsPrepare executes the plugins prepare functions in the order they were registered.

func SectionCode Uses

func SectionCode(t *testing.T, section *SectionTemplate) string

SectionCode generates and formats the code for the given section.

func SectionCodeFromImportsAndMethods Uses

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 Uses

func SectionsCode(t *testing.T, sections []*SectionTemplate) string

SectionsCode generates and formats the code for the given sections.

func SnakeCase Uses

func SnakeCase(name string) string

SnakeCase produces the snake_case version of the given CamelCase string.

func TemplateFuncs Uses

func TemplateFuncs() map[string]interface{}

TemplateFuncs lists common template helper functions.

func ValidationCode Uses

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 Uses

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 Uses

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.

func WalkType Uses

func WalkType(u expr.UserType, walker func(*expr.AttributeExpr) error) error

WalkType traverses the data structure recursively and calls the given function once on each attribute starting with the user type attribute.

func WrapText Uses

func WrapText(text string, maxChars int) string

WrapText produces lines with text capped at maxChars it will keep words intact and respects newlines.

type AttributeContext Uses

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 Uses

func NewAttributeContext(pointer, reqIgnore, useDefault bool, pkg string, scope *NameScope) *AttributeContext

NewAttributeContext initializes an attribute context.

func (*AttributeContext) Dup Uses

func (a *AttributeContext) Dup() *AttributeContext

Dup creates a shallow copy of the AttributeContext.

func (*AttributeContext) IsPrimitivePointer Uses

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 Uses

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 Uses

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

AttributeScope contains the scope of an attribute. It implements the Attributor interface.

func (*AttributeScope) Field Uses

func (a *AttributeScope) Field(att *expr.AttributeExpr, name string, firstUpper bool) string

Field returns a valid Go struct field name.

func (*AttributeScope) Name Uses

func (a *AttributeScope) Name(att *expr.AttributeExpr, pkg string) string

Name returns the type name for the given attribute.

func (*AttributeScope) Ref Uses

func (a *AttributeScope) Ref(att *expr.AttributeExpr, pkg string) string

Ref returns the type name for the given attribute.

func (*AttributeScope) Scope Uses

func (a *AttributeScope) Scope() *NameScope

Scope returns the name scope.

type Attributor Uses

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 Uses

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 Uses

func RunPlugins(cmd, genpkg string, roots []eval.Root, genfiles []*File) ([]*File, error)

RunPlugins executes the plugins registered with the given command in the order they were registered.

func (*File) Render Uses

func (f *File) Render(dir string) (string, error)

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 Uses

func (f *File) Section(name string) []*SectionTemplate

Section returns the section templates with the given name or nil if not found.

type GenerateFunc Uses

type GenerateFunc func(genpkg string, roots []eval.Root, files []*File) ([]*File, error)

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 Uses

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 Uses

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 Uses

func GetMetaTypeImports(att *expr.AttributeExpr) []*ImportSpec

GetMetaTypeImports parses the attribute for all user defined imports

func NewImport Uses

func NewImport(name, path string) *ImportSpec

NewImport creates an import spec.

func SimpleImport Uses

func SimpleImport(path string) *ImportSpec

SimpleImport creates an import with no explicit path component.

func (*ImportSpec) Code Uses

func (s *ImportSpec) Code() string

Code returns the Go import statement for the ImportSpec.

type MappedAttributeWalker Uses

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 Uses

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

NameScope defines a naming scope.

func NewNameScope Uses

func NewNameScope() *NameScope

NewNameScope creates an empty name scope.

func (*NameScope) GoFullTypeName Uses

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 Uses

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 Uses

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 Uses

func (s *NameScope) GoTypeName(att *expr.AttributeExpr) string

GoTypeName returns the Go type name of the given attribute type.

func (*NameScope) GoTypeRef Uses

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 Uses

func (s *NameScope) GoVar(varName string, dt expr.DataType) string

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 Uses

func (s *NameScope) HashedUnique(key Hasher, name string, suffix ...string) string

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 Uses

func (s *NameScope) Name(name string) string

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.

func (*NameScope) Unique Uses

func (s *NameScope) Unique(name string, suffix ...string) string

Unique returns a unique name for the given name. A suffix is appended to the name if given name is not unique. If suffixed name is still not unique, a counter value is added to the suffixed name until unique.

type PrepareFunc Uses

type PrepareFunc func(genpkg string, roots []eval.Root) error

PrepareFunc makes it possible to modify the design roots before the files being generated by the goa code generators or other plugins.

type Scoper Uses

type Scoper interface {
    Scope() *NameScope
}

Scoper provides a scope for generating unique names.

type SectionTemplate Uses

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(title, pack string, imports []*ImportSpec) *SectionTemplate

Header returns a Go source file header section template.

func (*SectionTemplate) Write Uses

func (s *SectionTemplate) Write(w io.Writer) error

Write writes the section to the given writer.

type TransformAttrs Uses

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 Uses

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 Uses

func AppendHelpers(oldH, newH []*TransformFunctionData) []*TransformFunctionData

AppendHelpers takes care of only appending helper functions from newH that are not already in oldH.

func GoTransform Uses

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

Directories

PathSynopsis
cliPackage 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.
examplePackage example contains code generation algorithms to produce an example server and client implementation for the transports defined in the design.
generatorPackage generator contains the code generation algorithms for a service server, client, and OpenAPI specification.
servicePackage 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 codegen imports 25 packages (graph) and is imported by 21 packages. Updated 2019-08-22. Refresh now. Tools for package owners.