gen

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: May 8, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package gen implements testkit's code generators and validators. It provides the type analysis, template rendering, and validation logic that the cmd/testkit CLI wraps.

Index

Constants

View Source
const (
	// DefaultTestPackageSuffix is appended to the package name for test
	// packages. "test" produces store → storetest.
	DefaultTestPackageSuffix = "test"

	// DefaultGeneratedSuffix is the file extension suffix for generated files.
	DefaultGeneratedSuffix = ".gen.go"

	// TestPackageStyleExternal produces package foo_test (black-box).
	TestPackageStyleExternal = "external"

	// TestPackageStyleInternal produces package foo (white-box).
	TestPackageStyleInternal = "internal"

	// DefaultTestPackageStyle is the default test package naming convention.
	DefaultTestPackageStyle = TestPackageStyleExternal

	// DefaultStubFilePattern is the base name pattern for generated stub files.
	// "{type}" is replaced with the lowercased type name.
	DefaultStubFilePattern = "{type}_stub"

	// DefaultStubTypeSuffix is appended to the type name for generated stub types.
	DefaultStubTypeSuffix = "Stub"
)
View Source
const (
	// ErrFieldName is the default name for error return fields.
	ErrFieldName = "Err"
	// ResultFieldName is the default name for non-error return fields.
	ResultFieldName = "Result"
)
View Source
const (
	// TestFileSuffix is the Go convention for test file names.
	TestFileSuffix = "_test.go"
	// TestPkgSuffix is the Go convention for external test package names.
	TestPkgSuffix = "_test"
)

Variables

View Source
var EmptyPos token.Position

EmptyPos is the zero-value token.Position, used when an error has no specific source location.

Functions

func CamelCase

func CamelCase(s string) string

CamelCase converts a string to CamelCase, splitting on underscores, hyphens, and case boundaries. "hello_world" → "HelloWorld".

func DerivePackageName

func DerivePackageName(outputPath, sourcePkgName string, cfg Config, opts Options) string

DerivePackageName computes the Go package name for a generated file based on its output path, the source package name, and config.

Rules:

  • Output in source package dir → source package name.
  • Output in <pkg><suffix>/ dir → <pkg><suffix>.
  • Output ending in _test.go → source package name + "_test".
  • TestPackageStyle "internal" → always source package name.

func FormatDocComment

func FormatDocComment(doc string) string

FormatDocComment prefixes each line of doc with "// " so it can be pasted directly into generated Go source. Returns empty string for empty doc.

func FuncMap

func FuncMap() template.FuncMap

FuncMap returns the standard template function map available to all generator templates.

func HasContextParam

func HasContextParam(sig *types.Signature) bool

HasContextParam reports whether the signature has a context.Context parameter.

func HasUnexportedFields

func HasUnexportedFields(typ types.Type) bool

HasUnexportedFields reports whether the type (or its named underlying struct) contains unexported fields, which prevents cmp.Diff comparison.

func IsContextType

func IsContextType(typ types.Type) bool

IsContextType reports whether typ is context.Context.

func IsErrorType

func IsErrorType(typ types.Type) bool

IsErrorType reports whether typ is the built-in error interface.

func LowerCamelCase

func LowerCamelCase(s string) string

LowerCamelCase converts a string to lowerCamelCase. "hello_world" → "helloWorld".

func NewTemplateSet

func NewTemplateSet() *template.Template

NewTemplateSet returns a template.Template pre-loaded with the standard function map. Generator templates are parsed into this set to inherit the shared functions.

func NonCtxParamCount

func NonCtxParamCount(sig *types.Signature) int

NonCtxParamCount returns the number of non-context.Context parameters.

func OutputImportPath

func OutputImportPath(outputPath string, pkg *Package, opts Options) (string, error)

OutputImportPath computes the Go import path for a generated file given its output path relative to the source package and the source package's module and import path.

func ParamName

func ParamName(i int) string

ParamName generates a parameter name for index i: "p0", "p1", etc.

func QualifyType

func QualifyType(qualifier, typeName string) string

QualifyType prefixes typeName with qualifier if non-empty. QualifyType("store", "Item") → "store.Item". QualifyType("", "Item") → "Item".

func Render

