genkit

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2025 License: MIT Imports: 14 Imported by: 0

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

View Source
const (
	EmojiInfo  = "📦"
	EmojiWarn  = "⚠️"
	EmojiError = "❌"
	EmojiDone  = "✅"
	EmojiFind  = "🔍"
	EmojiWrite = "📝"
	EmojiLoad  = "📂"
)

Emoji for log levels

Variables

This section is empty.

Functions

func HasAnnotation

func HasAnnotation(doc, tool, name string) bool

HasAnnotation checks if doc contains a specific annotation. Format: tool:@name (e.g., HasAnnotation(doc, "enumgen", "enum"))

func OutputPath

func OutputPath(dir, filename string) string

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 Enum

type Enum struct {
	Name   string
	Doc    string
	Pkg    *Package
	Values []*EnumValue
}

Enum represents a Go enum (type with const values).

func (*Enum) GoIdent

func (e *Enum) GoIdent() GoIdent

GoIdent returns the GoIdent for this enum.

type EnumValue

type EnumValue struct {
	Name    string
	Value   string
	Doc     string
	Comment string
	Pos     token.Position // source position
}

EnumValue represents an enum constant.

type Field

type Field struct {
	Name    string
	Type    string
	Tag     string
	Doc     string
	Comment string
	Pos     token.Position // source position
}

Field represents a struct field.

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.

func (*GeneratedFile) Skip

func (g *GeneratedFile) Skip()

Skip marks this file to be skipped.

func (*GeneratedFile) Unskip

func (g *GeneratedFile) Unskip()

Unskip reverses Skip.

func (*GeneratedFile) Write

func (g *GeneratedFile) Write(p []byte) (int, error)

Write implements io.Writer.

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 New

func New(opts ...Options) *Generator

New creates a new Generator.

func (*Generator) DryRun

func (g *Generator) DryRun() (map[string][]byte, error)

DryRun returns generated content without writing files.

func (*Generator) Load

func (g *Generator) Load(patterns ...string) error

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.

func (*Generator) Write

func (g *Generator) Write() error

Write writes all generated files to disk.

type GoDoc

type GoDoc string

GoDoc represents a documentation comment.

func (GoDoc) PrintTo

func (d GoDoc) PrintTo(g *GeneratedFile)

type GoFunc

type GoFunc struct {
	Doc     GoDoc
	Name    string
	Params  GoParams
	Results GoResults
}

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.

func (GoIdent) String

func (id GoIdent) String() string

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 GoPackageName

type GoPackageName string

GoPackageName is a Go package name.

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

type GoParams struct {
	List     []GoParam
	Variadic bool
}

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 NewLogger

func NewLogger() *Logger

NewLogger creates a new Logger writing to stdout.

func NewLoggerWithWriter

func NewLoggerWithWriter(w io.Writer) *Logger

NewLoggerWithWriter creates a new Logger with custom writer.

func (*Logger) Done

func (l *Logger) Done(format string, args ...any)

Done logs a completion message.

func (*Logger) Error

func (l *Logger) Error(format string, args ...any)

Error logs an error message.

func (*Logger) Find

func (l *Logger) Find(format string, args ...any)

Find logs a discovery message.

func (*Logger) Info

func (l *Logger) Info(format string, args ...any)

Info logs an info message.

func (*Logger) Item

func (l *Logger) Item(format string, args ...any)

Item logs an indented item under the previous log entry.

func (*Logger) Load

func (l *Logger) Load(format string, args ...any)

Load logs a loading message.

func (*Logger) Warn

func (l *Logger) Warn(format string, args ...any)

Warn logs a warning message.

func (*Logger) Write

func (l *Logger) Write(format string, args ...any)

Write logs a file write message.

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

	// IgnoreGeneratedFiles when true, ignores files that start with
	// "// Code generated" comment. This is useful for ignoring generated
	// files that may have syntax errors.
	IgnoreGeneratedFiles bool
}

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.

type Type

type Type struct {
	Name     string
	Doc      string
	Pkg      *Package
	Fields   []*Field
	TypeSpec *ast.TypeSpec
}

Type represents a Go type declaration.

func (*Type) GoIdent

func (t *Type) GoIdent() GoIdent

GoIdent returns the GoIdent for this type.

Jump to

Keyboard shortcuts

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