codegen

package
v3.14.4 Latest Latest
Warning

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

Go to latest
Published: Jan 8, 2024 License: MIT Imports: 24 Imported by: 117

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

View Source
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

View Source
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

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

func CommandLine() string

CommandLine return the command used to run this process.

func Comment

func Comment(elems ...string) string

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

func CreateTempFile

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

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

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

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

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

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

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

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, both unions or one union and one object. actx and bctx are used to build the error message if any.

func KebabCase

func KebabCase(name string) string

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

func MapDepth

func MapDepth(m *expr.Map) int

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

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 RunDSL

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

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

func RunPluginsPrepare

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

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 SnakeCase

func SnakeCase(name string) string

SnakeCase produces the snake_case version of the given CamelCase string. News => news OldNews => old_news CNNNews => cnn_news

func TemplateFuncs

func TemplateFuncs() map[string]any

TemplateFuncs lists common template helper functions.

func UnionValTypeName added in v3.7.0

func UnionValTypeName(unionName string) string

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 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.

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.

func WalkType

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

func WrapText(text string, maxChars int) string

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

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

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

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

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

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

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

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

type GenerateFunc

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

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 NewImport

func NewImport(name, path string) *ImportSpec

NewImport creates an import spec.

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

func UserTypeLocation(dt expr.DataType) *Location

UserTypeLocation returns the location of the user type if set via the attr:pkg:path metadata, nil otherwise..

func (*Location) PackageName added in v3.6.0

func (loc *Location) PackageName() string

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 NewNameScope

func NewNameScope() *NameScope

NewNameScope creates an empty name 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

func (*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

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

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

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

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

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

Header returns a Go source file header section template.

func (*SectionTemplate) Write

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

Write writes the section to the given writer.

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.

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.

Jump to

Keyboard shortcuts

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