func Render(tmplText string, data any, header Header) ([]byte, error)

Render executes tmplText with data, prepends the generated-file header, and formats with goimports. Returns formatted Go source.

func RenderTemplate

func RenderTemplate(tmpl *template.Template, name string, data any, header Header) ([]byte, error)

RenderTemplate executes a pre-parsed template by name (empty for the root template), prepends header, and formats with goimports.

func SampleBasicValue

func SampleBasicValue(b *types.Basic, fieldName string) string

SampleBasicValue returns a non-zero Go literal for a basic type.

func SampleValueOf

func SampleValueOf(typ types.Type, fieldName string, tracker *ImportTracker) string

SampleValueOf returns a non-zero Go literal for a type, suitable for use in generated test assertions. The value is deterministic and distinct from the zero value so tests can verify setters work.

func SnakeCase

func SnakeCase(s string) string

SnakeCase converts a string to snake_case. "HelloWorld" → "hello_world".

func SplitWords

func SplitWords(s string) []string

SplitWords splits a string into words on underscores, hyphens, and CamelCase boundaries.

func TestPathFrom

func TestPathFrom(implPath string) string

TestPathFrom derives the companion test file path from an impl path. "storetest/store.gen.go" → "storetest/store.gen_test.go".

func Title

func Title(s string) string

Title uppercases the first letter of s, with awareness of Go initialisms. "id" → "ID", "url" → "URL", "name" → "Name".

func TypeStr

func TypeStr(typ types.Type, tracker *ImportTracker) string

TypeStr renders a Go type as source code using the tracker's qualifier.

func WriteResult

func WriteResult(result *Result, workDir string, check bool) error

WriteResult writes all files in a Result to disk. Paths are resolved relative to workDir. Directories are created as needed.

When check is true, it compares each file against existing content and returns an error with unified diffs for any files that differ (dry-run mode for CI).

func ZeroCallArgs

func ZeroCallArgs(sig *types.Signature, tracker *ImportTracker) string

ZeroCallArgs renders comma-separated zero-value arguments for calling a method. Context params use t.Context(), variadic params are omitted, others use ZeroValueOf.

func ZeroCallArgsWithCtx

func ZeroCallArgsWithCtx(sig *types.Signature, tracker *ImportTracker, ctxExpr string) string

ZeroCallArgsWithCtx renders zero-value arguments for calling a method, using ctxExpr for context.Context parameters.

func ZeroValueOf

func ZeroValueOf(typ types.Type, t *ImportTracker) string

ZeroValueOf returns the Go zero-value literal for a type.

Types

type Config

type Config struct {
	// TestPackageSuffix is appended to package name for test packages.
	// Default: [DefaultTestPackageSuffix].
	TestPackageSuffix string

	// GeneratedSuffix is the file extension suffix for generated files.
	// Default: [DefaultGeneratedSuffix].
	GeneratedSuffix string

	// TestPackageStyle controls package naming for generated test files.
	// Use [TestPackageStyleExternal] or [TestPackageStyleInternal].
	// Default: [DefaultTestPackageStyle].
	TestPackageStyle string

	// Stub holds naming conventions for the stub generator.
	Stub StubConfig
}

Config holds project-wide conventions that influence code generation. The CLI is responsible for loading this from .testkit.yml — the gen package never touches YAML directly.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config with all default values.

type ConstInfo

type ConstInfo struct {
	Name    string
	Type    types.Type
	Value   constant.Value
	Doc     string // doc comment above the constant
	Comment string // inline comment after the constant (e.g. "// Pending")
	Pos     token.Position
}

ConstInfo holds a named constant — used by the enum generator to find iota-based const blocks.

type Directive

type Directive struct {
	Name string
	Args []string
}

Directive is a parsed //testkit: annotation on a type or method.

//testkit:errors ErrNotFound ErrConflict

Produces Directive{Name: "errors", Args: ["ErrNotFound", "ErrConflict"]}.

type Error

type Error struct {
	Pos     token.Position // file:line:col, zero value if not applicable
	Message string
	Cause   error // wrapped underlying error, if any
}

Error is a positioned error returned by the generator engine. When Pos is valid, Error.Error formats as "file:line: message".

