codegen

package
v0.0.0-...-28775f4 Latest Latest
Warning

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

Go to latest
Published: May 2, 2016 License: MIT Imports: 20 Imported by: 0

Documentation

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

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

View Source
const Version = "0.0.1"

Version of generator tools.

Variables

View Source
var (
	// OutputDir is the path to the directory the generated files should be
	// written to.
	OutputDir string

	// DesignPackagePath is the path to the user Go design package.
	DesignPackagePath string

	// Debug toggles debug mode.
	// If debug mode is enabled then the generated files are not
	// cleaned up upon failure.
	// Also logs additional debug information.
	// Set this flag to true prior to calling Generate.
	Debug bool

	// NoFormat causes "goimports" to be skipped when true.
	NoFormat bool

	// CommandName is the name of the command being run.
	CommandName string

	// ExtraFlags is the list of extra, arbitrary flags to was read from the
	// command line.  These flags will be passed as command line flags to the
	// final generator.
	ExtraFlags []string
)
View Source
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,
		"gonative":            GoNativeType,
		"gotypedef":           GoTypeDef,
		"gotypename":          GoTypeName,
		"gotypedesc":          GoTypeDesc,
		"gotyperef":           GoTypeRef,
		"join":                strings.Join,
		"recursiveFinalizer":  RecursiveFinalizer,
		"recursiveValidate":   RecursiveChecker,
		"recursivePublicizer": RecursivePublicizer,
		"tabs":                Tabs,
		"tempvar":             Tempvar,
		"title":               strings.Title,
		"toLower":             strings.ToLower,
		"validationChecker":   ValidationChecker,
	}
)
View Source
var (
	// TempCount holds the value appended to variable names to make them unique.
	TempCount int
)

Functions

func Add

func Add(a, b int) int

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

func BuiltInTypeName

func BuiltInTypeName(mt *design.MediaTypeDefinition) string

BuiltInTypeName returns the name of the goa struct corresponding to the media type definition or the empty string if there isn't one.

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

func RecursiveChecker(att *design.AttributeDefinition, nonzero, required, hasDefault bool, target, context string, depth int, private bool) string

RecursiveChecker produces Go code that runs the validation checks recursively over the given attribute.

func RecursiveFinalizer

func RecursiveFinalizer(att *design.AttributeDefinition, target string, depth int) string

RecursiveFinalizer produces Go code that sets the default values for fields recursively for the given attribute.

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 RegisterFlags

func RegisterFlags(r FlagRegistry)

RegisterFlags registers the global flags.

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.

Types

type BaseCommand

type BaseCommand struct {
	CmdName        string
	CmdDescription string
}

BaseCommand provides the basic logic for all commands. It implements the Command interface. Commands may then specialize to provide the specific Run behavior.

func NewBaseCommand

func NewBaseCommand(name, desc string) *BaseCommand

NewBaseCommand instantiates a base command.

func (*BaseCommand) Description

func (b *BaseCommand) Description() string

Description returns the command description.

func (*BaseCommand) Name

func (b *BaseCommand) Name() string

Name returns the command name.

func (*BaseCommand) RegisterFlags

func (b *BaseCommand) RegisterFlags(r FlagRegistry)

RegisterFlags is a dummy implementation, override in sub-command.

func (*BaseCommand) Run

func (b *BaseCommand) Run() ([]string, error)

Run is a dummy implementation, override in sub-command.

type Command

type Command interface {
	// Name of the command
	Name() string

	// Description returns the description used by the goa tool help.
	Description() string

	// RegisterFlags initializes the given registry flags with all
	// the flags relevant to this command.
	RegisterFlags(r FlagRegistry)

	// Run generates the generator code then compiles and runs it.
	// It returns the list of generated files.
	// Run uses the variables initialized by the command line defined in RegisterFlags.
	Run() ([]string, error)
}

Command is the interface implemented by all generation goa commands. There is one command per generation target (i.e. app, docs, etc.)

type FlagRegistry

type FlagRegistry interface {
	// Flags returns the command flag set
	Flags() *pflag.FlagSet
}

FlagRegistry is the interface implemented by cobra.Command to register flags.

type ImportSpec

type ImportSpec struct {
	Name string
	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 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

CreateSourceFile creates a Go source file in the given package.

type SourceFile

type SourceFile struct {
	// Name of the source file
	Name string
	// Package containing source file
	Package *Package
}

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) 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 runs "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 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.

Jump to

Keyboard shortcuts

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