Documentation
¶
Index ¶
- Constants
- Variables
- func FixImportDir(dest string) (string, error)
- func FixOutputLoc(file_name, suffix string) (string, error)
- func FixVariableName(variable_name string, keywords []string, exported GoExport) (string, error)
- func GetOutputLoc() (string, error)
- func GetPackages(packages []string) []string
- func GetStringFunctionCall(var_name string, type_name string, custom map[string][]string) (string, []string)
- func InitLogger(prefix string) *log.Logger
- func IsErrNotGeneric(target error) bool
- func IsGenericsID(id string) (rune, error)
- func IsValidName(variable_name string, keywords []string, exported GoExport) error
- func MakeAssignmentList() (map[string]string, error)
- func MakeParameterList() (string, error)
- func MakeTypeSig(type_name string, suffix string) (string, error)
- func ParseFlags() error
- func ParseGenerics(str string) ([]rune, error)
- func PrintFlags()
- func SetGenericsSignFlag(flag_name string, is_required bool, count int)
- func SetOutputFlag(def_value string, required bool)
- func SetStructFieldsFlag(flag_name string, is_required bool, count int, brief string)
- func SetTypeListFlag(flag_name string, is_required bool, count int, brief string)
- func ZeroValueOf(type_name string, custom map[string]string) string
- type CodeGenerator
- type DoFunc
- type ErrEmptyString
- type ErrInvalidID
- type ErrNotGeneric
- type Generater
- type GenericsSignVal
- type GoExport
- type StructFieldsVal
- type TypeListVal
Constants ¶
const ( // DebugMode is the debug mode. Default is true. DebugMode bool = true )
Variables ¶
var ( // ZeroValueTypes is a list of types that have a default value of zero. ZeroValueTypes []string // NillablePrefix is a list of prefixes that indicate a type is nillable. NillablePrefix []string )
var ( // OutputLocFlag is a flag that specifies the location of the output file. OutputLocFlag *string // IsOutputLocRequiredFlag is a flag that specifies whether the output location is required or not. IsOutputLocRequiredFlag bool // StructFieldsFlag is a pointer to the fields_flag flag. StructFieldsFlag *StructFieldsVal // GenericsSigFlag is a pointer to the generics_flag flag. GenericsSigFlag *GenericsSignVal // TypeListFlag is a pointer to the type_list_flag flag. TypeListFlag *TypeListVal )
var ( // GoReservedKeywords is a list of Go reserved keywords. GoReservedKeywords []string )
Functions ¶
func FixImportDir ¶
FixImportDir takes a destination string and manipulates it to get the correct import path.
Parameters:
- dest: The destination path.
Returns:
- string: The correct import path.
- error: An error if there is any.
func FixOutputLoc ¶
FixOutputLoc fixes the output location.
Parameters:
- file_name: The name of the file.
- suffix: The suffix of the file.
Returns:
- string: The output location.
- error: An error if any.
Errors:
- *common.ErrInvalidParameter: If the file name is empty.
- *common.ErrInvalidUsage: If the OutputLoc flag was not set.
- error: Any other error that may have occurred.
The suffix parameter must end with the ".go" extension. Plus, the output location is always lowercased.
NOTES: This function only sets the output location if the user did not set the output flag. If they did, this function won't do anything but the necessary checks and validations.
Example:
loc, err := FixOutputLoc("test", ".go")
if err != nil {
panic(err)
}
fmt.Println(loc) // test.go
func FixVariableName ¶
FixVariableName acts in the same way as IsValidName but fixes the variable name if it is invalid.
Parameters:
- variable_name: The variable name to check.
- keywords: The list of keywords to check against.
- exported: Whether the variable is exported or not.
Returns:
- string: The fixed variable name.
- error: An error if the variable name is invalid.
func GetOutputLoc ¶
GetOutputLoc gets the location of the output file.
Returns:
- string: The location of the output file.
- error: An error of type *common.ErrInvalidUsage if the output location was not defined prior to calling this function.
func GetPackages ¶ added in v0.1.2
GetPackages returns a list of packages from a list of strings.
Parameters:
- packages: The list of strings to get the packages from.
Returns:
- []string: The list of packages. Never returns nil.
func GetStringFunctionCall ¶ added in v0.1.2
func GetStringFunctionCall(var_name string, type_name string, custom map[string][]string) (string, []string)
GetStringFunctionCall returns the string function call for the given element. It is just a wrapper around the reflect.GetStringOf function.
Parameters:
- var_name: The name of the variable.
- type_name: The name of the type.
- custom: The custom strings to use. Empty values are ignored.
Returns:
- string: The string function call.
- []string: The dependencies of the string function call.
func InitLogger ¶
InitLogger initializes the logger with the given prefix.
Parameters:
- prefix: The prefix to use for the logger.
Returns:
- *log.Logger: The initialized logger. Never nil.
If the prefix is empty, it defaults to "go_generator".
func IsErrNotGeneric ¶
IsErrNotGeneric checks if an error is of type ErrNotGeneric.
Parameters:
- target: The error to check.
Returns:
- bool: True if the error is of type ErrNotGeneric, false otherwise.
func IsGenericsID ¶
IsGenericsID checks if the input string is a valid single upper case letter and returns it as a rune.
Parameters:
- id: The id to check.
Returns:
- rune: The valid single upper case letter.
- error: An error of type *ErrInvalidID if the input string is not a valid identifier.
func IsValidName ¶
IsValidName checks if the given variable name is valid.
This function checks if the variable name is not empty and if it is not a Go reserved keyword. It also checks if the variable name is not in the list of keywords.
Parameters:
- variable_name: The variable name to check.
- keywords: The list of keywords to check against.
- exported: Whether the variable is exported or not.
Returns:
- error: An error if the variable name is invalid.
If the variable is exported, the function checks if the variable name starts with an uppercase letter. If the variable is not exported, the function checks if the variable name starts with a lowercase letter. Any other case, the function does not perform any checks.
func MakeAssignmentList ¶
MakeAssignmentList makes a string representing a list of assignments.
WARNING: Call this function only if StructFieldsFlag is set.
Parameters:
- fields: A map of field names and their types.
Returns:
- string: A string representing the assignments.
- error: An error if any.
func MakeParameterList ¶
MakeParameterList makes a string representing a list of parameters.
WARNING: Call this function only if StructFieldsFlag is set.
Parameters:
- fields: A map of field names and their types.
Returns:
- string: A string representing the parameters.
- error: An error if any.
func MakeTypeSig ¶
MakeTypeSig creates a type signature from a type name and a suffix.
It also adds the generic signature if it exists.
Parameters:
- type_name: The name of the type.
- suffix: The suffix of the type.
Returns:
- string: The type signature.
- error: An error if the type signature cannot be created. (i.e., the type name is empty)
func ParseFlags ¶
func ParseFlags() error
ParseFlags parses the command line flags.
Returns:
- error: An error if any.
func ParseGenerics ¶
ParseGenerics parses a string representing a list of generic types enclosed in square brackets.
Parameters:
- str: The string to parse.
Returns:
- []rune: An array of runes representing the parsed generic types.
- error: An error if the parsing fails.
Errors:
- *ErrNotGeneric: The string is not a valid list of generic types.
- error: An error if the string is a possibly valid list of generic types but fails to parse.
func PrintFlags ¶ added in v0.1.2
func PrintFlags()
PrintFlags prints the default values of the flags.
It is useful for debugging and for error messages.
func SetGenericsSignFlag ¶
SetGenericsSignFlag sets the flag that specifies the generics to generate the code for.
Parameters:
- flag_name: The name of the flag.
- is_required: Whether the flag is required or not.
- count: The number of generics. If -1, no upper bound is set, 0 means no generics.
Documentation:
**Flag: Generics**
This optional flag is used to specify the type(s) of the generics. However, this only applies if at least one generic type is specified in the fields flag. If none, then this flag is ignored.
As an edge case, if this flag is not specified but the fields flag contains generics, then all generics are set to the default value of "any".
As with the fields flag, its argument is specified as a list of key-value pairs where each pair is separated by a comma (",") and a slash ("/") is used to separate the key and the value. The key indicates the name of the generic and the value indicates the type of the generic.
For instance, running the following command:
//go:generate treenode -type="TreeNode" -fields=a/MyType[T],b/MyType[C] -g=T/any,C/int
will generate a tree node with the following fields:
type TreeNode[T any, C int] struct {
// Node pointers.
a T
b C
}
func SetOutputFlag ¶
SetOutputFlag sets the flag that specifies the location of the output file.
Parameters:
- def_value: The default value of the output_flag flag.
- required: Whether the flag is required or not.
Here are all the possible valid calls to this function:
SetOutputFlag("", false) <-> SetOutputFlag("[no location]", false)
SetOutputFlag("path/to/file.go", false)
SetOutputFlag("", true) <-> SetOutputFlag("path/to/file.go", true)
However, the def_value parameter does not specify the actual default location of the output file. Instead, it is merely used in the "usage" portion of the flag specification in order to give the user more information about the location of the output file. Thus, if no output flag is set, the actual default location of the flag is an empty string.
Documentation:
**Flag: Output File**
This optional flag is used to specify the output file. If not specified, the output will be written to standard output, that is, the file "<type_name>_treenode.go" in the root of the current directory.
func SetStructFieldsFlag ¶
SetStructFieldsFlag sets the flag that specifies the fields of the struct to generate the code for.
Parameters:
- flag_name: The name of the flag.
- is_required: Whether the flag is required or not.
- count: The number of fields expected. -1 for unlimited number of fields.
- brief: A brief description of the flag.
Any negative number will be interpreted as unlimited number of fields. Also, the value 0 will not set the flag.
Documentation:
**Flag: Fields**
The "fields" flag is used to specify the fields that the tree node contains. Because it doesn't make a lot of sense to have a tree node without fields, this flag must be set.
Its argument is specified as a list of key-value pairs where each pair is separated by a comma (",") and a slash ("/") is used to separate the key and the value.
The key indicates the name of the field while the value indicates the type of the field.
For instance, running the following command:
//go:generate treenode -type="TreeNode" -fields=a/int,b/int,name/string
will generate a tree node with the following fields:
type TreeNode struct {
// Node pointers.
a int
b int
name string
}
It is important to note that spaces are not allowed.
Also, it is possible to specify generics by following the value with the generics between square brackets; like so: "a/MyType[T,C]"
func SetTypeListFlag ¶
SetTypeListFlag sets the flag that specifies the fields of the struct to generate the code for.
Parameters:
- flag_name: The name of the flag.
- is_required: Whether the flag is required or not.
- count: The number of fields expected. -1 for unlimited number of fields.
- brief: A brief description of the flag.
Any negative number will be interpreted as unlimited number of fields. Also, the value 0 will not set the flag.
Documentation:
**Flag: Types**
The "types" flag is used to specify a list of types that are accepted by the generator.
Its argument is specidied as a list of Go types separated by commas without spaces.
For instance, running the following command:
//go:generate table -name=IntTable -type=int -fields=a/int,b/int,name/string
will generate a tree node with the following fields:
type TreeNode struct {
// Node pointers.
a int
b int
name string
}
It is important to note that spaces are not allowed.
Also, it is possible to specify generics by following the value with the generics between square brackets; like so: "a/MyType[T,C]"
Types ¶
type CodeGenerator ¶ added in v0.1.2
type CodeGenerator[T Generater] struct { // contains filtered or unexported fields }
CodeGenerator is the code generator.
func NewCodeGenerator ¶ added in v0.1.2
func NewCodeGenerator[T Generater](templ *template.Template) (*CodeGenerator[T], error)
NewCodeGenerator creates a new code generator.
Parameters:
- templ: The template to use for the generated code.
Returns:
- *CodeGenerator: The code generator.
- error: An error of type *common.ErrInvalidParameter if the templ is nil.
func NewCodeGeneratorFromTemplate ¶ added in v0.1.2
func NewCodeGeneratorFromTemplate[T Generater](name, templ string) (*CodeGenerator[T], error)
NewCodeGeneratorFromTemplate creates a new code generator from a template. Panics if the template is not valid.
Parameters:
- name: The name of the template.
- templ: The template to use for the generated code.
Returns:
- *CodeGenerator: The code generator.
- error: An error of type *common.ErrInvalidParameter if the templ is invalid.
func (*CodeGenerator[T]) AddDoFunc ¶ added in v0.1.2
func (cg *CodeGenerator[T]) AddDoFunc(do_func DoFunc[T])
AddDoFunc adds a function to perform on the data before generating the code.
Parameters:
- do_func: The function to perform on the data before generating the code.
Does nothing if the do_func is nil.
func (*CodeGenerator[T]) Generate ¶ added in v0.1.2
func (cg *CodeGenerator[T]) Generate(file_name, suffix string, data T) (string, error)
Generate generates code using the given generator and writes it to the given destination file.
WARNING:
- Remember to call this function iff the function go_generator.SetOutputFlag() was called and only after the function flag.Parse() was called.
Parameters:
- file_name: The file name to use for the generated code.
- suffix: The suffix to use for the generated code. This should end with the ".go" extension.
- data: The data to use for the generated code.
Returns:
- string: The output location of the generated code.
- error: An error if occurred.
Errors:
- *common.ErrInvalidParameter: If the file_name or suffix is an empty string.
- error: Any other type of error that may have occurred.
type DoFunc ¶ added in v0.1.2
DoFunc is the type of the function to perform on the data before generating the code.
Parameters:
- T: The data to perform the function on.
Returns:
- error: An error if occurred.
type ErrEmptyString ¶
type ErrEmptyString struct{}
ErrEmptyString represents an error when a string is empty.
func NewErrEmptyString ¶
func NewErrEmptyString() *ErrEmptyString
NewErrEmptyString creates a new ErrEmptyString error.
Returns:
- *ErrEmptyString: The new error. Never returns nil.
func (*ErrEmptyString) Error ¶
func (e *ErrEmptyString) Error() string
Error implements the error interface.
Message: "value must not be an empty string"
type ErrInvalidID ¶
type ErrInvalidID struct {
// ID is the invalid identifier.
ID string
// Reason is the reason why the identifier is invalid.
Reason error
}
ErrInvalidID represents an error when an identifier is invalid.
func NewErrInvalidID ¶
func NewErrInvalidID(id string, reason error) *ErrInvalidID
NewErrInvalidID creates a new ErrInvalidID error.
Parameters:
- id: The invalid identifier.
- reason: The reason for the error.
Returns:
- *ErrInvalidID: The new error.
func (*ErrInvalidID) Error ¶
func (e *ErrInvalidID) Error() string
Error implements the error interface.
Message: "identifier <id> is invalid: <reason>"
type ErrNotGeneric ¶
type ErrNotGeneric struct {
// Reason is the reason for the error.
Reason error
}
ErrNotGeneric is an error type for when a type is not a generic.
func NewErrNotGeneric ¶
func NewErrNotGeneric(reason error) *ErrNotGeneric
NewErrNotGeneric creates a new ErrNotGeneric error.
Parameters:
- reason: The reason for the error.
Returns:
- *ErrNotGeneric: The new error.
func (*ErrNotGeneric) Error ¶
func (e *ErrNotGeneric) Error() string
Error implements the error interface.
Message: "not a generic type"
type Generater ¶
type Generater interface {
// SetPackageName sets the package name for the generated code.
//
// Parameters:
// - pkg_name: The package name to use for the generated code.
SetPackageName(pkg_name string)
}
Generater is the interface that all generators must implement.
type GenericsSignVal ¶
type GenericsSignVal struct {
// contains filtered or unexported fields
}
GenericsSignVal is a struct that contains the values of the generics.
func (*GenericsSignVal) GetSignature ¶
func (gv *GenericsSignVal) GetSignature() string
GetSignature returns the signature of the generics.
Format:
[T1, T2, T3]
Returns:
- string: The list of generics.
func (*GenericsSignVal) Set ¶
func (s *GenericsSignVal) Set(value string) error
Set implements the flag.Value interface.
func (*GenericsSignVal) String ¶
func (s *GenericsSignVal) String() string
String implements the flag.Value interface.
Format:
[letter1 type1, letter2 type2, ...]
type GoExport ¶
type GoExport int
GoExport is an enum that represents whether a variable is exported or not.
type StructFieldsVal ¶
type StructFieldsVal struct {
// contains filtered or unexported fields
}
StructFieldsVal is a struct that represents the fields value.
func (*StructFieldsVal) GetFields ¶
func (s *StructFieldsVal) GetFields() map[string]string
GetFields returns the fields of the struct.
Returns:
- map[string]string: A map of field names and their types. Never returns nil.
func (*StructFieldsVal) Set ¶
func (s *StructFieldsVal) Set(value string) error
Set implements the flag.Value interface.
func (*StructFieldsVal) String ¶
func (s *StructFieldsVal) String() string
String implements the flag.Value interface.
Format:
"<value1> <type1>, <value2> <type2>, ..."
type TypeListVal ¶
type TypeListVal struct {
// contains filtered or unexported fields
}
TypeListVal is a struct that represents a list of types.
func (*TypeListVal) GetType ¶
func (s *TypeListVal) GetType(idx int) (string, error)
GetType returns the type at the given index.
Parameters:
- idx: The index of the type to return.
Return:
- string: The type at the given index.
- error: An error of type *luc.ErrInvalidParameter if the index is out of bounds.
func (*TypeListVal) Set ¶
func (s *TypeListVal) Set(value string) error
Set implements the flag.Value interface.
func (*TypeListVal) String ¶
func (s *TypeListVal) String() string
String implements the flag.Value interface.
Format:
"<type1>, <type2>, ..."