func Errorf

func Errorf(pos token.Position, format string, args ...any) *Error

Errorf creates a positioned error with a formatted message.

func ValidateTypes

func ValidateTypes(pkg *Package, names []string, kind TypeKind) []*Error

ValidateTypes checks that all named types exist in the package and are of the expected kind. Returns a slice of positioned errors for any failures.

func WrapErr

func WrapErr(pos token.Position, cause error, format string, args ...any) *Error

WrapErr creates a positioned error wrapping an underlying cause.

func (*Error) Error

func (e *Error) Error() string

Error formats the error with position information when available.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying cause for errors.Is / errors.As chains.

type FieldData

type FieldData struct {
	FieldName string // "ID", "Name" — Go-initialism-aware
	TypeStr   string // "context.Context", "store.Item"
	ZeroValue string // `""`, `0`, `nil`, `Item{}`
	IsError   bool   // true if this is the error return
}

FieldData is a rendered struct field used by multiple generators (stub call types, builder fields, recording call types, suite specs).

func BuildParamFields

func BuildParamFields(tuple *types.Tuple, tracker *ImportTracker) []FieldData

BuildParamFields creates FieldData for each parameter in a function signature tuple. Parameter names are capitalized following Go initialism conventions.

func BuildResultFields

func BuildResultFields(tuple *types.Tuple, tracker *ImportTracker) []FieldData

BuildResultFields creates FieldData for each result in a function signature tuple. Names are derived from declared names when available, falling back to "Result"/"Result0"/"Err" conventions.

type FieldInfo

type FieldInfo struct {
	Name     string
	Type     types.Type
	Exported bool
	Tag      string
}

FieldInfo holds a single struct field.

type GenerateDirective

type GenerateDirective struct {
	Generator string   // "stub", "builder", "recording", etc.
	Output    string   // -o flag value, or "" for convention default
	Types     []string // type arguments
	File      string   // source file containing the directive
	Line      int
}

GenerateDirective is a parsed //go:generate testkit line from a source file. Used for cross-package linking — finding where generated code for a type lives.

type Generator

type Generator interface {
	// Name returns the subcommand name ("stub", "builder", etc.).
	Name() string

	// Generate produces output files for the given package and type
	// arguments. The args slice contains type names (e.g. ["Store"])
	// or is empty for generators that scan the whole package (sentinel).
	Generate(pkg *Package, args []string, cfg Config, opts Options) (*Result, error)
}

Generator produces output files from Go type information. Each generator (stub, builder, sentinel, enum, suite, model, etc.) implements this interface and registers with the Registry.

type Header struct {
	Subcommand string // "stub", "recording", etc.
	Args       string // original command-line args for traceability
	SourceFile string // optional source file:line for navigation (e.g. "store.go:14")
	BuildTag   string // optional //go:build tag, empty for most generators
}

Header describes the generated-file header comment.

type Import

type Import struct {
	Alias string // empty when package name matches last path element
	Path  string
}

Import represents a single import in a generated file.

type ImportTracker

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

ImportTracker collects import paths needed by generated code and assigns short aliases when package names collide. Thread-unsafe — use one tracker per generated file.

func NewImportTracker

func NewImportTracker(localPkgPath string) *ImportTracker

NewImportTracker returns an ImportTracker for a generated file in the package with the given import path. Imports of localPkgPath are omitted from the output (same package, no qualifier needed).

func (*ImportTracker) Add

func (t *ImportTracker) Add(pkg *types.Package) string

Add registers a package import and returns the qualifier to use in generated code. Returns empty string if pkg is the local package.

func (*ImportTracker) AddPath

func (t *ImportTracker) AddPath(pkgPath string) string

AddPath registers an import by path and returns the qualifier. The package name is derived from the last element of the path.

func (*ImportTracker) Imports

func (t *ImportTracker) Imports() []Import

Imports returns all collected imports sorted by path. The local package is excluded.

func (*ImportTracker) Qualifier

func (t *ImportTracker) Qualifier() types.Qualifier

Qualifier returns a types.Qualifier function suitable for types.TypeString. It calls ImportTracker.Add for each referenced package.

type InterfaceInfo

