github.com/goadesign/goa/goagen/codegen
codegen
import "github.com/goadesign/goa/goagen/codegen"
Overview
Package codegen contains common code used by all code generators. Each sub-package corresponds to a code generator. The “meta” sub-package is the generator generator: it contains code that compiles and runs a specific generator tool that uses the user metadata.
Index
- Constants
- Variables
- func Add(a, b int) int
- func CanonicalParams(r *design.ResourceDefinition) []string
- func CanonicalTemplate(r *design.ResourceDefinition) string
- func CheckVersion(ver string) error
- func CommandLine() string
- func Comment(elems …string) string
- func GoNativeType(t design.DataType) string
- func GoTypeDef(ds design.DataStructure, tabs int, jsonTags, private bool) string
- func GoTypeDesc(t design.DataType, upper bool) string
- func GoTypeName(t design.DataType, required []string, tabs int, private bool) string
- func GoTypeRef(t design.DataType, required []string, tabs int, private bool) string
- func GoTypeTransform(source, target *design.UserTypeDefinition, targetPkg, funcName string) (string, error)
- func GoTypeTransformName(source, target *design.UserTypeDefinition, suffix string) string
- func Goify(str string, firstUpper bool) string
- func GoifyAtt(att *design.AttributeDefinition, name string, firstUpper bool) string
- func Indent(s, prefix string) string
- func IndentBytes(b, prefix []byte) []byte
- func KebabCase(name string) string
- func PackageName(path string) (string, error)
- func PackagePath(path string) (string, error)
- func PackageSourcePath(pkg string) (string, error)
- func ParseDSL()
- func PrintVal(t design.DataType, val interface{}) string
- func Publicizer(att *design.AttributeDefinition, sourceField, targetField string, dereference bool, depth int, init bool) string
- func RecursivePublicizer(att *design.AttributeDefinition, source, target string, depth int) string
- func Run(generators …generator)
- func RunTemplate(tmpl *template.Template, data interface{}) string
- func SnakeCase(name string) string
- func Tabs(depth int) string
- func Tempvar() string
- func ValidationChecker(att *design.AttributeDefinition, nonzero, required, hasDefault bool, target, context string, depth int, private bool) string
- func WriteTabs(buf *bytes.Buffer, count int)
- type Finalizer
- type ImportSpec
- type Package
- type SourceFile
- func SourceFileFor(path string) (*SourceFile, error)
- func (f *SourceFile) Abs() string
- func (f *SourceFile) Close()
- func (f *SourceFile) ExecuteTemplate(name, source string, funcMap template.FuncMap, data interface{}) error
- func (f *SourceFile) FormatCode() error
- func (f *SourceFile) Write(b []byte) (int, error)
- func (f *SourceFile) WriteHeader(title, pack string, imports []*ImportSpec) error
- type Validator
- type Workspace
Package files
doc.go finalizer.go helpers.go import_spec.go publicizer.go run.go types.go validation.go workspace.go
Constants
const TransformMapKey = "transform:key"
TransformMapKey is the name of the metadata used to specify the key for mapping fields when generating the code that transforms one data structure into another.
Variables
var (
// DefaultFuncMap is the FuncMap used to initialize all source file templates.
DefaultFuncMap = template.FuncMap{
"add": func(a, b int) int { return a + b },
"commandLine": CommandLine,
"comment": Comment,
"goify": Goify,
"goifyatt": GoifyAtt,
"gonative": GoNativeType,
"gotypedef": GoTypeDef,
"gotypename": GoTypeName,
"gotypedesc": GoTypeDesc,
"gotyperef": GoTypeRef,
"join": strings.Join,
"recursivePublicizer": RecursivePublicizer,
"tabs": Tabs,
"tempvar": Tempvar,
"title": strings.Title,
"toLower": strings.ToLower,
"validationChecker": ValidationChecker,
}
)
var Reserved = map[string]bool{
"byte": true,
"complex128": true,
"complex64": true,
"float32": true,
"float64": true,
"int": true,
"int16": true,
"int32": true,
"int64": true,
"int8": true,
"rune": true,
"string": true,
"uint16": true,
"uint32": true,
"uint64": true,
"uint8": true,
"break": true,
"case": true,
"chan": true,
"const": true,
"continue": true,
"default": true,
"defer": true,
"else": true,
"fallthrough": true,
"for": true,
"func": true,
"go": true,
"goto": true,
"if": true,
"import": true,
"interface": true,
"map": true,
"package": true,
"range": true,
"return": true,
"select": true,
"struct": true,
"switch": true,
"type": true,
"var": true,
"fmt": true,
"http": true,
"json": true,
"os": true,
"url": true,
"time": true,
}
Reserved golang keywords and package names
var (
// TempCount holds the value appended to variable names to make them unique.
TempCount int
)
func Add
func Add(a, b int) int
Add adds two integers and returns the sum of the two.
func CanonicalParams
func CanonicalParams(r *design.ResourceDefinition) []string
CanonicalParams returns the list of parameter names needed to build the canonical href to the resource. It returns nil if the resource does not have a canonical action.
func CanonicalTemplate
func CanonicalTemplate(r *design.ResourceDefinition) string
CanonicalTemplate returns the resource URI template as a format string suitable for use in the fmt.Printf function family.
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 GoNativeType
func GoNativeType(t design.DataType) string
GoNativeType returns the Go built-in type from which instances of t can be initialized.
func GoTypeDef
func GoTypeDef(ds design.DataStructure, tabs int, jsonTags, private 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
).
tabs is the number of tab character(s) used to tabulate the definition however the first
line is never indented.
jsonTags controls whether to produce json tags.
private controls whether the field is a pointer or not. All fields in the struct are
pointers for a private struct.
func GoTypeDesc
func GoTypeDesc(t design.DataType, upper bool) string
GoTypeDesc returns the description of a type. If no description is defined for the type, one will be generated.
func GoTypeName
func GoTypeName(t design.DataType, required []string, tabs int, private bool) string
GoTypeName returns the Go type name for a data type. tabs is used to properly tabulate the object struct fields and only applies to this case. This function assumes the type is in the same package as the code accessing it. required only applies when referring to a user type that is an object defined inline. In this case the type (Object) does not carry the required field information defined in the parent (anonymous) attribute.
func GoTypeRef
func GoTypeRef(t design.DataType, required []string, tabs int, private bool) string
GoTypeRef returns the Go code that refers to the Go type which matches the given data type
(the part that comes after var foo
)
required only applies when referring to a user type that is an object defined inline. In this
case the type (Object) does not carry the required field information defined in the parent
(anonymous) attribute.
tabs is used to properly tabulate the object struct fields and only applies to this case.
This function assumes the type is in the same package as the code accessing it.
func GoTypeTransform
func GoTypeTransform(source, target *design.UserTypeDefinition, targetPkg, funcName string) (string, error)
GoTypeTransform produces Go code that initializes the data structure defined by target from an instance of the data structure described by source. The algorithm matches object fields by name or using the value of the “transform:key” attribute metadata when present. The function returns an error if target is not compatible with source (different type, fields of different type etc). It ignores fields in target that don’t have a match in source.
func GoTypeTransformName
func GoTypeTransformName(source, target *design.UserTypeDefinition, suffix string) string
GoTypeTransformName generates a valid Go identifer that is adequate for naming the type transform function that creates an instance of the data structure described by target from an instance of the data strucuture described by source.
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.AttributeDefinition, name string, firstUpper 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 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 IndentBytes
func IndentBytes(b, prefix []byte) []byte
IndentBytes inserts prefix at the beginning of each non-empty line of b. 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 PackageName
func PackageName(path string) (string, error)
PackageName returns the name of a package at the given path
func PackagePath
func PackagePath(path string) (string, error)
PackagePath returns the Go package path for the directory that lives under the given absolute file path.
func PackageSourcePath
func PackageSourcePath(pkg string) (string, error)
PackageSourcePath returns the absolute path to the given package source.
func ParseDSL
func ParseDSL()
ParseDSL will run the DSL engine and analyze any imported design
package, creating your design.APIDefinition
along the way.
func PrintVal
func PrintVal(t design.DataType, val interface{}) string
PrintVal prints the given value corresponding to the given data type. The value is already checked for the compatibility with the data type.
func Publicizer
func Publicizer(att *design.AttributeDefinition, sourceField, targetField string, dereference bool, depth int, init bool) string
Publicizer publicizes a single attribute based on the type.
func RecursivePublicizer
func RecursivePublicizer(att *design.AttributeDefinition, source, target string, depth int) string
RecursivePublicizer produces code that copies fields from the private struct to the public struct
func Run
func Run(generators ...generator)
Run runs all generators passed as parameter. Call ParseDSL first to
fill design.Design
. Each goa
generator lives in its own
goagen/gen_something
package in generator.go
and has a
Generator
object which implements the interface required here.
codegen.Run(
&genapp.Generator{
API: design.Design,
Target: "app",
},
&genmain.Generator{
API: design.Design,
},
)
func RunTemplate
func RunTemplate(tmpl *template.Template, data interface{}) string
RunTemplate executs the given template with the given input and returns the rendered string.
func SnakeCase
func SnakeCase(name string) string
SnakeCase produces the snake_case version of the given CamelCase string.
func Tabs
func Tabs(depth int) string
Tabs returns a string made of depth tab characters.
func Tempvar
func Tempvar() string
Tempvar generates a unique variable name.
func ValidationChecker
func ValidationChecker(att *design.AttributeDefinition, nonzero, required, hasDefault bool, target, context string, depth int, private bool) string
ValidationChecker produces Go code that runs the validation defined in the given attribute definition against the content of the variable named target recursively. context is used to keep track of recursion to produce helpful error messages in case of type validation error. The generated code assumes that there is a pre-existing “err” variable of type error. It initializes that variable in case a validation fails. Note: we do not want to recurse here, recursion is done by the marshaler/unmarshaler code.
func WriteTabs
func WriteTabs(buf *bytes.Buffer, count int)
WriteTabs is a helper function that writes count tabulation characters to buf.
type Finalizer
type Finalizer struct {
// contains filtered or unexported fields
}
Finalizer is the code generator for the ‘Finalize’ type methods.
func NewFinalizer
func NewFinalizer() *Finalizer
NewFinalizer instantiates a finalize code generator.
func (*Finalizer) Code
func (f *Finalizer) Code(att *design.AttributeDefinition, target string, depth int) string
Code produces Go code that sets the default values for fields recursively for the given attribute.
type ImportSpec
type ImportSpec struct {
Name string
Path string
}
ImportSpec defines a generated import statement.
func AttributeImports
func AttributeImports(att *design.AttributeDefinition, imports []*ImportSpec, seen []*design.AttributeDefinition) []*ImportSpec
AttributeImports constructs a new ImportsSpec slice from an existing slice and adds in imports specified in struct:field:type Metadata tags.
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 Package
type Package struct {
// (Go) Path of package
Path string
// Workspace containing package
Workspace *Workspace
}
Package represents a temporary Go package
func PackageFor
func PackageFor(source string) (*Package, error)
PackageFor returns the package for the given source file.
func (*Package) Abs
func (p *Package) Abs() string
Abs returns the absolute path to the package source directory
func (*Package) Compile
func (p *Package) Compile(bin string) (string, error)
Compile compiles a package and returns the path to the compiled binary.
func (*Package) CreateSourceFile
func (p *Package) CreateSourceFile(name string) (*SourceFile, error)
CreateSourceFile creates a Go source file in the given package. If the file already exists it is overwritten.
func (*Package) OpenSourceFile
func (p *Package) OpenSourceFile(name string) (*SourceFile, error)
OpenSourceFile opens an existing file to append to it. If the file does not exist OpenSourceFile creates it.
type SourceFile
type SourceFile struct {
// Name of the source file
Name string
// Package containing source file
Package *Package
// contains filtered or unexported fields
}
SourceFile represents a single Go source file
func SourceFileFor
func SourceFileFor(path string) (*SourceFile, error)
SourceFileFor returns a SourceFile for the file at the given path.
func (*SourceFile) Abs
func (f *SourceFile) Abs() string
Abs returne the source file absolute filename
func (*SourceFile) Close
func (f *SourceFile) Close()
Close closes the underlying OS file.
func (*SourceFile) ExecuteTemplate
func (f *SourceFile) ExecuteTemplate(name, source string, funcMap template.FuncMap, data interface{}) error
ExecuteTemplate executes the template and writes the output to the file.
func (*SourceFile) FormatCode
func (f *SourceFile) FormatCode() error
FormatCode performs the equivalent of “goimports -w” on the source file.
func (*SourceFile) Write
func (f *SourceFile) Write(b []byte) (int, error)
Write implements io.Writer so that variables of type *SourceFile can be used in template.Execute.
func (*SourceFile) WriteHeader
func (f *SourceFile) WriteHeader(title, pack string, imports []*ImportSpec) error
WriteHeader writes the generic generated code header.
type Validator
type Validator struct {
// contains filtered or unexported fields
}
Validator is the code generator for the ‘Validate’ type methods.
func NewValidator
func NewValidator() *Validator
NewValidator instantiates a validate code generator.
func (*Validator) Code
func (v *Validator) Code(att *design.AttributeDefinition, nonzero, required, hasDefault bool, target, context string, depth int, private bool) string
Code produces Go code that runs the validation checks recursively over the given attribute.
type Workspace
type Workspace struct {
// Path is the absolute path to the workspace directory.
Path string
// contains filtered or unexported fields
}
Workspace represents a temporary Go workspace
func NewWorkspace
func NewWorkspace(prefix string) (*Workspace, error)
NewWorkspace returns a newly created temporary Go workspace. Use Delete to delete the corresponding temporary directory when done.
func WorkspaceFor
func WorkspaceFor(source string) (*Workspace, error)
WorkspaceFor returns the Go workspace for the given Go source file.
func (*Workspace) Delete
func (w *Workspace) Delete()
Delete deletes the workspace temporary directory.
func (*Workspace) NewPackage
func (w *Workspace) NewPackage(goPath string) (*Package, error)
NewPackage creates a new package in the workspace. It deletes any pre-existing package. goPath is the go package path used to import the package.
func (*Workspace) Reset
func (w *Workspace) Reset() error
Reset removes all content from the workspace.
Generated by godoc2md