generator

package
v0.1.11 Latest Latest
Warning

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

Go to latest
Published: Jul 22, 2026 License: Apache-2.0 Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const (
	KindRestAny = "rest_any" // map[string]any with payload:"*"
	KindRestRaw = "rest_raw" // map[string]json.RawMessage with payload:"*"
	KindStruct  = "struct"
	KindSlice   = "slice"
	KindMap     = "map"
)

Composite and special field kinds.

View Source
const DefaultTemplatesName = "tinybind_templates_gen.go"

Variables

View Source
var ErrFeatureDisabled = errors.New("generator: feature disabled")

ErrFeatureDisabled is returned when a disabled generator artifact is invoked directly.

Functions

func AnalyzeConfigBind added in v0.1.5

func AnalyzeConfigBind(dir string) (pkgName string, specs []cbcg.Spec, err error)

AnalyzeConfigBind discovers Bind[T](prefix) registrations and builds codegen specs.

func Emit

func Emit(plan *PackagePlan) ([]byte, error)

Emit generates Go source for type-specific binders, writers, and JSON codecs. The output does not import "reflect".

func EmitOpenAPI

func EmitOpenAPI(pkg string, doc Document) ([]byte, error)

EmitOpenAPI produces Go source for a package-named fragment. Prefer EmitOpenAPIFragment when the package import path is available.

func EmitOpenAPIFragment added in v0.1.11

func EmitOpenAPIFragment(pkg, packagePath string, doc Document) ([]byte, error)

EmitOpenAPIFragment produces Go source embedding and registering one package-local OpenAPI fragment.

func Generate

func Generate(dir, outDir, outName string) (string, error)

Generate analyzes dir and writes <outName> (default: tinybind_gen.go) into outDir (default: dir). Returns the absolute path of the written file.

func GenerateOpenAPI

func GenerateOpenAPI(dir, outDir, outName string) (string, error)

GenerateOpenAPI builds OpenAPI 3.1 from Go sources in dir and writes a generated file that embeds the document and registers it with httpbind for serving.

func Main

func Main(options Options)

Main owns the tinybind-gen command-line interface for custom generator binaries.

func Run

func Run(args []string, stdout, stderr io.Writer, options Options) int

Run executes the generator CLI and returns a process exit code.

func TemplateFiles added in v0.1.5

func TemplateFiles(dir string) ([]string, error)

TemplateFiles returns the .tb.html and .tb.sql files directly contained in dir. A generator invocation targets one Go package and therefore does not descend into child package directories.

Types

type CheckRules

type CheckRules struct {
	Required   bool
	Min        *float64
	Max        *float64
	MinLen     *int
	MaxLen     *int
	Len        *int
	Enum       []string
	Pattern    string
	Default    string
	HasDefault bool
	Email      bool
	UUID       bool
	Date       bool
	Time       bool
	DateTime   bool
}

CheckRules is the structured form of a field's check tag (codegen only).

func ParseCheckTag

func ParseCheckTag(raw, kind string) (CheckRules, error)

ParseCheckTag parses a check tag value for a field of the given Go kind. Invalid syntax, unknown rules, type mismatches, and invalid patterns fail here.

func (CheckRules) HasRules

func (c CheckRules) HasRules() bool

HasRules reports whether any check constraint or default is set.

func (CheckRules) HasValidation added in v0.1.6

func (c CheckRules) HasValidation() bool

HasValidation reports whether the rules can reject a bound value. A default alone changes an absent value but cannot produce a validation error.

func (CheckRules) NeedsPresence

func (c CheckRules) NeedsPresence() bool

NeedsPresence is true when codegen must track whether the field was present.

type ConfigBindBinding added in v0.1.5

type ConfigBindBinding struct {
	TypeName string
	Prefix   string
}

ConfigBindBinding is one discovered configbind.Bind[T](prefix) call.

type DiscoverySymbol

type DiscoverySymbol struct {
	PackagePath string
	Name        string
	Usage       Usage
}