type InterfaceInfo struct {
	Name       string
	OriginName string // For directive/doc lookup; differs from Name for type aliases of generic instantiations.
	Type       *types.Interface
	Methods    []MethodInfo
	TypeParams []TypeParamInfo
	Doc        string
	Pos        token.Position
}

InterfaceInfo holds a named interface with its methods, type parameters, and doc comment. Methods are flattened — embedded interface methods are included, sorted by name.

func (*InterfaceInfo) TypeParamArgs

func (i *InterfaceInfo) TypeParamArgs() string

TypeParamArgs renders type parameter names for instantiation.

"[K, V]"

func (*InterfaceInfo) TypeParamDecl

func (i *InterfaceInfo) TypeParamDecl(t *ImportTracker) string

TypeParamDecl renders the type parameter declaration for a generic interface or struct.

"[K comparable, V any]"

type IterSeqInfo

type IterSeqInfo struct {
	IsSeq     bool   // true if iter.Seq[V]
	IsSeq2    bool   // true if iter.Seq2[K, V]
	Seq2Error bool   // true if iter.Seq2[V, error] — the error-yielding pattern
	ElemType  string // qualified type string for V (Seq) or K (Seq2)
	ValType   string // qualified type string for V in Seq2 (empty for Seq)
}

IterSeqInfo holds the result of inspecting a return type for iter.Seq or iter.Seq2. Zero value means the type is not an iterator.

func AnalyzeIterReturn

func AnalyzeIterReturn(typ types.Type, tracker *ImportTracker) IterSeqInfo

AnalyzeIterReturn inspects typ and returns IterSeqInfo if it is iter.Seq[V] or iter.Seq2[K, V]. Returns zero value for non-iterator types.

type Loader

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

Loader caches loaded packages. Create one per testkit invocation and reuse across generators to avoid redundant go/packages calls.

func NewLoader

func NewLoader() *Loader

NewLoader returns a new Loader with an empty cache.

func (*Loader) Load

func (l *Loader) Load(pattern, workDir string) (*Package, error)

Load loads a Go package by pattern (import path, relative path, or "." for current directory). workDir is the directory to resolve relative patterns from — matching //go:generate behavior. Returns a cached result on repeated calls for the same package.

type MethodInfo

type MethodInfo struct {
	Name       string
	Signature  *types.Signature
	Doc        string
	Directives []Directive
	Pos        token.Position
}

MethodInfo holds a single method with its signature, doc comment, and any //testkit: directives attached to it.

func (*MethodInfo) CallForward

func (m *MethodInfo) CallForward(recv string) string

CallForward renders a forwarding call expression. For variadic methods, the last parameter is spread with "...".

"recv.Get(ctx, id)"
"recv.Find(ctx, ids...)"

func (*MethodInfo) FuncType

func (m *MethodInfo) FuncType(t *ImportTracker) string

FuncType renders the function type signature (without name).

"func(context.Context, model.PutRequest) error"

func (*MethodInfo) HasContext

func (m *MethodInfo) HasContext() bool

HasContext reports whether the first parameter is context.Context.

func (*MethodInfo) IsVariadic

func (m *MethodInfo) IsVariadic() bool

IsVariadic reports whether the last parameter is variadic.

func (*MethodInfo) NumParams

func (m *MethodInfo) NumParams() int

NumParams returns the number of parameters (excluding receiver).

func (*MethodInfo) NumResults

func (m *MethodInfo) NumResults() int

NumResults returns the number of result values.

func (*MethodInfo) ParamList

func (m *MethodInfo) ParamList(t *ImportTracker) string

ParamList renders the parameter list as Go source using the given ImportTracker to qualify types.

"ctx context.Context, id string"

func (*MethodInfo) ParamNameList

func (m *MethodInfo) ParamNameList() []string

ParamNameList returns individual parameter names as a slice.

func (*MethodInfo) ParamNames

func (m *MethodInfo) ParamNames() string

ParamNames renders just the parameter names, comma-separated.

"ctx, id"

func (*MethodInfo) ParamNamesSpread

func (m *MethodInfo) ParamNamesSpread() string

ParamNamesSpread renders parameter names for a forwarding call. For variadic methods, the last parameter is spread with "...".

