optgen

package module
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 25 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-optgen

go install github.com/altessa-s/go-optgen/cmd/optgen@latest

optgen is a code generator for the functional option pattern. It scans Go structs for fields annotated with opt/optgen/optval/optcheck/optfn tags and generates type-safe WithXxx option functions, default constructors, and validation code with an extensible plugin system.

Tag format

Tag Purpose
opt Option name for the WithXxx function; use - to skip generation. Omit it to derive the name from the field (see Option naming)
optgen Generator directives: default=..., append, set, put, enables=field, `resets=a
optval Value modifiers: trimspaces, lower, upper, trimprefix=..., trimsuffix=..., dedup, clone[=eager], nonempty, positive; invert / param for bool fields. trimspaces applies to string fields by default; notrim disables it
optcheck Validation rules: required, nonzero, min=N, minlen=N, maxlen=N, oneof=[a,b,c]
optfn Setter targets as OptionName=Function or OptionName=.Method; target signatures supply parameters

Function-backed setters

Use optfn when an option should construct or transform the field value through an existing function or method. Each Name=Target entry generates a separate option; method targets begin with a dot and are called on the current field value. Generic functions must be explicitly instantiated, and targets returning (T, error) require --option-error.

type options struct {
	allowed fieldpolicy.AllowList `optfn:"Allowed=fieldpolicy.NewAllowList"`
	mapping fieldpolicy.Mapping   `optfn:"Exact=.WithExact, Prefix=.WithPrefixes"`
}

Target parameter types and variadic behavior come from Go type information. optfn fields cannot use opt:"-", optval, or optcheck.

oneof treats unquoted values on string fields as string literals. For other comparable fields, unquoted values must be Go identifiers or qualified constants. min accepts numeric fields and time.Duration; a field with optcheck:"min=..." does not receive the default positive modifier. optgen:"onfail=skip" makes a failed check a no-op in the option function, including when options return errors.

optgen:"enables=flagField" sets a bool field after the option assignment. optgen:"resets=a|b" resets listed fields after assignment. Guards that return early skip these updates.

Collection tags optval:"clone", optgen:"set", and optgen:"put" require slice and map types written directly on the field ([]T or map[K]V). Named slice and map types are not supported by these tags.

Documentation

Generated options use a field's complete godoc when it starts with the final generated function name and a space. For example, WithTimeout controls... documents WithTimeout directly; WithoutValidation disables... works for an inverted bool option. This works with every field plugin.

For fields that produce multiple options, including multi-target optfn, use //optgen:doc <Option> <text> lines in the field comment. Each option's directive lines are joined in order and form the complete function doc. The first line must start with the final function name and a space. A directive without text adds an empty doc line, and a tab at the start of the text is preserved for godoc code examples.

type options struct {
	//optgen:doc Exact WithExact sets the exact field mapping.
	//optgen:doc Prefix WithPrefix sets the prefix field mapping.
	mapping Mapping `optfn:"Exact=.WithExact, Prefix=.WithPrefix"`
}

The directive option name matches the field's unprefixed option name. Its function name may use that name or the final name after --option-prefix; semantic preparation applies the option prefix when needed. The function prefix comes from --func-prefix; inverted bool options use --invert-func-prefix.

Option naming

For fields selected by --all-fields, all-fields: true, or an optgen/optval/optcheck/optfn tag, an omitted opt tag derives the option name from the field name, with every word that is a known initialism upper-cased — Go style requires an initialism to keep a consistent case throughout an identifier:

Field Generated
ttl WithTTL
httpClient WithHTTPClient
entityId WithEntityIDExtractor*
maxIdleTime WithMaxIdleTime
grpcOptions WithGrpcOptions

* for a field named entityIdExtractor.

The table is golint's commonInitialisms plus DB. gRPC is deliberately absent: the repo spells it Grpc throughout (grpcconfig.Config, DefaultGrpc), and a lone WithGRPCOptions would be less consistent, not more. To override a spelling the table gets wrong, name the option explicitly — the opt tag always wins:

type options struct {
    ttl time.Duration                // -> WithTTL
    uid string        `opt:"Uid"`    // -> WithUid
}

CLI commands

Command Description
generate Parse the struct and generate option functions into *_gen.go
list-plugins List registered field plugins, type-default providers, transform plugins, modifier plugins, and check plugins with their keys and aliases

The root command prints version information with --version.

Configuration

Settings are loaded from .optgen.yaml, searched from --directory (default .) up to the project root. Explicit CLI flags override corresponding config values. Per-package overrides use the packages map keyed by relative path; package-specific disable-plugins overrides global defaults.

Library API

import optgen "github.com/altessa-s/go-optgen"

The root package implements the CLI; cmd/optgen is a thin main around optgen.Run.

Entry points
Function Description
New Returns a *cobra.Command tree with the generate and list-plugins subcommands (--version flag on the root)
Run Sets the given args, executes the root command, and returns any error
NewGenerate Returns the generate subcommand for embedding in custom CLI trees
NewListPlugins Returns the list-plugins subcommand for embedding in custom CLI trees
Options
Option Purpose
WithPlugins Registers additional plugins in every command execution, after the built-in plugins
Custom plugins

Plugins are compiled into a program that wraps the CLI; there is no runtime plugin loading (complete example: examples/customplugin):

// tools/optgen/main.go
func main() {
	if err := optgen.Run(os.Args[1:], optgen.WithPlugins(myplugins.Register)); err != nil {
		os.Exit(1)
	}
}
//go:generate go run ./tools/optgen generate
Configuration

Configuration is loaded from .optgen.yaml (see config.File) unless --no-config is set. Explicit CLI flags override corresponding config values.

Each execution assembles its own registry: the built-in plugins, the configured type-defaults, the plugins of WithPlugins, then --disable-plugins, which fails on an unknown name. Verbose progress lists every field with its final option name, prefix included.

Subpackages

Package Description
cmd/optgen optgen binary: a main around optgen.Run; CLI flag reference
config Loads and merges .optgen.yaml configuration with per-package overrides
model Public data structures (OptField, GenericInfo) shared across layers
plugin Public extension API: FieldPlugin, TransformPlugin, Registry
internal/application Generation use case coordinating source, preparation, rendering, output
internal/parser Syntax extraction of struct fields, tags, and imports
internal/semantic Validation of checks and application of catalog default policies
internal/generator Renders prepared option models through plugin contracts
internal/naming Derives option names from field names, with initialism handling
internal/source Filesystem AST source adapter
internal/output Atomic output publication and allowlisted code formatting
examples Runnable examples: strict validation, generics, several types, custom plugins

Architecture

SOLID and Clean Architecture are mandatory. See architecture for the layer boundaries, plugin contracts, and verification rules.

Documentation

Overview

Package optgen implements the optgen code generator CLI as a library: the optgen binary is a thin main around Run, and programs that register their own plugins call Run with WithPlugins.

The package exposes three entry points:

  • New returns a ready-to-execute cobra.Command tree (generate, list-plugins, and --version).
  • Run is a convenience wrapper that accepts arguments and executes the root command.
  • NewGenerate and NewListPlugins return individual subcommands.

Configuration is loaded from .optgen.yaml (see [config.File]) unless --no-config is set. CLI flags always take precedence over config-file values.

Usage

cmd := optgen.New()
err := cmd.ExecuteContext(ctx)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func New

func New(opts ...Option) *cobra.Command

New creates the CLI root command. Options such as WithPlugins apply to every subcommand.

func NewGenerate

func NewGenerate(opts ...Option) *cobra.Command

NewGenerate returns a cobra command that generates functional option functions from struct field tags. The returned command validates inputs in PersistentPreRunE (directory existence, identifier validity, config loading) before running generation.

func NewListPlugins

func NewListPlugins(opts ...Option) *cobra.Command

NewListPlugins returns a cobra command that prints all registered plugins, type default providers, modifier plugins, and optcheck keys. The builtin plugins are registered explicitly for each command execution.

func Run

func Run(args []string, opts ...Option) error

Run executes the CLI with panic recovery. A program that registers its own plugins wraps it in its main function:

func main() {
	if err := optgen.Run(os.Args[1:], optgen.WithPlugins(myplugins.Register)); err != nil {
		os.Exit(1)
	}
}

Types

type GenerateCommand

type GenerateCommand struct {
	*cobra.Command
	// contains filtered or unexported fields
}

GenerateCommand implements the "generate" subcommand.

It parses the target directory for Go source files, locates the struct type identified by --type, collects opt-tagged fields, runs the plugin pipeline, and writes the generated WithXxx functions to --output (default options_gen.go). Use --dry-run to preview output without writing files.

type Option

type Option func(o *options)

Option is a functional option for configuring options.

func WithPlugins

func WithPlugins(v ...func(*plugin.Registry) error) Option

WithPlugins sets the plugins option.

plugins register additional plugins into the registry of every command execution, after the built-in plugins and before --disable-plugins.

Directories

Path Synopsis
cmd
optgen command
Package main runs the optgen command-line application.
Package main runs the optgen command-line application.
Package config decodes and merges .optgen.yaml configuration documents.
Package config decodes and merges .optgen.yaml configuration documents.
examples
cache
Package cache shows options for a generic struct and --with-isset.
Package cache shows options for a generic struct and --with-isset.
customplugin
Package customplugin shows generation with plugins of your own.
Package customplugin shows generation with plugins of your own.
customplugin/cmd/optgen command
Command optgen is the optgen CLI with the plugins of examples/customplugin/myplugins registered after the built-in ones.
Command optgen is the optgen CLI with the plugins of examples/customplugin/myplugins registered after the built-in ones.
customplugin/myplugins
Package myplugins implements two optgen plugins: the optval:"collapse" transform and the optcheck:"hostport" check.
Package myplugins implements two optgen plugins: the optval:"collapse" transform and the optcheck:"hostport" check.
pipeline
Package pipeline shows several option types generated in one run and a package-local .optgen.yaml.
Package pipeline shows several option types generated in one run and a package-local .optgen.yaml.
server
Package server shows the strict end of optgen: options that return errors, optcheck rules re-checked by the constructor, and the built-in field plugins.
Package server shows the strict end of optgen: options that return errors, optcheck rules re-checked by the constructor, and the built-in field plugins.
Package internal organizes the private implementation of optgen.
Package internal organizes the private implementation of optgen.
application
Package application coordinates generation through consumer-owned ports.
Package application coordinates generation through consumer-owned ports.
generator
Package generator renders prepared option declarations using injected plugins.
Package generator renders prepared option declarations using injected plugins.
naming
Package naming derives exported option names from private struct field names.
Package naming derives exported option names from private struct field names.
output
Package output formats generated source and publishes successful output atomically.
Package output formats generated source and publishes successful output atomically.
parser
Package parser extracts opt-tagged declarations without applying plugin policies.
Package parser extracts opt-tagged declarations without applying plugin policies.
plugin/builtin
Package builtin registers every built-in plugin: checks, type defaults, field plugins, guards, post-processors, and transforms.
Package builtin registers every built-in plugin: checks, type defaults, field plugins, guards, post-processors, and transforms.
plugin/builtin/check
Package check implements value-validation plugins.
Package check implements value-validation plugins.
plugin/builtin/defaults
Package defaults provides default expressions during semantic preparation.
Package defaults provides default expressions during semantic preparation.
plugin/builtin/fields
Package fields implements functional-option field renderers.
Package fields implements functional-option field renderers.
plugin/builtin/fieldtmpl
Package fieldtmpl provides templates and option data shared by the built-in field plugins.
Package fieldtmpl provides templates and option data shared by the built-in field plugins.
plugin/builtin/guard
Package guard implements conditional runtime guards.
Package guard implements conditional runtime guards.
plugin/builtin/postprocess
Package postprocess implements value cleanup after transformation.
Package postprocess implements value cleanup after transformation.
plugin/builtin/transform
Package transform implements string-expression transformations.
Package transform implements string-expression transformations.
rootcmd
Package rootcmd constructs CLI roots with generated options and panic recovery.
Package rootcmd constructs CLI roots with generated options and panic recovery.
semantic
Package semantic validates declarations and applies explicit plugin policies: the option name prefix, check applicability, type defaults and default normalization, and the default modifiers derived from plugin metadata.
Package semantic validates declarations and applies explicit plugin policies: the option name prefix, check applicability, type defaults and default normalization, and the default modifiers derived from plugin metadata.
source
Package source reads Go packages and extracts declarations.
Package source reads Go packages and extracts declarations.
Package model defines the public data structures shared between optgen's parser, generator, and plugin subsystems.
Package model defines the public data structures shared between optgen's parser, generator, and plugin subsystems.
Package plugin defines extension contracts and per-session plugin execution.
Package plugin defines extension contracts and per-session plugin execution.

Jump to

Keyboard shortcuts

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