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
- Variables
- func CamelCase(s string) string
- func DerivePackageName(outputPath, sourcePkgName string, cfg Config, opts Options) string
- func FormatDocComment(doc string) string
- func FuncMap() template.FuncMap
- func HasContextParam(sig *types.Signature) bool
- func HasUnexportedFields(typ types.Type) bool
- func IsContextType(typ types.Type) bool
- func IsErrorType(typ types.Type) bool
- func LowerCamelCase(s string) string
- func NewTemplateSet() *template.Template
- func NonCtxParamCount(sig *types.Signature) int
- func OutputImportPath(outputPath string, pkg *Package, opts Options) (string, error)
- func ParamName(i int) string
- func QualifyType(qualifier, typeName string) string
- func Render(tmplText string, data any, header Header) ([]byte, error)
- func RenderTemplate(tmpl *template.Template, name string, data any, header Header) ([]byte, error)
- func SampleBasicValue(b *types.Basic, fieldName string) string
- func SampleValueOf(typ types.Type, fieldName string, tracker *ImportTracker) string
- func SnakeCase(s string) string
- func SplitWords(s string) []string
- func TestPathFrom(implPath string) string
- func Title(s string) string
- func TypeStr(typ types.Type, tracker *ImportTracker) string
- func WriteResult(result *Result, workDir string, check bool) error
- func ZeroCallArgs(sig *types.Signature, tracker *ImportTracker) string
- func ZeroCallArgsWithCtx(sig *types.Signature, tracker *ImportTracker, ctxExpr string) string
- func ZeroValueOf(typ types.Type, t *ImportTracker) string
- type Config
- type ConstInfo
- type Directive
- type Error
- type FieldData
- type FieldInfo
- type GenerateDirective
- type Generator
- type Header
- type Import
- type ImportTracker
- type InterfaceInfo
- type IterSeqInfo
- type Loader
- type MethodInfo
- func (m *MethodInfo) CallForward(recv string) string
- func (m *MethodInfo) FuncType(t *ImportTracker) string
- func (m *MethodInfo) HasContext() bool
- func (m *MethodInfo) IsVariadic() bool
- func (m *MethodInfo) NumParams() int
- func (m *MethodInfo) NumResults() int
- func (m *MethodInfo) ParamList(t *ImportTracker) string
- func (m *MethodInfo) ParamNameList() []string
- func (m *MethodInfo) ParamNames() string
- func (m *MethodInfo) ParamNamesSpread() string
- func (m *MethodInfo) ResultList(t *ImportTracker) string
- func (m *MethodInfo) ReturnsError() bool
- func (m *MethodInfo) ZeroResults(t *ImportTracker) string
- type MethodShape
- type Options
- type OutputFile
- type Package
- func (p *Package) Const(name string) (*ConstInfo, error)
- func (p *Package) ConstDirectives(varName string) []Directive
- func (p *Package) ConstsOfType(typeName string) []*ConstInfo
- func (p *Package) Directives(objectName string) []Directive
- func (p *Package) EffectiveMethodDirectives(typeName, methodName string) []Directive
- func (p *Package) ErrorTypeHasIs(typeName string) bool
- func (p *Package) ErrorTypeHasUnwrap(typeName string) bool
- func (p *Package) ErrorTypes() []*StructInfo
- func (p *Package) ErrorVars(sourceFile ...string) []*VarInfo
- func (p *Package) FieldDirectives(typeName, fieldName string) []Directive
- func (p *Package) GenerateDirectives() []GenerateDirective
- func (p *Package) Interface(name string) (*InterfaceInfo, error)
- func (p *Package) Interfaces() []*InterfaceInfo
- func (p *Package) MethodDirectives(typeName, methodName string) []Directive
- func (p *Package) MethodsOn(typeName string) []*MethodInfo
- func (p *Package) ResolveVar(name string) (*VarInfo, string, error)
- func (p *Package) Struct(name string) (*StructInfo, error)
- func (p *Package) Structs() []*StructInfo
- func (p *Package) Var(name string) (*VarInfo, error)
- func (p *Package) VarDirectives(varName string) []Directive
- type Registry
- type Result
- type ShapeInfo
- type StructInfo
- type StubConfig
- type TestFileInfo
- type TypeKind
- type TypeParamInfo
- type VarInfo
Constants ¶
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" )
const ( // ErrFieldName is the default name for error return fields. ErrFieldName = "Err" // ResultFieldName is the default name for non-error return fields. ResultFieldName = "Result" )
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 ¶
var EmptyPos token.Position
EmptyPos is the zero-value token.Position, used when an error has no specific source location.
Functions ¶
func CamelCase ¶
CamelCase converts a string to CamelCase, splitting on underscores, hyphens, and case boundaries. "hello_world" → "HelloWorld".
func DerivePackageName ¶
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 ¶
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 ¶
FuncMap returns the standard template function map available to all generator templates.
func HasContextParam ¶
HasContextParam reports whether the signature has a context.Context parameter.
func HasUnexportedFields ¶
HasUnexportedFields reports whether the type (or its named underlying struct) contains unexported fields, which prevents cmp.Diff comparison.
func IsContextType ¶
IsContextType reports whether typ is context.Context.
func IsErrorType ¶
IsErrorType reports whether typ is the built-in error interface.
func LowerCamelCase ¶
LowerCamelCase converts a string to lowerCamelCase. "hello_world" → "helloWorld".
func NewTemplateSet ¶
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 ¶
NonCtxParamCount returns the number of non-context.Context parameters.
func OutputImportPath ¶
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 QualifyType ¶
QualifyType prefixes typeName with qualifier if non-empty. QualifyType("store", "Item") → "store.Item". QualifyType("", "Item") → "Item".
func Render ¶
Render executes tmplText with data, prepends the generated-file header, and formats with goimports. Returns formatted Go source.
func RenderTemplate ¶
RenderTemplate executes a pre-parsed template by name (empty for the root template), prepends header, and formats with goimports.
func SampleBasicValue ¶
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 SplitWords ¶
SplitWords splits a string into words on underscores, hyphens, and CamelCase boundaries.
func TestPathFrom ¶
TestPathFrom derives the companion test file path from an impl path. "storetest/store.gen.go" → "storetest/store.gen_test.go".
func Title ¶
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 ¶
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 ¶
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 ValidateTypes ¶
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.
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 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 ¶
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.
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 ¶
Const looks up a named constant. Returns a positioned Error if not found or not a constant.
func (*Package) ConstDirectives ¶
ConstDirectives returns all //testkit: annotations on a package-level constant declaration.
func (*Package) ConstsOfType ¶
ConstsOfType returns all exported constants whose type matches the named type, sorted by name.
func (*Package) Directives ¶
Directives returns all //testkit: annotations on the doc comment of a top-level type declaration.
func (*Package) EffectiveMethodDirectives ¶
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 ¶
ErrorTypeHasIs reports whether the named error type has a custom Is(error) bool method for matching semantics.
func (*Package) ErrorTypeHasUnwrap ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Var looks up a named package-level variable. Returns a positioned Error if not found or not a variable.
func (*Package) VarDirectives ¶
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.
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):
- Returns iter.Seq[T] or iter.Seq2[T, error] → StreamReader
- Returns bool only → Predicate
- No error return → Pure
- ctx + one non-ctx param + (V, error) return where V is not error → Reader
- ctx + one non-ctx param + error-only return → Writer (default; //testkit:deleter overrides)
- ctx + one non-ctx param + (R, error) return → Writer (with result)
- ctx only + (T, error) return → Aggregator
- ctx only + error return → Lifecycle
- 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 TypeParamInfo ¶
TypeParamInfo holds a generic type parameter with its constraint.
Source Files
¶
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. |