"ctx, ids..." (variadic)
"ctx, id"    (non-variadic)

func (*MethodInfo) ResultList

func (m *MethodInfo) ResultList(t *ImportTracker) string

ResultList renders the result type list as Go source.

"(Item, error)" or "error" for single result

func (*MethodInfo) ReturnsError

func (m *MethodInfo) ReturnsError() bool

ReturnsError reports whether the last result is the error interface.

func (*MethodInfo) ZeroResults

func (m *MethodInfo) ZeroResults(t *ImportTracker) string

ZeroResults renders the zero values for all result types, comma-separated. Used for error return paths.

"Item{}, nil"

type MethodShape

type MethodShape int

MethodShape classifies an interface method by its signature pattern. The generator uses the shape to emit type-safe On<Method> options accepting only primitives matching the detected shape.

Observer alignment: plug-in primitives for each shape receive context.Context in their closures if and only if the method itself takes context.Context. Pure and Predicate methods are ctx-free by definition (rules 2-3 require !hasCtx), so their observers (PureContext, PredicateContext) are also ctx-free. This is intentional, not an omission.

const (
	ShapeUnknown        MethodShape = iota
	ShapeReader                     // func(ctx, K) (V, error)
	ShapeReaderWithBool             // func(ctx, K) (V, bool) or func(K) (V, bool)
	ShapeLookup                     // func(K) (R1, R2, bool) or func(ctx, K) (R1, R2, bool)
	ShapeWriter                     // func(ctx, V) error or func(ctx, V) (R, error)
	ShapeMutator                    // func(ctx, V) — no return; requires //testkit:mutator directive
	ShapeDeleter                    // func(ctx, K) error — requires //testkit:deleter directive
	ShapeAggregator                 // func(ctx) (T, error)
	ShapeStreamReader               // returns iter.Seq[V] or iter.Seq2[V, error]
	ShapeLifecycle                  // func(ctx) error
	ShapePure                       // no error return, no ctx
	ShapePredicate                  // returns bool only, no ctx
	ShapePoisonAccessor             // func() error — no ctx, no params, returns error only
)

Method shape constants.

func (MethodShape) String

func (s MethodShape) String() string

String returns the shape name for debugging.

type Options

type Options struct {
	Output           string // -o flag value, empty for convention default
	Check            bool   // dry-run mode — compare but don't write
	Verbose          bool
	BuildTag         string // e.g. "integration" for //go:build tag
	WorkDir          string // directory //go:generate runs in
	SourceFile       string // $GOFILE — the file containing the //go:generate directive
	OutputPackage    string // override output package name (set when -p loads a remote package)
	OutputImportBase string // import path of the CWD (set when -p loads a remote package)
}

Options holds per-invocation settings for a generator.

type OutputFile

type OutputFile struct {
	Path    string // relative to WorkDir
	Content []byte // formatted, with header
}

OutputFile is a single generated file with its path and content.

type Package

type Package struct {
	Pkg    *types.Package
	Syntax []*ast.File
	Fset   *token.FileSet
	Info   *types.Info
	Module *packages.Module
}

Package is a loaded Go package with query methods for type information. Generators call the methods they need — the struct is stable and does not change when new generators are added.

func (*Package) Const

func (p *Package) Const(name string) (*ConstInfo, error)

Const looks up a named constant. Returns a positioned Error if not found or not a constant.

func (*Package) ConstDirectives

func (p *Package) ConstDirectives(varName string) []Directive

ConstDirectives returns all //testkit: annotations on a package-level constant declaration.

func (*Package) ConstsOfType

func (p *Package) ConstsOfType(typeName string) []*ConstInfo

ConstsOfType returns all exported constants whose type matches the named type, sorted by name.

func (*Package) Directives

func (p *Package) Directives(objectName string) []Directive

Directives returns all //testkit: annotations on the doc comment of a top-level type declaration.

func (*Package) EffectiveMethodDirectives

func (p *Package) EffectiveMethodDirectives(typeName, methodName string) []Directive

EffectiveMethodDirectives returns the merged directives for a method, combining interface-level directives (inherited by all methods) with method-level directives. Interface-level directives appear first. A method-level directive with the same name as an interface-level one does NOT replace it — both are kept. Use an explicit "//testkit:<name>" with no args on the method to clear an inherited parameterised directive if needed.

