zcore

package module
v0.0.0-...-0fa2eba Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2023 License: Apache-2.0 Imports: 25 Imported by: 2

README

logo

Go Go Report Card Go Reference

Last Commit codecov

Documentation

English | 简体中文

Introduction

gozz-core provides core packages separated from gozz. contains core typing and code-generate utils for better independent plugin package referenced.

Why they independent

In Golang plugin, module with same name loaded should be compiled in same version.

So we have great reason to reduce core dependencies of gozz in go.mod then provide greater independence.

License

Apache-2.0

Documentation

Index

Constants

View Source
const (
	AnnotationSeparator       = ":"
	EscapeAnnotationSeparator = `\u003A`
	KeyValueSeparator         = "="
)
View Source
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

View Source
const (
	ExecSuffix       = "zz"
	ExecName         = "go" + ExecSuffix
	AnnotationIdent  = "+"
	AnnotationPrefix = AnnotationIdent + ExecSuffix + ":"
)

Variables

View Source
var BuffPool = sync.Pool{New: func() interface{} { return new(bytes.Buffer) }}
View Source
var Logger = log.New(os.Stderr, "[GOZZ] ", 0)
View Source
var (
	// SkipDirs contains some directory name would skip in walk
	SkipDirs = map[string]struct{}{
		"vendor":       {},
		"node_modules": {},
		"testdata":     {},
	}
)
View Source
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 Appendf

func Appendf(ss *[]string, format string, v ...interface{})

Appendf format string and values by fmt.Fprintf and append into strings slice

func AssertFuncType

func AssertFuncType(field *ast.Field) (name string, ft *ast.FuncType, ok bool)

AssertFuncType to assert interface fields as function type and try return name

func Bytesf

func Bytesf(format string, v ...interface{}) []byte

Bytesf format string and values by fmt.Fprintf and return byte slice

func CommentLines

func CommentLines(comment string) string

func EscapeAnnotation

func EscapeAnnotation(str string) string

func ExecCommand

func ExecCommand(command, dir string) (output string, err error)

ExecCommand execute command in provide directory and get stdout,stderr as string,error

func ExecuteTemplate

func ExecuteTemplate(data interface{}, text string, writer io.Writer) (err error)

ExecuteTemplate parse provide text template and execute template data into writer

func ExtractAnonymousName

func ExtractAnonymousName(spec ast.Expr) (name *ast.Ident)

func ExtractStructFieldsNames

func ExtractStructFieldsNames(typ *ast.StructType) (names []string)

ExtractStructFieldsNames extracts struct exported fields names

func FixPackage

func FixPackage(name, srcImportPath, dstImportPath string, srcImports, dstImports Imports) string

FixPackage modify or add selector package to provide name according to src and dst import module info

func GetImportName

func GetImportName(filename string) string

GetImportName get filename or directory module import name if file is not exist then return a relative calculated result from module environments

func GetImportPath

func GetImportPath(filename string) string

GetImportName get filename or directory module import path if file is not exist then return a relative calculated result from module environments

func GetModFile

func GetModFile(dir string) string

GetModFile get directory direct mod file by execute "go env GOMOD"

func GetOrWriteDefault

func GetOrWriteDefault(filename string, defaultData []byte) ([]byte, error)

GetOrWriteDefault try read filename or write default data

func GetPackageImportDir

func GetPackageImportDir(pkg, dir string) (output string)

func GetPackageImportName

func GetPackageImportName(pkg, dir string) (output string)

func IsGoFile

func IsGoFile(path string) bool

IsGoFile check path is valid golang file and ignore test file

func IsStandardImportPath

func IsStandardImportPath(path string) bool

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 JoinDocs

func JoinDocs(docs []string) string

func KebabCase

func KebabCase(s string) string

KebabCase converts a string into kebab case.

func LoadExtension

func LoadExtension(filename string) (name string, err error)

LoadExtension load filename and lookup symbol named "Z" symbol object should implement Plugin or OrmSchemaDriver

func LowerCamelCase

func LowerCamelCase(s string) string

LowerCamelCase converts a string into camel case starting with a lower case letter.

func OrmTypeMapping

func OrmTypeMapping() map[string]string

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 PluginRegistry() map[string]Plugin

func ReadFile

func ReadFile(filename string) (data []byte, version string, err error)

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 RenderWithDefaultTemplate

func RenderWithDefaultTemplate(plugin Plugin, templateText, filename, pkg string, editable bool, ext ...string) (err error)

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

func ScanSqlRows(rows *sql.Rows, fields []string, iterator Iterator) (err error)

ScanSqlRows scan iterator slice and scan sql.Rows values into iterated OrmFieldMapper elements

func SnakeCase

func SnakeCase(s string) string

SnakeCase converts a string into snake case.

func SplitKV

func SplitKV(str string, sep string) (key, value string)

SplitKV2Map split string into in key-value pairs by separator

func SplitKV2Map

func SplitKV2Map(str string, sep string, dst map[string]string)

SplitKV2Map split string into in key-value pairs by separator and set key-value into dst map

func SplitKVSlice2Map

func SplitKVSlice2Map(ss []string, sep string, dst map[string]string)

