goa: github.com/goadesign/goa/goagen/codegen Index | Files

package codegen

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

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

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 Uses

func Add(a, b int) int

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

func AttributeImports Uses

func AttributeImports(att *design.AttributeDefinition, imports []*ImportSpec, seen []*design.AttributeDefinition) []*ImportSpec

AttributeImports will construct a new ImportsSpec slice from an existing slice and add in imports specified in struct:field:type Metadata tags.

func CanonicalParams Uses

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 Uses

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 Uses

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

func GoNativeType(t design.DataType) string

GoNativeType returns the Go built-in type from which instances of t can be initialized.

func GoTypeDef Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 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 *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 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 IndentBytes Uses

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 Uses

func KebabCase(name string) string

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

func PackageName Uses

func PackageName(path string) (string, error)

PackageName returns the name of a package at the given path

func PackagePath Uses

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 Uses

func PackageSourcePath(pkg string) (string, error)

PackageSourcePath returns the absolute path to the given package source.

func ParseDSL Uses

func ParseDSL()

ParseDSL will run the DSL engine and analyze any imported `design` package, creating your `design.APIDefinition` along the way.

func PrintVal Uses

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 Uses

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 Uses

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 Uses

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 Uses

func RunTemplate(tmpl *template.Template, data interface{}) string

RunTemplate executs the given template with the given input and returns the rendered string.

func SnakeCase Uses

func SnakeCase(name string) string

SnakeCase produces the snake_case version of the given CamelCase string.

func Tabs Uses

func Tabs(depth int) string

Tabs returns a string made of depth tab characters.

func Tempvar Uses

func Tempvar() string

Tempvar generates a unique variable name.

func ValidationChecker Uses

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 Uses

func WriteTabs(buf *bytes.Buffer, count int)

WriteTabs is a helper function that writes count tabulation characters to buf.

type Finalizer Uses

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

Finalizer is the code generator for the 'Finalize' type methods.

func NewFinalizer Uses

func NewFinalizer() *Finalizer

NewFinalizer instantiates a finalize code generator.

func (*Finalizer) Code Uses

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 Uses

type ImportSpec struct {
    Name string
    Path string
}

ImportSpec defines a generated import statement.

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

type Package struct {
    // (Go) Path of package
    Path string
    // Workspace containing package
    Workspace *Workspace
}

Package represents a temporary Go package

func PackageFor Uses

func PackageFor(source string) (*Package, error)

PackageFor returns the package for the given source file.

func (*Package) Abs Uses

func (p *Package) Abs() string

Abs returns the absolute path to the package source directory

func (*Package) Compile Uses

func (p *Package) Compile(bin string) (string, error)

Compile compiles a package and returns the path to the compiled binary.

func (*Package) CreateSourceFile Uses

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 Uses

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 Uses

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 Uses

func SourceFileFor(path string) (*SourceFile, error)

SourceFileFor returns a SourceFile for the file at the given path.

func (*SourceFile) Abs Uses

func (f *SourceFile) Abs() string

Abs returne the source file absolute filename

func (*SourceFile) Close Uses

func (f *SourceFile) Close()

Close closes the underlying OS file.

func (*SourceFile) ExecuteTemplate Uses

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 Uses

func (f *SourceFile) FormatCode() error

FormatCode performs the equivalent of "goimports -w" on the source file.

func (*SourceFile) Write Uses

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 Uses

func (f *SourceFile) WriteHeader(title, pack string, imports []*ImportSpec) error

WriteHeader writes the generic generated code header.

type Validator Uses

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

Validator is the code generator for the 'Validate' type methods.

func NewValidator Uses

func NewValidator() *Validator

NewValidator instantiates a validate code generator.

func (*Validator) Code Uses

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 Uses

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 Uses

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 Uses

func WorkspaceFor(source string) (*Workspace, error)

WorkspaceFor returns the Go workspace for the given Go source file.

func (*Workspace) Delete Uses

func (w *Workspace) Delete()

Delete deletes the workspace temporary directory.

func (*Workspace) NewPackage Uses

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 Uses

func (w *Workspace) Reset() error

Reset removes all content from the workspace.

Package codegen imports 23 packages (graph) and is imported by 161 packages. Updated 2017-08-08. Refresh now. Tools for package owners.