func (*Package) ErrorTypeHasIs

func (p *Package) ErrorTypeHasIs(typeName string) bool

ErrorTypeHasIs reports whether the named error type has a custom Is(error) bool method for matching semantics.

func (*Package) ErrorTypeHasUnwrap

func (p *Package) ErrorTypeHasUnwrap(typeName string) bool

ErrorTypeHasUnwrap reports whether the named error type has an Unwrap() error method for error chain traversal.

func (*Package) ErrorTypes

func (p *Package) ErrorTypes() []*StructInfo

ErrorTypes returns all exported struct types that implement the error interface (via pointer receiver), sorted by name. These are custom error types like NotFoundError with an Error() string method.

func (*Package) ErrorVars

func (p *Package) ErrorVars(sourceFile ...string) []*VarInfo

ErrorVars returns all exported package-level variables whose name starts with "Err", sorted by name. If sourceFile is non-empty, only variables declared in that file are returned (for file-scoped generation via $GOFILE).

func (*Package) FieldDirectives

func (p *Package) FieldDirectives(typeName, fieldName string) []Directive

FieldDirectives returns all //testkit: annotations on a struct field.

func (*Package) GenerateDirectives

func (p *Package) GenerateDirectives() []GenerateDirective

GenerateDirectives returns all //go:generate testkit directives found in the package's source files.

func (*Package) Interface

func (p *Package) Interface(name string) (*InterfaceInfo, error)

Interface looks up a named interface in the package. Returns a positioned Error if the name does not exist or is not an interface.

func (*Package) Interfaces

func (p *Package) Interfaces() []*InterfaceInfo

Interfaces returns all exported interfaces in the package, sorted by name.

func (*Package) MethodDirectives

func (p *Package) MethodDirectives(typeName, methodName string) []Directive

MethodDirectives returns all //testkit: annotations on a method of an interface or concrete type.

func (*Package) MethodsOn

func (p *Package) MethodsOn(typeName string) []*MethodInfo

MethodsOn returns the method set of a named concrete type, sorted by name. Returns nil if the type has no methods.

func (*Package) ResolveVar

func (p *Package) ResolveVar(name string) (*VarInfo, string, error)

ResolveVar looks up a variable by name. The name can be a bare identifier (resolved in the source package) or a qualified name like "otherpkg.ErrXxx" (resolved in the named import). Returns the VarInfo and the import path of the package containing the variable (empty string for the source package).

func (*Package) Struct

func (p *Package) Struct(name string) (*StructInfo, error)

Struct looks up a named struct in the package. Returns a positioned Error if the name does not exist or is not a struct.

func (*Package) Structs

func (p *Package) Structs() []*StructInfo

Structs returns all exported structs in the package, sorted by name.

func (*Package) Var

func (p *Package) Var(name string) (*VarInfo, error)

Var looks up a named package-level variable. Returns a positioned Error if not found or not a variable.

func (*Package) VarDirectives

func (p *Package) VarDirectives(varName string) []Directive

VarDirectives returns all //testkit: annotations on a package-level variable declaration.

type Registry

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

Registry holds generators and provides lookup by name. The CLI uses this to dispatch subcommands to the correct generator.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates an empty Registry.

func (*Registry) Get

func (r *Registry) Get(name string) Generator

Get returns the generator for the given name, or nil if not found.

func (*Registry) Names

func (r *Registry) Names() []string

Names returns all registered generator names in sorted order.

func (*Registry) Register

func (r *Registry) Register(g Generator)

Register adds a generator. Panics if a generator with the same name is already registered.

type Result

type Result struct {
	Files []OutputFile
}

Result holds the output files from a single generator invocation.

type ShapeInfo

type ShapeInfo struct {
	Shape    MethodShape
	KeyType  string      // qualified type for K (Reader/Deleter)
	ValType  string      // qualified type for V
	RetType  string      // qualified type for R (Writer with result)
	IterInfo IterSeqInfo // for StreamReader
}

ShapeInfo holds the detected shape of a method plus the extracted type parameters for that shape.

func DetectShape

