Documentation
¶
Overview ¶
Package genstruct provides tooling for generating static Go code from struct data.
The generator takes data in the form of struct slices and generates type-safe constants, variables, and slices for use in Go code. It supports referencing between different struct types using the structgen tag.
Basic usage:
generator := genstruct.NewGenerator( genstruct.WithPackageName("zoo"), genstruct.WithOutputFile("animals.go"), ) err := generator.Generate(animals)
For struct references:
generator := genstruct.NewGenerator( genstruct.WithPackageName("blog"), genstruct.WithOutputFile("blog.go"), ) err := generator.Generate(posts, tags)
Index ¶
- Constants
- func GetLogger() *slog.Logger
- func GetPackageNameFromPath(filePath string) string
- func InitLogger() *slog.Logger
- func WithLevel(level slog.Level) *slog.Logger
- type EmptyError
- type Generator
- type InvalidTypeError
- type NonSliceOrArrayError
- type Option
- func WithConstantIdent(name string) Option
- func WithCustomVarNameFn(fn func(structValue reflect.Value) string) Option
- func WithIdentifierFields(fields []string) Option
- func WithLogger(logger *slog.Logger) Option
- func WithOutputFile(path string) Option
- func WithPackageName(name string) Option
- func WithTypeName(name string) Option
- func WithVarPrefix(name string) Option
Constants ¶
const ( LevelDebug = "debug" LevelInfo = "info" LevelWarn = "warn" LevelError = "error" )
Verbosity levels
Variables ¶
This section is empty.
Functions ¶
func GetLogger ¶ added in v0.0.5
GetLogger returns the default logger or initializes a new one if it doesn't exist
func GetPackageNameFromPath ¶ added in v0.1.4
GetPackageNameFromPath extracts the containing folder name from a file path This can be used to determine the package name for a given Go file Example: "./out/penguin/gen.go" would return "penguin"
func InitLogger ¶ added in v0.0.5
InitLogger initializes the logger with command line flags
Types ¶
type Generator ¶
type Generator struct { // Primary configuration options PackageName string TypeName string ConstantIdent string VarPrefix string OutputFile string IdentifierFields []string CustomVarNameFn func(structValue reflect.Value) string Logger *slog.Logger // Internal state Data any // The primary array of structs to generate code for Refs map[string]any // Additional arrays that can be referenced File *jen.File }
Generator is responsible for generating code for static struct arrays
func NewGenerator ¶
NewGenerator creates a new generator instance with the specified options.
Example usage:
generator := genstruct.NewGenerator( genstruct.WithPackageName("mypackage"), genstruct.WithOutputFile("output_file.go"), ) // Generate code for posts with tags references err := generator.Generate(posts, tags)
Configuration is handled through functional options, and many values are automatically inferred if not specified:
- TypeName: Inferred from the struct type in the data provided to Generate()
- ConstantIdent: Defaults to TypeName if not specified
- VarPrefix: Defaults to TypeName if not specified
- OutputFile: Defaults to lowercase(typename_generated.go) if not specified
- IdentifierFields: Uses default fields if not specified
- Logger: Uses the default logger if not specified
Export mode (referencing types from other packages) is automatically determined based on the output file path. If the path contains directory separators, it will use qualified imports when referencing types from other packages.
func (*Generator) Generate ¶
Generate performs the code generation for both primary data and reference data.
Parameters:
- data: The primary array of structs to generate code for (can be slice, array, or pointer to slice/array)
- refs: Optional additional arrays that can be referenced by the primary data
The refs parameters enable struct references via the `structgen` tag. For example, a Post struct with a TagSlugs field can reference Tag structs:
type Post struct { ID string TagSlugs []string // Contains identifiers Tags []*Tag `structgen:"TagSlugs"` // Will be populated automatically }
Reference fields can be either direct structs or pointers to structs:
- []Tag `structgen:"TagSlugs"` - Direct struct references
- []*Tag `structgen:"TagSlugs"` - Pointer-based struct references (recommended)
This method generates: 1. Constants for the primary data's IDs 2. Variables for each item in the primary data 3. A slice containing all primary data items 4. Constants for each reference data set's IDs 5. Variables for each item in each reference data set 6. A slice for each reference data set 7. Creates references between primary data and reference data as specified by structgen tags
All generated code is written to a single output file specified in the OutputFile field.
Returns an error if:
- The data is not a slice, array, or pointer to slice/array
- The data is empty (no elements to analyze)
- The data elements are not structs
- Required fields couldn't be inferred
type InvalidTypeError ¶
InvalidTypeError is returned when the type of the data is not a struct.
func (InvalidTypeError) Error ¶
func (e InvalidTypeError) Error() string
Error returns the error message
type NonSliceOrArrayError ¶
NonSliceOrArrayError is returned when the data is not a slice or array.
func (NonSliceOrArrayError) Error ¶
func (e NonSliceOrArrayError) Error() string
Error returns the error message
type Option ¶ added in v0.1.4
type Option func(g *Generator)
Option is a functional option for customizing the generator.
func WithConstantIdent ¶ added in v0.1.4
WithConstantIdent sets the prefix for generated constants. For example, with prefix "Animal", constants will be named "AnimalLionID", etc. If not specified, defaults to the TypeName.
func WithCustomVarNameFn ¶ added in v0.1.4
WithCustomVarNameFn sets a custom function to control variable naming. This takes precedence over IdentifierFields if provided. The function receives a reflect.Value of the struct and should return a string to be used as the base name for the variable.
func WithIdentifierFields ¶ added in v0.1.4
WithIdentifierFields sets the fields to use for variable naming. These fields are checked in order until a non-empty string field is found. If not specified, defaults to ["ID", "Name", "Slug", "Title", "Key", "Code"].
func WithLogger ¶ added in v0.1.4
WithLogger sets a custom slog.Logger instance for logging during generation. If not specified, the default logger is used.
func WithOutputFile ¶ added in v0.1.4
WithOutputFile sets the output file path for the generated code. The path can include directories. Export mode is automatically determined based on this path - if it contains directory separators, qualified imports will be used for external types. If not specified, defaults to lowercase(typename_generated.go).
func WithPackageName ¶ added in v0.1.4
WithPackageName sets the package name for the generated code. If not specified, the package name is inferred from the output file directory.
func WithTypeName ¶ added in v0.1.4
WithTypeName sets the type name for the generated code. If not specified, the type name is inferred from the data struct type.
func WithVarPrefix ¶ added in v0.1.4
WithVarPrefix sets the prefix for generated variables. For example, with prefix "Animal", variables will be named "AnimalLion", etc. If not specified, defaults to the TypeName.
Source Files
¶
Directories
¶
Path | Synopsis |
---|---|
examples
|
|
exported-blog-network
Package main demonstrates how to export complex embedded structs.
|
Package main demonstrates how to export complex embedded structs. |
exported-blog-posts-tags
Package main demonstrates how to export blog post data with tag references.
|
Package main demonstrates how to export blog post data with tag references. |
exported-data-zoo
Package main shows how to export data from a package.
|
Package main shows how to export data from a package. |
logging-circus-show
Package main shows how to use the generator with a custom logger.
|
Package main shows how to use the generator with a custom logger. |