Documentation ¶
Index ¶
- Constants
- Variables
- func Appendf(ss *[]string, format string, v ...interface{})
- func AssertFuncType(field *ast.Field) (name string, ft *ast.FuncType, ok bool)
- func Bytesf(format string, v ...interface{}) []byte
- func CommentLines(comment string) string
- func EscapeAnnotation(str string) string
- func ExecCommand(command, dir string) (output string, err error)
- func ExecuteTemplate(data interface{}, text string, writer io.Writer) (err error)
- func ExtractAnonymousName(spec ast.Expr) (name *ast.Ident)
- func ExtractStructFieldsNames(typ *ast.StructType) (names []string)
- func FixPackage(name, srcImportPath, dstImportPath string, srcImports, dstImports Imports) string
- func GetImportName(filename string) string
- func GetImportPath(filename string) string
- func GetModFile(dir string) string
- func GetOrWriteDefault(filename string, defaultData []byte) ([]byte, error)
- func GetPackageImportDir(pkg, dir string) (output string)
- func GetPackageImportName(pkg, dir string) (output string)
- func IsGoFile(path string) bool
- func IsStandardImportPath(path string) bool
- func IterateOrmFieldMapper(i Iterator, f func(m OrmFieldMapper, b bool) bool)
- func JoinDocs(docs []string) string
- func KebabCase(s string) string
- func LoadExtension(filename string) (name string, err error)
- func LowerCamelCase(s string) string
- func OrmTypeMapping() map[string]string
- func ParseCommentGroup(prefix string, cg ...*ast.CommentGroup) (docs, annotations []string)
- func PluginRegistry() map[string]Plugin
- func ReadFile(filename string) (data []byte, version string, err error)
- func RegisterOrmSchemaDriver(driver OrmSchemaDriver)
- func RegisterPlugin(plugin Plugin)
- func RenderTemplate(plugin Plugin, templateText string, pkg string, editable bool, ext ...string) (data []byte, err error)
- func RenderWithDefaultTemplate(plugin Plugin, templateText, filename, pkg string, editable bool, ...) (err error)
- func RenderWrite(plugin Plugin, templateText, filename, pkg string, editable bool, ...) (err error)
- func ScanSqlRows(rows *sql.Rows, fields []string, iterator Iterator) (err error)
- func SnakeCase(s string) string
- func SplitKV(str string, sep string) (key, value string)
- func SplitKV2Map(str string, sep string, dst map[string]string)
- func SplitKVSlice2Map(ss []string, sep string, dst map[string]string)
- func TrimPrefix(str, prefix string) (string, bool)
- func TryExecuteTemplate(data interface{}, text string, dst *string)
- func UnescapeAnnotation(str string) string
- func UnsafeBytes2String(b []byte) string
- func UnsafeString2Bytes(s string) []byte
- func UpperCamelCase(s string) string
- func UpperKebabCase(s string) string
- func UpperSnakeCase(s string) string
- func WalkDir(dir string, fn func(filename string) error) (err error)
- func WalkPackage(dir string, fn func(file *File) (err error)) (files map[string]*File, err error)
- func WriteFile(filename string, data []byte, perm fs.FileMode) (updated bool, err error)
- type AnnotatedDecl
- type AnnotatedDecls
- func ParseDecls(d ast.Decl, prefix string) (items AnnotatedDecls)
- func ParseFileDecls(filename string, prefix string) (decls AnnotatedDecls, err error)
- func ParseFileOrDirectory(path string, prefix string) (decls AnnotatedDecls, err error)
- func ParseGenericDecl(gen *ast.GenDecl, prefix string) (decls AnnotatedDecls)
- type AnnotatedField
- type DeclEntities
- type DeclEntity
- type ErrGroup
- type FieldEntities
- type FieldEntity
- type File
- type Import
- type Imports
- type Iterator
- type KeySet
- type Modify
- type ModifySet
- type Options
- type OrmColumn
- type OrmFieldMapper
- type OrmSchemaDriver
- type OrmTable
- type Plugin
- type PluginEntities
- type PluginEntity
- type VersionStore
Constants ¶
const ( AnnotationSeparator = ":" EscapeAnnotationSeparator = `\u003A` KeyValueSeparator = "=" )
const ( DeclTypeInterface = iota + 1 // type T interface{} DeclTypeStruct // type T struct{} DeclTypeMap // type T map[string]string DeclTypeArray // type T []string DeclTypeFunc // type T func() DeclTypeRefer // type T T2 or type T = T2 DeclFunc // func Fn() DeclValue // var variable = 1 or var v Type or const constant = 1 )
Types of annotated declaration
const ( ExecSuffix = "zz" ExecName = "go" + ExecSuffix AnnotationIdent = "+" AnnotationPrefix = AnnotationIdent + ExecSuffix + ":" )
Variables ¶
var Logger = log.New(os.Stderr, "[GOZZ] ", 0)
var ( // SkipDirs contains some directory name would skip in walk SkipDirs = map[string]struct{}{ "vendor": {}, "node_modules": {}, "testdata": {}, } )
var ( TemplateFuncs = map[string]interface{}{ "quote": strconv.Quote, "title": strings.Title, "lower": strings.ToLower, "upper": strings.ToUpper, "snake": SnakeCase, "camel": LowerCamelCase, "kebab": KebabCase, "comment": CommentLines, } )
Functions ¶
func AssertFuncType ¶
AssertFuncType to assert interface fields as function type and try return name
func CommentLines ¶
func EscapeAnnotation ¶
func ExecCommand ¶
ExecCommand execute command in provide directory and get stdout,stderr as string,error
func ExecuteTemplate ¶
ExecuteTemplate parse provide text template and execute template data into writer
func ExtractStructFieldsNames ¶
func ExtractStructFieldsNames(typ *ast.StructType) (names []string)
ExtractStructFieldsNames extracts struct exported fields names
func FixPackage ¶
FixPackage modify or add selector package to provide name according to src and dst import module info
func GetImportName ¶
GetImportName get filename or directory module import name if file is not exist then return a relative calculated result from module environments
func GetImportPath ¶
GetImportName get filename or directory module import path if file is not exist then return a relative calculated result from module environments
func GetModFile ¶
GetModFile get directory direct mod file by execute "go env GOMOD"
func GetOrWriteDefault ¶
GetOrWriteDefault try read filename or write default data
func GetPackageImportDir ¶
func GetPackageImportName ¶
func IsStandardImportPath ¶
IsStandardImportPath check import path is whether golang standard library
func IterateOrmFieldMapper ¶
func IterateOrmFieldMapper(i Iterator, f func(m OrmFieldMapper, b bool) bool)
IterateOrmFieldMapper range slice and apply function receive OrmFieldMapper
func LoadExtension ¶
LoadExtension load filename and lookup symbol named "Z" symbol object should implement Plugin or OrmSchemaDriver
func LowerCamelCase ¶
LowerCamelCase converts a string into camel case starting with a lower case letter.
func OrmTypeMapping ¶
OrmTypeMapping provides default type mapping from sql datatype and golang type
func ParseCommentGroup ¶
func ParseCommentGroup(prefix string, cg ...*ast.CommentGroup) (docs, annotations []string)
ParseCommentGroup extract comment group text and split by lines if line match annotation prefix then append line to annotations else append line to docs
func PluginRegistry ¶
func ReadFile ¶
ReadFile try read filename and return data bytes. data bytes would be cached by version key
func RegisterOrmSchemaDriver ¶
func RegisterOrmSchemaDriver(driver OrmSchemaDriver)
RegisterOrmSchemaDriver registers OrmSchemaDriver to ormSchemaDriverRegistry
func RegisterPlugin ¶
func RegisterPlugin(plugin Plugin)
func RenderTemplate ¶
func RenderTemplate(plugin Plugin, templateText string, pkg string, editable bool, ext ...string) (data []byte, err error)
RenderTemplate render golang file template and generate headers
func RenderWrite ¶
func RenderWrite(plugin Plugin, templateText, filename, pkg string, editable bool, ext ...string) (err error)
RenderWrite render golang file template and write into filename
func ScanSqlRows ¶
ScanSqlRows scan iterator slice and scan sql.Rows values into iterated OrmFieldMapper elements
func SplitKV2Map ¶
SplitKV2Map split string into in key-value pairs by separator and set key-value into dst map
func SplitKVSlice2Map ¶
SplitKVSlice2Map split strings into in key-value pairs by separator and set key-value into dst map
func TrimPrefix ¶
TrimPrefix check strings has prefix and return trimmed string and check result
func TryExecuteTemplate ¶
TryExecuteTemplate try execute template, if success replace value to string pointer
func UnescapeAnnotation ¶
func UnsafeBytes2String ¶
func UnsafeString2Bytes ¶
func UpperCamelCase ¶
UpperCamelCase converts a string into camel case starting with a upper case letter.
func UpperKebabCase ¶
UpperKebabCase converts a string into kebab case with capital letters.
func UpperSnakeCase ¶
UpperSnakeCase converts a string into snake case with capital letters.
func WalkPackage ¶
WalkPackage walk package directory and parse file as *File. return *File map with filename
Types ¶
type AnnotatedDecl ¶
type AnnotatedDecl struct { File *File Type int FuncDecl *ast.FuncDecl TypeSpec *ast.TypeSpec ValueSpec *ast.ValueSpec Docs []string Annotations []string Fields []*AnnotatedField }
func ParseFuncDecl ¶
func ParseFuncDecl(decl *ast.FuncDecl, prefix string) (d *AnnotatedDecl)
ParseFuncDecl parse function declaration docs to match annotations prefix
Example:
// +zz:annotation:args:key=value func Foo() { }
func (*AnnotatedDecl) Filename ¶
func (decl *AnnotatedDecl) Filename() string
Filename return base filename from file ast
func (*AnnotatedDecl) Name ¶
func (decl *AnnotatedDecl) Name() string
Name return name from different decl
func (*AnnotatedDecl) Package ¶
func (decl *AnnotatedDecl) Package() string
Package return package name from file ast
func (*AnnotatedDecl) RelFilename ¶
func (decl *AnnotatedDecl) RelFilename(filename string, defaultName string) (ret string)
RelFilename return relative format filename from decl info and mod file if filename is absolute. filename would be related to mod file else filename would be related to declaration file if filename does not have ".go" suffix. defaultName provided would be added as base name and origin filename as directory name
type AnnotatedDecls ¶
type AnnotatedDecls []*AnnotatedDecl
func ParseDecls ¶
func ParseDecls(d ast.Decl, prefix string) (items AnnotatedDecls)
ParseDecls check declaration type parse generic declaration or function declaration and get annotated declarations
func ParseFileDecls ¶
func ParseFileDecls(filename string, prefix string) (decls AnnotatedDecls, err error)
ParseFileDecls parse provided file into ast and analysis declarations annotations return annotated declarations list or error while reading file or parsing ast
func ParseFileOrDirectory ¶
func ParseFileOrDirectory(path string, prefix string) (decls AnnotatedDecls, err error)
ParseFileOrDirectory try parse provided path annotated declarations with annotations prefix if directory provided. walks file tree from provided path as root and returns all parsed
func ParseGenericDecl ¶
func ParseGenericDecl(gen *ast.GenDecl, prefix string) (decls AnnotatedDecls)
ParseGenericDecl parse generic declaration to match annotation prefix
func (AnnotatedDecls) Parse ¶
func (decls AnnotatedDecls) Parse(plugin Plugin, extOptions map[string]string) (entities DeclEntities)
Parse parses declarations by plugin's name and args count. returns declaration entities with parsed args and options
type AnnotatedField ¶
type AnnotatedField struct { Decl *AnnotatedDecl Field *ast.Field Docs []string Annotations []string }
func (*AnnotatedField) Parse ¶
func (field *AnnotatedField) Parse(name string, argsCount int, extOptions map[string]string) (entities FieldEntities)
Parse analysis annotated fields annotations matched with name and args count. and convert into args and options.
type DeclEntities ¶
type DeclEntities []DeclEntity
func (DeclEntities) GroupBy ¶
func (entities DeclEntities) GroupBy(fn func(entity DeclEntity) string) (m map[string]DeclEntities)
GroupBy groups entities into string map by function return a string from entity
func (DeclEntities) GroupByDir ¶
func (entities DeclEntities) GroupByDir() (m map[string]DeclEntities)
GroupByDir groups entities into string map by declaration file dir
type DeclEntity ¶
type DeclEntity struct { *AnnotatedDecl Plugin string Args []string Options Options }
DeclEntity represents annotated ast.Decl with parsed args and options
func (*DeclEntity) ParseFields ¶
func (entity *DeclEntity) ParseFields(argsCount int, options map[string]string) (fields FieldEntities)
ParseFields parses decl fields annotation and returns FieldEntities
type ErrGroup ¶
type ErrGroup struct {
// contains filtered or unexported fields
}
ErrGroup is a simple version of golang.org/x/sync/errgroup.Group
type FieldEntities ¶
type FieldEntities []FieldEntity
type FieldEntity ¶
type FieldEntity struct { *AnnotatedField Args []string Options Options }
FieldEntity represents annotated ast.Field with parsed args and options
type File ¶
type File struct { Path string Data []byte Ast *ast.File // contains filtered or unexported fields }
File store parsed *ast.File and data bytes
func LookupTypSpec ¶
LookupTypSpec lookup typename in package src path.
func ParseFile ¶
ParseFile try read file data and parse ast file. return values would be cached by version key
type Imports ¶
Imports represents a key-value store with import path as key and import name as value it helps to deduplicated import path and rotate import name if duplicated
func LoadImports ¶
LoadImports parse *ast.File import spec list as Imports map
type KeySet ¶
type KeySet map[string]struct{}
KeySet provide a unique key set to deduplicated and sort keys
type ModifySet ¶
type ModifySet struct {
// contains filtered or unexported fields
}
ModifySet store inited *Modify with filename as key
type Options ¶
Options carries parsed key-value options from annotations
type OrmFieldMapper ¶
type OrmFieldMapper interface {
FieldMapping(map[string]interface{})
}
OrmFieldMapper assign mapping of orm struct field and column name keys represents column names values represents pointers to struct field
type OrmSchemaDriver ¶
type OrmSchemaDriver interface { // Name represents driver's unique name to register Name() string // Dsn format database localhost install default dns with provided password Dsn(password string) (dsn string) // Parse load database schema from dns then parse schema into []OrmTable for generation Parse(dsn, schema, table string, types map[string]string, options Options) (tables []OrmTable, err error) }
OrmSchemaDriver represents interface to register as driver.
func GetOrmSchemaDriver ¶
func GetOrmSchemaDriver(name string) OrmSchemaDriver
GetOrmSchemaDriver get OrmSchemaDriver from ormSchemaDriverRegistry by name
type Plugin ¶
type Plugin interface { // Name represents plugin's unique name to register and annotations prefix Name() string // Args represents arguments and options of plugin to uses. // plugin should implement Args to provide args and options description. // these infos would be showed in command "list" // // additionally args count effects annotations parsing and options offsets from name prefix // use ":" to split args name with description like "arg_name:arg_help" // // options provides optional control for plugins // plugin can return extra key-value options to describe name-help. Args() (args []string, options map[string]string) // Description represents summary of plugin . // these infos would be showed in command "list" Description() string // Run is entry of plugin make use of parsed entities from command "run". // plugin can use entities parsed from provided name prefix to do awesome things Run(entities DeclEntities) (err error) }
Plugin represents interface to register as plugin and handles entities builtin Plugin would automate registered on process init. also here supports load external plugin extension from ".so" plugin. external plugin should provide symbol named "Z" and implements Plugin interface
type PluginEntities ¶
type PluginEntities []PluginEntity
func (PluginEntities) Run ¶
func (entities PluginEntities) Run(filename string) (err error)
type PluginEntity ¶
PluginEntity represents Plugin instance and extra options from execute command
type VersionStore ¶
type VersionStore struct {
// contains filtered or unexported fields
}
VersionStore provide a store with source load like single-flights and versioned cache store
func (*VersionStore) Load ¶
func (s *VersionStore) Load(key interface{}, version string, fn func() (interface{}, error)) (r interface{}, err error)
func (*VersionStore) Update ¶
func (s *VersionStore) Update(key, version string, v interface{})