DiscoverySymbol identifies a generic function and the entry point it needs. PackagePath is matched by go/types identity, so import aliases are supported.

type Document

type Document map[string]any

Document is an OpenAPI 3.1 document represented as ordered JSON-friendly maps. Keys under paths/operations/components are sorted for deterministic output.

func BuildOpenAPI

func BuildOpenAPI(dir string) (Document, error)

BuildOpenAPI analyzes dir with the route parser and field planner and returns an OpenAPI 3.1 document derived only from Go source (not from handwritten YAML).

func (Document) JSON

func (d Document) JSON() ([]byte, error)

JSON is an alias for MarshalJSON bytes for callers.

func (Document) MarshalJSON

func (d Document) MarshalJSON() ([]byte, error)

MarshalJSON returns deterministic indented OpenAPI JSON.

func (Document) YAML

func (d Document) YAML() ([]byte, error)

YAML returns a minimal YAML encoding of the document (deterministic key order).

type Feature

type Feature string

Feature identifies a generator capability that can be permanently disabled.

const (
	FeatureRouteDiscovery Feature = "route-discovery"
	FeatureOpenAPI        Feature = "openapi"
	FeatureBind           Feature = "bind"
	FeatureWrite          Feature = "write"
	FeatureWriteStatus    Feature = "write-status"
	FeatureDecodeJSON     Feature = "decode-json"
	FeatureEncodeJSON     Feature = "encode-json"
	FeatureStreaming      Feature = "streaming"
	FeatureScanRows       Feature = "scan-rows"
	FeatureMultipartFile  Feature = "multipart-file"
)

type FieldPlan

type FieldPlan struct {
	Name     string      // Go field name
	Wire     string      // wire / tag name ("*" for payload rest)
	Source   FieldSource // input|query|payload|path|header|cookie|method
	Kind     string      // string|int|int64|bool|float64|file|rest_*|struct|slice|map
	JSON     string      // json name for encode/document keys
	Check    CheckRules  // from check:"" tag; empty if absent
	TypeName string      // KindStruct name, or element struct name for slice/map of struct
	ElemKind string      // for slice/map: string|int|int64|bool|float64|struct
	DB       string      // SQL result column (db tag or snake_case field name)
	GroupKey bool        // groupkey tag presence
}

FieldPlan is one struct field mapping plan (compile-time).

func (FieldPlan) GoType

func (f FieldPlan) GoType() string

GoType returns a Go type string for generated code (e.g. NestedCustomer, []string).

func (FieldPlan) IsComposite

func (f FieldPlan) IsComposite() bool

IsComposite reports nested struct/slice/map kinds.

func (FieldPlan) IsRest

func (f FieldPlan) IsRest() bool

IsRest reports whether f is a payload rest map field.

type FieldSource

type FieldSource string

FieldSource is where a request field is read from.

const (
	SourceInput   FieldSource = "input"
	SourceQuery   FieldSource = "query"
	SourcePayload FieldSource = "payload"
	SourcePath    FieldSource = "path"
	SourceHeader  FieldSource = "header"
	SourceCookie  FieldSource = "cookie"
	SourceMethod  FieldSource = "method"
)

type Generator

type Generator struct{ Options Options }

Generator is a reusable, configurable code generator.

func New

func New(opts Options) *Generator

New constructs a usage-directed generator. Set GenerateAll for legacy output.

func (*Generator) Analyze

func (g *Generator) Analyze(dir string) (*PackagePlan, error)

Analyze analyzes a package using this generator's discovery symbols.

func (*Generator) BuildOpenAPI

func (g *Generator) BuildOpenAPI(dir string) (Document, error)

BuildOpenAPI builds a document using this generator's discovery identities.

func (*Generator) Generate

func (g *Generator) Generate(dir, outDir, outName string) (string, error)

Generate analyzes dir and writes generated source.

func (*Generator) GenerateConfigBind added in v0.1.5

func (g *Generator) GenerateConfigBind(dir, outDir, outName string) (string, error)