SplitKVSlice2Map split strings into in key-value pairs by separator and set key-value into dst map

func TrimPrefix

func TrimPrefix(str, prefix string) (string, bool)

TrimPrefix check strings has prefix and return trimmed string and check result

func TryExecuteTemplate

func TryExecuteTemplate(data interface{}, text string, dst *string)

TryExecuteTemplate try execute template, if success replace value to string pointer

func UnescapeAnnotation

func UnescapeAnnotation(str string) string

func UnsafeBytes2String

func UnsafeBytes2String(b []byte) string

func UnsafeString2Bytes

func UnsafeString2Bytes(s string) []byte

func UpperCamelCase

func UpperCamelCase(s string) string

UpperCamelCase converts a string into camel case starting with a upper case letter.

func UpperKebabCase

func UpperKebabCase(s string) string

UpperKebabCase converts a string into kebab case with capital letters.

func UpperSnakeCase

func UpperSnakeCase(s string) string

UpperSnakeCase converts a string into snake case with capital letters.

func WalkDir

func WalkDir(dir string, fn func(filename string) error) (err error)

WalkDir walks directory provide but does not walk subdirectory

func WalkPackage

func WalkPackage(dir string, fn func(file *File) (err error)) (files map[string]*File, err error)

WalkPackage walk package directory and parse file as *File. return *File map with filename

func WriteFile

func WriteFile(filename string, data []byte, perm fs.FileMode) (updated bool, err error)

WriteFile checks data and exists filename md5 sum and update data if file not exists or md5 sum not matched

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

func (*ErrGroup) Go

func (g *ErrGroup) Go(f func() error)

func (*ErrGroup) Wait

func (g *ErrGroup) Wait() error

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

func LookupTypSpec(name, dir, pkgPath string) (expr ast.Expr, srcFile *File)

LookupTypSpec lookup typename in package src path.

func ParseFile

func ParseFile(filename string) (file *File, err error)

ParseFile try read file data and parse ast file. return values would be cached by version key

func (*File) Imports

func (f *File) Imports() Imports

Imports dumps file ast imports list and return Imports map

func (*File) Lookup

func (f *File) Lookup(name string) *ast.Object

Lookup is a shortcut of ast scope lookup

func (*File) Node

func (f *File) Node(node ast.Node) []byte

Node return data bytes of ast.Node

func (*File) ReplacePackages

func (f *File) ReplacePackages(node ast.Node, dstFilename string, dstImports Imports) (data []byte)

ReplacePackages try replaces type package selector to provide node according to dst filename return modified node data bytes

type Import

type Import struct {
	Name string
	Path string
}

Import contains import name and import path this struct is used to render templates

type Imports

type Imports map[string]string

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

func LoadImports(f *ast.File, dir string) (imps Imports)

LoadImports parse *ast.File import spec list as Imports map

func (Imports) Add

func (imps Imports) Add(p string) (name string)

Add check import path exist or adds into imports and return imports name

func (Imports) List

func (imps Imports) List() []Import

List convert Imports map into sorted Import slice

func (Imports) Which

func (imps Imports) Which(name string) (path string)

Which check import name exist and return import path

type Iterator

type Iterator interface {
	Iterate(f func(element interface{}, alloc bool) (next bool))
}

Iterator provide range method for slice elements range and alloc

type KeySet

type KeySet map[string]struct{}

KeySet provide a unique key set to deduplicated and sort keys

func (KeySet) Add

func (set KeySet) Add(keys []string)

Add to append multi keys in set

func (KeySet) Keys

func (set KeySet) Keys() []string

Keys return all keys sorted in set

type Modify

type Modify struct {
	Filename string
	Imports  Imports
	Nodes    map[ast.Node][]byte
	Appends  [][]byte
}

Modify store changes of target filename golang ast modify

func (*Modify) Apply

func (m *Modify) Apply() (err error)

Apply to updates all modify changes and write data to target filename

type ModifySet

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

ModifySet store inited *Modify with filename as key

func (*ModifySet) Add

func (set *ModifySet) Add(filename string) *Modify

Add try adds filename and alloc *Modify object into ModifySet

func (*ModifySet) Apply

func (set *ModifySet) Apply() (err error)

Apply handles all filenames in ModifySet and apply all Modify

type Options

type Options map[string]string

Options carries parsed key-value options from annotations

func (Options) Exist

func (opt Options) Exist(key string) bool

Exist checks key in Options map. if exist and not empty then return strconv.ParseBool result

func (Options) Get

func (opt Options) Get(key string, def string) string

Get option value by key from Options map. if empty return default value from def

type OrmColumn

type OrmColumn struct {
	Name          string
	Type          string
	Column        string
	Comment       string
	Nullable      bool
	MaximumLength int64
	Ext           interface{}
}

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 OrmTable

type OrmTable struct {
	Name    string
	Table   string
	Schema  string
	Comment string
	Primary string
	Columns []OrmColumn
	Ext     interface{}
}

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

type PluginEntity struct {
	Plugin
	Options map[string]string
}

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{})

Jump to

Keyboard shortcuts

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