github.com/goadesign/goa/codegen


codegen

import "github.com/goadesign/goa/codegen"

Overview

Index

Package files

file.go funcs.go goify.go header.go import.go plugin.go scope.go testing.go transform.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 Add

func Add(a, b int) int

Add adds two integers and returns the sum of the two.

func AddImport

func AddImport(section *SectionTemplate, imprt *ImportSpec)

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

func AttributeTags

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

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

func CheckVersion

func CheckVersion(ver string) error

CheckVersion returns an error if the ver is empty, contains an incorrect value or a version number that is not compatible with the version of this repo.

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 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 design.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 *design.AttributeExpr, name string, upper bool) string

GoifyAtt honors any struct:field:name metadata set on the attribute and calls Goify with the tag value if present or the given name otherwise.

func HasValidations

func HasValidations(att *design.AttributeExpr, ignoreRequired bool) bool

HasValidations returns true if the given attribute or any of its children recursively has validations. If ignoreRequired is true then HasValidation does not consider “Required” validations. This is necessary to know whether validation code should be generated for types that don’t use pointers to define required fields.

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 KebabCase

func KebabCase(name string) string

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

func RecursiveValidationCode

func RecursiveValidationCode(att *design.AttributeExpr, req, ptr, def 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.

func RegisterPlugin

func RegisterPlugin(name string, cmd string, 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, 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, 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()) *design.RootExpr

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

func RunDSLWithFunc

func RunDSLWithFunc(t *testing.T, dsl func(), fn func()) *design.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 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 SnakeCase

func SnakeCase(name string) string

SnakeCase produces the snake_case version of the given CamelCase string.

func TemplateFuncs

func TemplateFuncs() map[string]interface{}

TemplateFuncs lists common template helper functions.

func ValidationCode

func ValidationCode(att *design.AttributeExpr, req, ptr, def 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.

req indicates whether the attribute is required (true) or optional (false) in which case target is a pointer if ptr is false and def is false or def is true and there’s no default value.

ptr indicates whether the data structure described by att uses pointers to hold all attributes (even required ones) so that they may be properly validated.

def indicates whether non required attributes that have a default value should not be pointers.

req | ptr | def | pointer?
 T  |  F  |  F  | F
 T  |  F  |  T  | F
 T  |  T  |  F  | T
 T  |  T  |  T  | T
 F  |  F  |  F  | T
 F  |  F  |  T  | F if has default value, T otherwise
 F  |  T  |  F  | T
 F  |  T  |  T  | T

context is used to produce helpful messages in case of error.

func Walk

func Walk(a *design.AttributeExpr, walker func(*design.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 *design.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 design.UserType, walker func(*design.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.

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
}

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

type MappedAttributeWalker func(name, elem string, required bool, a *design.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 *design.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 *design.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 *design.AttributeExpr, 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).

func (*NameScope) GoTypeName

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

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

func (*NameScope) GoTypeRef

func (s *NameScope) GoTypeRef(att *design.AttributeExpr) string

GoTypeRef returns the Go code that refers to 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) Unique

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

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

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.

func (*SectionTemplate) Write

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

Write writes the section to the given writer.

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 GoTypeTransform

func GoTypeTransform(source, target design.DataType, sourceVar, targetVar, sourcePkg, targetPkg string, unmarshal bool, scope *NameScope) (string, []*TransformFunctionData, error)

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

sourceVar and targetVar contain the name of the variables that hold the source and target data structures respectively.

sourcePkg and targetPkg contain the name of the Go package that defines the source or target type respectively in case it’s not the same package as where the generated code lives.

unmarshal if true indicates whether the code is being generated to initialize a type from unmarshaled data, otherwise to initialize a type that is marshaled:

  if unmarshal is true (unmarshal)
    - The source type uses pointers for all fields - even required ones.
    - The target type do not use pointers for primitive fields that have
             default values even when not required.

  if unmarshal is false (marshal)
    - The source type used do not use pointers for primitive fields that
             have default values even when not required.
    - The target type fields are initialized with their default values
             (if any) when source field is a primitive pointer and nil or a
             non-primitive type and nil.

scope is used to compute the name of the user types when initializing fields that use them.


Generated by godoc2md