Documentation
¶
Overview ¶
Package genkit provides a framework for building Go code generators, inspired by google.golang.org/protobuf/compiler/protogen and Go's standard toolchain.
Key design principles:
- Library-first: designed as a library, not a plugin system
- Go toolchain compatible: supports "./..." patterns like go build
- Type-safe API: structured types for describing source code elements
- GeneratedFile abstraction: convenient code generation with automatic import management
Basic usage:
gen := genkit.New()
if err := gen.Load("./..."); err != nil {
log.Fatal(err)
}
for _, pkg := range gen.Packages {
for _, enum := range pkg.Enums {
g := gen.NewGeneratedFile(genkit.OutputPath(pkg.Dir, enum.Name+"_enum.go"))
// generate code...
}
}
if err := gen.Write(); err != nil {
log.Fatal(err)
}
Package genkit provides code generation utilities.
Index ¶
- Constants
- func HasAnnotation(doc, tool, name string) bool
- func OutputPath(dir, filename string) string
- type Annotation
- type Annotations
- type Enum
- type EnumValue
- type Field
- type GeneratedFile
- func (g *GeneratedFile) Content() ([]byte, error)
- func (g *GeneratedFile) Import(importPath GoImportPath) GoPackageName
- func (g *GeneratedFile) ImportAs(importPath GoImportPath, alias GoPackageName) GoPackageName
- func (g *GeneratedFile) P(v ...any)
- func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string
- func (g *GeneratedFile) Skip()
- func (g *GeneratedFile) Unskip()
- func (g *GeneratedFile) Write(p []byte) (int, error)
- type Generator
- type GoDoc
- type GoFunc
- type GoIdent
- type GoImportPath
- type GoMethod
- type GoPackageName
- type GoParam
- type GoParams
- type GoPrintable
- type GoReceiver
- type GoResults
- type Logger
- func (l *Logger) Done(format string, args ...any)
- func (l *Logger) Error(format string, args ...any)
- func (l *Logger) Find(format string, args ...any)
- func (l *Logger) Info(format string, args ...any)
- func (l *Logger) Item(format string, args ...any)
- func (l *Logger) Load(format string, args ...any)
- func (l *Logger) Warn(format string, args ...any)
- func (l *Logger) Write(format string, args ...any)
- type Options
- type Package
- type RawString
- type Tool
- type Type
Constants ¶
const ( EmojiInfo = "📦" EmojiWarn = "⚠️" EmojiError = "❌" EmojiDone = "✅" EmojiFind = "🔍" EmojiWrite = "📝" EmojiLoad = "📂" )
Emoji for log levels
Variables ¶
This section is empty.
Functions ¶
func HasAnnotation ¶
HasAnnotation checks if doc contains a specific annotation. Format: tool:@name (e.g., HasAnnotation(doc, "enumgen", "enum"))
func OutputPath ¶
OutputPath joins directory and filename.
Types ¶
type Annotation ¶
type Annotation struct {
Tool string // tool name (e.g., "enumgen")
Name string // annotation name (e.g., "enum")
Args map[string]string // key=value args
Flags []string // positional args without =
Raw string
}
Annotation represents a parsed annotation from comments. Annotations follow the format: tool:@name or tool:@name(arg1, arg2, key=value) Example: enumgen:@enum(string, json)
func GetAnnotation ¶
func GetAnnotation(doc, tool, name string) *Annotation
GetAnnotation returns the first annotation with the given tool and name.
func ParseAnnotations ¶
func ParseAnnotations(doc string) []*Annotation
ParseAnnotations extracts annotations from a doc comment. Supports format: tool:@name or tool:@name(args) or tool:@name.subname(args)
func (*Annotation) Get ¶
func (a *Annotation) Get(name string) string
Get returns an arg value or empty string.
func (*Annotation) GetOr ¶
func (a *Annotation) GetOr(name, def string) string
GetOr returns an arg value or the default.
func (*Annotation) Has ¶
func (a *Annotation) Has(name string) bool
Has checks if the annotation has a flag or arg (case-sensitive).
type Annotations ¶
type Annotations []*Annotation
Annotations is a slice of annotations with helper methods.
func ParseDoc ¶
func ParseDoc(doc string) Annotations
ParseDoc parses all annotations from a doc comment.
func (Annotations) Get ¶
func (a Annotations) Get(tool, name string) *Annotation
Get returns the first annotation with the tool and name.
func (Annotations) Has ¶
func (a Annotations) Has(tool, name string) bool
Has checks if any annotation with the tool and name exists.
type GeneratedFile ¶
type GeneratedFile struct {
// contains filtered or unexported fields
}
GeneratedFile represents a file to be generated.
func (*GeneratedFile) Content ¶
func (g *GeneratedFile) Content() ([]byte, error)
Content returns the formatted content.
func (*GeneratedFile) Import ¶
func (g *GeneratedFile) Import(importPath GoImportPath) GoPackageName
Import explicitly imports a package and returns its local name.
func (*GeneratedFile) ImportAs ¶
func (g *GeneratedFile) ImportAs(importPath GoImportPath, alias GoPackageName) GoPackageName
ImportAs explicitly imports a package with a custom alias. This is useful for packages where the import path doesn't match the package name, e.g., "gopkg.in/yaml.v3" should be imported as "yaml".
func (*GeneratedFile) P ¶
func (g *GeneratedFile) P(v ...any)
P prints a line to the generated file. Arguments are concatenated without spaces. Use GoIdent for automatic import handling. Special types: GoIdent, GoMethod, GoFunc, GoDoc, GoParams, GoResults are formatted appropriately.
func (*GeneratedFile) QualifiedGoIdent ¶
func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string
QualifiedGoIdent returns the qualified identifier string with import handling.
type Generator ¶
type Generator struct {
// Packages are the loaded packages.
Packages []*Package
// Fset is the token file set.
Fset *token.FileSet
// contains filtered or unexported fields
}
Generator is the main entry point for code generation.
func (*Generator) Load ¶
Load loads packages matching the given patterns. Patterns follow Go's standard conventions:
- "./..." - current directory and all subdirectories
- "./pkg" - specific package
- "." - current directory only
func (*Generator) NewGeneratedFile ¶
func (g *Generator) NewGeneratedFile(filename string, importPath GoImportPath) *GeneratedFile
NewGeneratedFile creates a new file to be generated.
type GoDoc ¶
type GoDoc string
GoDoc represents a documentation comment.
func (GoDoc) PrintTo ¶
func (d GoDoc) PrintTo(g *GeneratedFile)
type GoFunc ¶
GoFunc represents a function signature (no receiver).
func (GoFunc) PrintTo ¶
func (f GoFunc) PrintTo(g *GeneratedFile)
type GoIdent ¶
type GoIdent struct {
GoImportPath GoImportPath
GoName string
}
GoIdent is a Go identifier with its import path.
type GoImportPath ¶
type GoImportPath string
GoImportPath is a Go import path.
func (GoImportPath) Ident ¶
func (p GoImportPath) Ident(name string) GoIdent
Ident returns a GoIdent for the given name in this import path.
type GoMethod ¶
type GoMethod struct {
Doc GoDoc // documentation comment (without //)
Recv GoReceiver // receiver
Name string // method name
Params GoParams // parameters
Results GoResults // return values
}
GoMethod represents a method signature for code generation.
func (GoMethod) PrintTo ¶
func (m GoMethod) PrintTo(g *GeneratedFile)
type GoParam ¶
type GoParam struct {
Name string // parameter name (can be empty for returns)
Type any // type: string, GoIdent
}
GoParam represents a function/method parameter or return value.
type GoParams ¶
GoParams represents a parameter list.
func (GoParams) PrintTo ¶
func (p GoParams) PrintTo(g *GeneratedFile)
type GoPrintable ¶
type GoPrintable interface {
PrintTo(g *GeneratedFile)
}
GoPrintable is implemented by types that can print themselves to a GeneratedFile.
type GoReceiver ¶
type GoReceiver struct {
Name string // receiver name (e.g., "x")
Type any // receiver type: string, GoIdent
Pointer bool // whether receiver is pointer
}
GoReceiver represents a method receiver.
type GoResults ¶
type GoResults []GoParam
GoResults represents a return value list.
func (GoResults) PrintTo ¶
func (r GoResults) PrintTo(g *GeneratedFile)
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger provides styled logging for code generators.
func NewLoggerWithWriter ¶
NewLoggerWithWriter creates a new Logger with custom writer.
type Options ¶
type Options struct {
// Tags are build tags to use when loading packages.
Tags []string
// Dir is the working directory. If empty, uses current directory.
Dir string
}
Options configures the generator.
type Package ¶
type Package struct {
Name string
PkgPath string
Dir string
GoFiles []string
Fset *token.FileSet
TypesPkg *types.Package
TypesInfo *types.Info
Syntax []*ast.File
Types []*Type
Enums []*Enum
}
Package represents a loaded Go package.
func (*Package) GoImportPath ¶
func (p *Package) GoImportPath() GoImportPath
GoImportPath returns the import path for this package.
type RawString ¶
type RawString string
RawString represents a raw string literal (backtick-quoted) for code generation. Use this for regex patterns or other strings that should not be escaped.
func (RawString) PrintTo ¶
func (r RawString) PrintTo(g *GeneratedFile)
type Tool ¶
type Tool interface {
// Name returns the tool name (e.g., "enumgen", "validategen").
Name() string
// Run processes all packages and generates code.
// It should handle logging internally.
Run(gen *Generator, log *Logger) error
}
Tool is the interface that code generation tools must implement. It provides a unified way to run code generators.