GenerateConfigBind analyzes dir for configbind.Bind usage and writes configbind_gen.go. Returns the absolute path written, or "" if no Bind calls found.

func (*Generator) GenerateOpenAPI

func (g *Generator) GenerateOpenAPI(dir, outDir, outName string) (string, error)

GenerateOpenAPI writes OpenAPI generated with this generator's identities.

func (*Generator) GenerateTemplates added in v0.1.5

func (g *Generator) GenerateTemplates(dir, outDir, outName string) (string, error)

GenerateTemplates discovers the standard template extensions and writes one Go file containing all generated declarations. It returns an empty path when no templates exist.

type MethodPattern

type MethodPattern struct {
	PackagePath         string
	Name                string
	ReceiverPackagePath string
	ReceiverType        string
}

MethodPattern identifies a method and its receiver type.

type Options

type Options struct {
	ServeMuxes      PatternSet[TypePattern]
	RouteMethods    PatternSet[MethodPattern]
	RouteFunctions  PatternSet[SymbolPattern]
	RuntimePackages PatternSet[string]

	Bind        PatternSet[SymbolPattern]
	Write       PatternSet[SymbolPattern]
	WriteStatus PatternSet[SymbolPattern]
	DecodeJSON  PatternSet[SymbolPattern]
	EncodeJSON  PatternSet[SymbolPattern]
	NewStream   PatternSet[SymbolPattern]
	ScanRows    PatternSet[SymbolPattern]
	FileTypes   PatternSet[TypePattern]
	// SQLContextAPI adds Context-resolved wrappers for exported SQL templates.
	SQLContextAPI bool
	// SQLExecutorResolver selects a framework-specific Context resolver and
	// implies SQLContextAPI. Nil uses sqlbind.SQLExecutorFromContext.
	SQLExecutorResolver *SymbolPattern

	DisableFeatures []Feature
	GenerateAll     bool
}

Options configures discovery identities and generated template APIs. A zero Options value intentionally discovers nothing and disables optional wrappers; use DefaultOptions for standard behavior.

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns the standard tinybind runtime setup.

type PackagePlan

type PackagePlan struct {
	Package     string
	PackagePath string
	Types       []TypePlan
	// Discovered lists type names referenced by configured generic call sites.
	Discovered []string
}

PackagePlan is all type plans in a package.

func AnalyzePackage

func AnalyzePackage(dir string) (*PackagePlan, error)

AnalyzePackage builds field plans for all package-level structs with exported fields. Generic call discovery (Bind/Write/DecodeJSON/EncodeJSON) uses go/types symbol identity.

func AnalyzePackageWithOptions

func AnalyzePackageWithOptions(dir string, opts Options) (*PackagePlan, error)

AnalyzePackageWithOptions is AnalyzePackage with customizable call targets.

type PatternSet

type PatternSet[T any] struct {
	Set      []T
	Disabled bool
}

PatternSet is an authoritative set of discovery identities. Set replaces, rather than extends, any defaults. Disabled suppresses the feature entirely.

type SymbolPattern

type SymbolPattern struct{ PackagePath, Name string }

SymbolPattern identifies a package-level declaration by go/types identity.

type TypePattern

type TypePattern struct{ PackagePath, Name string }

TypePattern identifies a named type by go/types identity.

type TypePlan

type TypePlan struct {
	Name   string
	Fields []FieldPlan
	// Usage records which generated entry points are referenced by source code.
	// Zero means the type is unused and emits no mapping paths.
	Usage Usage
	// DirectUsage excludes usage inherited from containing structs.
	DirectUsage Usage
}

TypePlan is the mapping plan for one struct type.

type Usage

type Usage uint32

Usage selects generated mapping entry points.

const (
	UsageBind Usage = 1 << iota
	UsageWrite
	UsageDecodeJSON
	UsageEncodeJSON
	UsageScanRows
	UsageAll = UsageBind | UsageWrite | UsageDecodeJSON | UsageEncodeJSON
)

Jump to

Keyboard shortcuts

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