func DetectShape(m MethodInfo, tracker *ImportTracker, dirs []Directive) ShapeInfo

DetectShape classifies a method by its signature pattern.

Detection rules (first match wins):

  1. Returns iter.Seq[T] or iter.Seq2[T, error] → StreamReader
  2. Returns bool only → Predicate
  3. No error return → Pure
  4. ctx + one non-ctx param + (V, error) return where V is not error → Reader
  5. ctx + one non-ctx param + error-only return → Writer (default; //testkit:deleter overrides)
  6. ctx + one non-ctx param + (R, error) return → Writer (with result)
  7. ctx only + (T, error) return → Aggregator
  8. ctx only + error return → Lifecycle
  9. Otherwise → Unknown

type StructInfo

type StructInfo struct {
	Name       string
	Type       *types.Struct
	Fields     []FieldInfo
	TypeParams []TypeParamInfo
	Doc        string
	Pos        token.Position
}

StructInfo holds a named struct with its fields, type parameters, and doc comment. Fields are in declaration order.

func (*StructInfo) TypeParamArgs

func (s *StructInfo) TypeParamArgs() string

TypeParamArgs renders type parameter names for instantiation.

func (*StructInfo) TypeParamDecl

func (s *StructInfo) TypeParamDecl(t *ImportTracker) string

TypeParamDecl renders the type parameter declaration for a generic struct.

type StubConfig

type StubConfig struct {
	// FilePattern is the base name pattern for generated stub files.
	// "{type}" is replaced with the lowercased type name.
	// Default: [DefaultStubFilePattern].
	FilePattern string

	// TypeSuffix is appended to the type name for generated stub types.
	// Default: [DefaultStubTypeSuffix].
	TypeSuffix string
}

StubConfig holds naming conventions for the stub generator.

type TestFileInfo

type TestFileInfo struct {
	PackageName  string   // "storetest_test" or "storetest" for internal style
	GenQualifier string   // "storetest." or "" for internal style
	Imports      []Import // base imports + self-import for external style
}

TestFileInfo holds the derived package name, qualifier, and imports for a generated test file. Used by generators that produce a companion _test.go file alongside the implementation file.

func BuildTestFileInfo

func BuildTestFileInfo(
	basePkgName string,
	baseImports []Import,
	cfg Config,
	genImportPath string,
) TestFileInfo

BuildTestFileInfo computes the test file metadata from the base package name, imports, config, and the generated package's import path. For external test style, it appends _test to the package name and adds the generated package to the import list.

type TypeKind

type TypeKind int

TypeKind constrains what kind of named type a generator expects.

const (
	// KindInterface requires the type to be an interface.
	KindInterface TypeKind = iota
	// KindStruct requires the type to be a struct.
	KindStruct
	// KindAny accepts any named type (sentinel, enum generators).
	KindAny
)

type TypeParamInfo

type TypeParamInfo struct {
	Name       string
	Constraint types.Type
}

TypeParamInfo holds a generic type parameter with its constraint.

type VarInfo

type VarInfo struct {
	Name string
	Type types.Type
	Doc  string
	Pos  token.Position
}

VarInfo holds a named package-level variable — used by the sentinel generator to find exported Err* variables.

Directories

Path Synopsis
Package bench implements the benchmark generator for testkit.
Package bench implements the benchmark generator for testkit.
Package builder implements the builder generator for testkit.
Package builder implements the builder generator for testkit.
Package directiveparse provides the known-directive registry and composition validation for testkit generators.
Package directiveparse provides the known-directive registry and composition validation for testkit generators.
Package directives defines the canonical directive name constants shared across the gen package and its sub-packages.
Package directives defines the canonical directive name constants shared across the gen package and its sub-packages.
Package enum implements the enum generator for testkit.
Package enum implements the enum generator for testkit.
Package model implements the model-based testing generator for testkit.
Package model implements the model-based testing generator for testkit.
Package sentinel implements the sentinel generator for testkit.
Package sentinel implements the sentinel generator for testkit.
Package stub implements the stub generator for testkit.
Package stub implements the stub generator for testkit.
Package suite implements the conformance suite generator for testkit.
Package suite implements the conformance suite generator for testkit.

Jump to

Keyboard shortcuts

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