genkit

package
v0.3.6 Latest Latest
Warning

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

Go to latest
Published: Jan 9, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package genkit provides configuration types for devgen tools and plugins.

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.

Package genkit provides plugin loading functionality for devgen tools.

Index

Constants

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

Emoji for log levels

Variables

This section is empty.

Functions

func CollectToolConfigs added in v0.2.0

func CollectToolConfigs(tools []Tool) map[string]ToolConfig

CollectToolConfigs collects configurations from a list of tools.

func FindConfig added in v0.2.0

func FindConfig(dir string) (string, error)

FindConfig searches for devgen.toml starting from dir and going up to root.

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 MergeToolConfigs added in v0.2.0

func MergeToolConfigs(configs ...map[string]ToolConfig) map[string]ToolConfig

MergeToolConfigs merges tool configurations from multiple sources. Later sources override earlier ones for the same tool name.

func OutputPath

func OutputPath(dir, filename string) string

OutputPath joins directory and filename.

Types

type AdapterRegistry added in v0.3.3

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

AdapterRegistry manages available agent adapters. It provides a central registry for all supported AI agents, allowing tools to discover and use adapters dynamically.

func NewAdapterRegistry added in v0.3.3

func NewAdapterRegistry() *AdapterRegistry

NewAdapterRegistry creates a new registry with built-in adapters. The registry is pre-populated with adapters for Kiro, CodeBuddy, and Cursor.

func (*AdapterRegistry) Get added in v0.3.3

func (r *AdapterRegistry) Get(name string) (AgentAdapter, bool)

Get retrieves an adapter by name. Returns the adapter and true if found, nil and false otherwise.

Example:

adapter, ok := registry.Get("kiro")
if !ok {
    return fmt.Errorf("unknown agent: kiro")
}

func (*AdapterRegistry) List added in v0.3.3

func (r *AdapterRegistry) List() []string

List returns all registered adapter names in alphabetical order. This is useful for displaying available agents to users.

Example output: ["codebuddy", "cursor", "kiro"]

func (*AdapterRegistry) Register added in v0.3.3

func (r *AdapterRegistry) Register(adapter AgentAdapter)

Register adds an adapter to the registry. If an adapter with the same name already exists, it will be replaced. This allows users to override built-in adapters with custom implementations.

type AgentAdapter added in v0.3.3

type AgentAdapter interface {
	// Name returns the agent identifier (e.g., "kiro", "codebuddy", "cursor").
	// This name is used in CLI commands like `devgen rules --agent kiro`.
	Name() string

	// OutputDir returns the directory path where rules should be written.
	// The path is relative to the project root.
	// Examples:
	//   - Kiro: ".kiro/steering"
	//   - CodeBuddy: ".codebuddy/rules"
	//   - Cursor: ".cursor/rules"
	OutputDir() string

	// Transform converts a generic Rule into agent-specific format.
	// It returns:
	//   - filename: the output filename (e.g., "enumgen.md")
	//   - content: the complete file content with frontmatter and markdown
	//   - error: any transformation error
	//
	// The transformation typically involves:
	//   1. Converting Rule fields to agent-specific frontmatter
	//   2. Formatting the frontmatter as YAML
	//   3. Combining frontmatter with the rule content
	Transform(rule Rule) (filename string, content string, err error)
}

AgentAdapter transforms rules for a specific AI assistant. Different AI assistants (Kiro, CodeBuddy, Cursor, etc.) require different frontmatter formats and directory structures. Adapters handle these differences by converting the generic Rule structure into agent-specific formats.

Example usage:

adapter := &KiroAdapter{}
filename, content, err := adapter.Transform(rule)
if err != nil {
    return err
}
filepath := filepath.Join(adapter.OutputDir(), filename)
os.WriteFile(filepath, []byte(content), 0644)

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 AnnotationConfig added in v0.2.0

type AnnotationConfig struct {
	// Name is the annotation name (e.g., "enum", "validate").
	Name string `toml:"name"`

	// Type is where the annotation can be applied: "type" or "field".
	Type string `toml:"type"`

	// Doc is the documentation for this annotation.
	Doc string `toml:"doc"`

	// Params defines parameter configuration.
	Params *AnnotationParams `toml:"params"`

	// LSP defines LSP integration configuration.
	LSP *LSPConfig `toml:"lsp"`
}

AnnotationConfig defines a single annotation's metadata.

type AnnotationParams added in v0.2.0

type AnnotationParams struct {
	// Type is the parameter type: "string", "number", "bool", "list", or "enum".
	// Can also be an array of types for multiple accepted types.
	Type any `toml:"type"`

	// Values is the list of allowed values for enum type.
	Values []string `toml:"values"`

	// Placeholder is the placeholder text for the parameter.
	Placeholder string `toml:"placeholder"`

	// MaxArgs is the maximum number of arguments allowed.
	MaxArgs int `toml:"maxArgs"`

	// Docs provides documentation for each enum value.
	Docs map[string]string `toml:"docs"`
}

AnnotationParams defines annotation parameter configuration.

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 CodeBuddyAdapter added in v0.3.3

type CodeBuddyAdapter struct{}

CodeBuddyAdapter transforms rules for CodeBuddy AI assistant. CodeBuddy uses YAML frontmatter with 'description', 'globs', and 'alwaysApply' fields.

Frontmatter format:

---
description: Brief description of the rule
globs: **/*.go, **/devgen.toml
alwaysApply: false
---

func (*CodeBuddyAdapter) Name added in v0.3.3

func (c *CodeBuddyAdapter) Name() string

Name returns "codebuddy".

func (*CodeBuddyAdapter) OutputDir added in v0.3.3

func (c *CodeBuddyAdapter) OutputDir() string

OutputDir returns ".codebuddy/rules".

func (*CodeBuddyAdapter) Transform added in v0.3.3

func (c *CodeBuddyAdapter) Transform(rule Rule) (string, string, error)

Transform converts a Rule to CodeBuddy format with YAML frontmatter. It maps Rule fields directly to CodeBuddy's frontmatter format.

type Config added in v0.2.0

type Config struct {
	// Plugins defines external tool plugins to load.
	Plugins []PluginConfig `toml:"plugins"`

	// Tools contains tool-specific configurations (annotations, output suffix, etc.)
	Tools map[string]ToolConfig `toml:"tools"`

	// Rules contains AI rules configuration.
	Rules RulesConfig `toml:"rules"`
}

Config represents the project-level devgen.toml configuration.

func LoadConfig added in v0.2.0

func LoadConfig(dir string) (*Config, error)

LoadConfig loads the devgen.toml configuration from the given directory. It searches for devgen.toml in the directory and its parents up to the root.

func LoadConfigFile added in v0.2.0

func LoadConfigFile(path string) (*Config, error)

LoadConfigFile loads configuration from a specific file path.

type ConfigurableTool added in v0.2.0

type ConfigurableTool interface {
	Tool

	// Config returns the tool's configuration including annotations metadata.
	// This is used by VSCode extension for syntax highlighting and auto-completion,
	// and by CLI for validation.
	Config() ToolConfig
}

ConfigurableTool extends Tool with self-describing configuration. Implement this interface to provide annotation metadata for VSCode extension and CLI integration without requiring a separate devgen.toml file.

type CursorAdapter added in v0.3.3

type CursorAdapter struct{}

CursorAdapter transforms rules for Cursor AI assistant. Cursor uses YAML frontmatter with 'description', 'globs', and 'alwaysApply' fields, similar to CodeBuddy but with .mdc file extension.

Frontmatter format:

---
description: Brief description of the rule
globs: **/*.go, **/devgen.toml
alwaysApply: false
---

func (*CursorAdapter) Name added in v0.3.3

func (c *CursorAdapter) Name() string

Name returns "cursor".

func (*CursorAdapter) OutputDir added in v0.3.3

func (c *CursorAdapter) OutputDir() string

OutputDir returns ".cursor/rules".

func (*CursorAdapter) Transform added in v0.3.3

func (c *CursorAdapter) Transform(rule Rule) (string, string, error)

Transform converts a Rule to Cursor format with YAML frontmatter. It maps Rule fields directly to Cursor's frontmatter format. Note: Cursor uses .mdc extension instead of .md.

type Diagnostic added in v0.2.1

type Diagnostic struct {
	Severity DiagnosticSeverity `json:"severity"`
	Message  string             `json:"message"`
	File     string             `json:"file"`
	Line     int                `json:"line"`
	Column   int                `json:"column"`
	EndLine  int                `json:"endLine,omitempty"`
	EndCol   int                `json:"endColumn,omitempty"`
	Tool     string             `json:"tool"`
	Code     string             `json:"code,omitempty"` // e.g., "E001"
}

Diagnostic represents a single error or warning with source location. Used for reporting validation errors that can be displayed in IDEs.

func NewDiagnostic added in v0.2.1

func NewDiagnostic(severity DiagnosticSeverity, tool, code, message string, pos token.Position) Diagnostic

NewDiagnostic creates a new diagnostic from a token.Position.

type DiagnosticCollector added in v0.2.1

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

DiagnosticCollector provides a fluent API for collecting diagnostics. It simplifies validation code by providing chainable methods.

func NewDiagnosticCollector added in v0.2.1

func NewDiagnosticCollector(tool string) *DiagnosticCollector

NewDiagnosticCollector creates a new collector for the given tool.

func (*DiagnosticCollector) Collect added in v0.2.1

func (c *DiagnosticCollector) Collect() []Diagnostic

Collect returns all collected diagnostics.

func (*DiagnosticCollector) Error added in v0.2.1

func (c *DiagnosticCollector) Error(code, message string, pos token.Position) *DiagnosticCollector

Error adds an error diagnostic.

func (*DiagnosticCollector) Errorf added in v0.2.1

func (c *DiagnosticCollector) Errorf(code string, pos token.Position, format string, args ...any) *DiagnosticCollector

Errorf adds an error diagnostic with formatted message.

func (*DiagnosticCollector) HasErrors added in v0.2.1

func (c *DiagnosticCollector) HasErrors() bool

HasErrors returns true if any error diagnostics were collected.

func (*DiagnosticCollector) Merge added in v0.2.1

Merge adds diagnostics from another collector.

func (*DiagnosticCollector) MergeSlice added in v0.2.1

func (c *DiagnosticCollector) MergeSlice(diagnostics []Diagnostic) *DiagnosticCollector

MergeSlice adds diagnostics from a slice.

func (*DiagnosticCollector) Warning added in v0.2.1

func (c *DiagnosticCollector) Warning(code, message string, pos token.Position) *DiagnosticCollector

Warning adds a warning diagnostic.

func (*DiagnosticCollector) Warningf added in v0.2.1

func (c *DiagnosticCollector) Warningf(
	code string,
	pos token.Position,
	format string,
	args ...any,
) *DiagnosticCollector

Warningf adds a warning diagnostic with formatted message.

type DiagnosticSeverity added in v0.2.1

type DiagnosticSeverity string

DiagnosticSeverity represents the severity of a diagnostic.

const (
	DiagnosticError   DiagnosticSeverity = "error"
	DiagnosticWarning DiagnosticSeverity = "warning"
	DiagnosticInfo    DiagnosticSeverity = "info"
)

type DryRunResult added in v0.2.1

type DryRunResult struct {
	Success     bool              `json:"success"`
	Files       map[string]string `json:"files,omitempty"` // filename -> content preview
	Diagnostics []Diagnostic      `json:"diagnostics,omitempty"`
	Stats       DryRunStats       `json:"stats"`
}

DryRunResult contains the result of a dry-run execution.

func (*DryRunResult) AddDiagnostic added in v0.2.1

func (r *DryRunResult) AddDiagnostic(d Diagnostic)

AddDiagnostic adds a diagnostic to the result and updates stats.

func (*DryRunResult) AddError added in v0.2.1

func (r *DryRunResult) AddError(tool, code, message string, pos token.Position)

AddError is a convenience method to add an error diagnostic.

func (*DryRunResult) AddWarning added in v0.2.1

func (r *DryRunResult) AddWarning(tool, code, message string, pos token.Position)

AddWarning is a convenience method to add a warning diagnostic.

type DryRunStats added in v0.2.1

type DryRunStats struct {
	PackagesLoaded int `json:"packagesLoaded"`
	FilesGenerated int `json:"filesGenerated"`
	ErrorCount     int `json:"errorCount"`
	WarningCount   int `json:"warningCount"`
}

DryRunStats contains statistics from a dry-run execution.

type Enum

type Enum struct {
	Name           string
	Doc            string
	Pkg            *Package
	Values         []*EnumValue
	UnderlyingType string // e.g., "int", "string", "int64"
}

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 // declared type (e.g., "Email", "*User", "[]string")
	UnderlyingType string // underlying type (e.g., "string", "*struct", "[]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) IncludeTests added in v0.3.1

func (g *Generator) IncludeTests() bool

IncludeTests returns whether tools should generate *_test.go 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 KiroAdapter added in v0.3.3

type KiroAdapter struct{}

KiroAdapter transforms rules for Kiro AI assistant. Kiro uses YAML frontmatter with 'inclusion' and 'fileMatchPattern' fields.

Frontmatter format:

---
inclusion: fileMatch | always
fileMatchPattern: ['**/*.go', '**/devgen.toml']
---

Inclusion types:

  • "always": Rule is always included in context
  • "fileMatch": Rule is included when files match fileMatchPattern

func (*KiroAdapter) Name added in v0.3.3

func (k *KiroAdapter) Name() string

Name returns "kiro".

func (*KiroAdapter) OutputDir added in v0.3.3

func (k *KiroAdapter) OutputDir() string

OutputDir returns ".kiro/steering".

func (*KiroAdapter) Transform added in v0.3.3

func (k *KiroAdapter) Transform(rule Rule) (string, string, error)

Transform converts a Rule to Kiro format with YAML frontmatter. It determines the inclusion type based on AlwaysApply and formats the Globs as a YAML array for fileMatchPattern.

type LSPConfig added in v0.2.0

type LSPConfig struct {
	// Enabled indicates whether LSP integration is enabled.
	Enabled bool `toml:"enabled"`

	// Provider is the LSP provider (e.g., "gopls").
	Provider string `toml:"provider"`

	// Feature is the LSP feature type: "method", "type", "symbol".
	Feature string `toml:"feature"`

	// Signature is the required method signature (e.g., "func() error").
	Signature string `toml:"signature"`

	// ResolveFrom specifies where to find the type: "fieldType", "receiverType".
	ResolveFrom string `toml:"resolveFrom"`
}

LSPConfig defines LSP integration for an annotation.

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) SetNoColor added in v0.3.0

func (l *Logger) SetNoColor(noColor bool) *Logger

SetNoColor disables color output.

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

	// IncludeTests when true, tools should also generate *_test.go files.
	// Tools can check this option via Generator.IncludeTests() method.
	IncludeTests 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 PluginConfig added in v0.2.0

type PluginConfig struct {
	// Name is the plugin/tool name (e.g., "customgen").
	Name string `toml:"name"`

	// Path is the path to the plugin.
	// For "source" type: Go package directory path
	// For "plugin" type: path to .so file
	Path string `toml:"path"`

	// Type specifies how to load the plugin.
	// - "source": compile Go source code at runtime (default)
	// - "plugin": load as Go plugin (.so)
	Type PluginType `toml:"type"`
}

PluginConfig defines an external plugin to load.

type PluginLoader added in v0.2.0

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

PluginLoader loads and manages external tool plugins.

func NewPluginLoader added in v0.2.0

func NewPluginLoader(cacheDir string) *PluginLoader

NewPluginLoader creates a new plugin loader. cacheDir is used to store compiled plugins; if empty, uses system temp dir.

func (*PluginLoader) CleanCache added in v0.2.0

func (pl *PluginLoader) CleanCache(maxAge time.Duration) error

CleanCache removes old cached plugins.

func (*PluginLoader) LoadPlugin added in v0.2.0

func (pl *PluginLoader) LoadPlugin(ctx context.Context, cfg PluginConfig) (Tool, error)

LoadPlugin loads a plugin based on its configuration.

func (*PluginLoader) LoadPlugins added in v0.2.0

func (pl *PluginLoader) LoadPlugins(ctx context.Context, cfg *Config) ([]Tool, error)

LoadPlugins loads all plugins from the configuration.

type PluginType added in v0.2.0

type PluginType string

PluginType defines how a plugin is loaded.

const (
	// PluginTypeSource compiles Go source code at runtime.
	PluginTypeSource PluginType = "source"

	// PluginTypePlugin loads a pre-compiled Go plugin (.so).
	PluginTypePlugin PluginType = "plugin"
)

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 Rule added in v0.3.0

type Rule struct {
	// Name is the rule file name (without extension).
	// Example: "enumgen", "validategen-basics"
	Name string

	// Description is a short description of what this rule covers.
	// Used by AI agents to decide whether to include this rule.
	// Example: "Go enum code generation with enumgen"
	Description string

	// Globs specifies file patterns that trigger this rule.
	// When files matching these patterns are referenced, the rule is auto-attached.
	// Example: []string{"*.go", "**/*_enum.go"}
	// Empty means the rule won't be auto-attached by file patterns.
	Globs []string

	// AlwaysApply indicates whether this rule should always be included.
	// If true, the rule is always in context (like Cursor's "Always" type).
	// If false, the rule is included based on Globs or manual reference.
	AlwaysApply bool

	// Content is the actual rule content in Markdown format.
	// This should be detailed, step-by-step documentation with examples.
	// Write it as if the reader knows nothing - be explicit and thorough.
	Content string
}

Rule represents an AI rule configuration. This structure is designed to be compatible with multiple AI agents: - CodeBuddy: .codebuddy/rules/*.mdc - Cursor: .cursor/rules/*.mdc - Kiro: .kiro/steering/*.md

func LoadRuleFromFile added in v0.3.4

func LoadRuleFromFile(path string) (Rule, error)

LoadRuleFromFile loads a single rule from a markdown file with YAML frontmatter.

func LoadRulesFromDir added in v0.3.4

func LoadRulesFromDir(dir string) ([]Rule, error)

LoadRulesFromDir loads all rule files from a directory. Rule files must be .md files with YAML frontmatter.

type RuleFrontmatter added in v0.3.4

type RuleFrontmatter struct {
	Description string   `yaml:"description"`
	Globs       []string `yaml:"globs"`
	AlwaysApply bool     `yaml:"alwaysApply"`
}

RuleFrontmatter represents the YAML frontmatter of a rule file.

type RuleTool added in v0.3.0

type RuleTool interface {
	Tool

	// Rules returns the AI rules for this tool.
	// Each rule should be detailed, step-by-step documentation
	// with plenty of examples to help AI assistants understand
	// how to use this tool correctly.
	Rules() []Rule
}

RuleTool extends Tool with AI rules generation capability. Implement this interface to provide AI-friendly documentation that can be used by AI coding assistants (CodeBuddy, Cursor, Kiro, etc.)

type RulesConfig added in v0.3.4

type RulesConfig struct {
	// SourceDir is the directory containing project-level rule files.
	// If not set, project rules will not be loaded.
	SourceDir string `toml:"source_dir"`

	// IncludeBuiltin indicates whether to include devgen's built-in rules.
	// Default: true
	IncludeBuiltin *bool `toml:"include_builtin"`
}

RulesConfig defines AI rules generation configuration.

func (*RulesConfig) GetSourceDir added in v0.3.4

func (rc *RulesConfig) GetSourceDir() string

GetSourceDir returns the configured source directory.

func (*RulesConfig) HasSourceDir added in v0.3.4

func (rc *RulesConfig) HasSourceDir() bool

HasSourceDir returns true if a source directory is explicitly configured.

func (*RulesConfig) ShouldIncludeBuiltin added in v0.3.4

func (rc *RulesConfig) ShouldIncludeBuiltin() bool

ShouldIncludeBuiltin returns whether to include built-in rules, defaulting to true.

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 ToolConfig added in v0.2.0

type ToolConfig struct {
	// OutputSuffix is the suffix for generated files (e.g., "_enum.go").
	OutputSuffix string `toml:"output_suffix"`

	// Annotations defines the annotations supported by this tool.
	Annotations []AnnotationConfig `toml:"annotations"`
}

ToolConfig defines configuration for a specific tool.

func GetToolConfig added in v0.2.0

func GetToolConfig(t Tool) ToolConfig

GetToolConfig extracts ToolConfig from a Tool. If the tool implements ConfigurableTool, returns its Config(). Otherwise returns an empty ToolConfig.

func (*ToolConfig) ToVSCodeConfig added in v0.2.0

func (tc *ToolConfig) ToVSCodeConfig() map[string]any

ToVSCodeConfig converts the tool configuration to VSCode extension format.

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.

type ValidatableTool added in v0.2.1

type ValidatableTool interface {
	Tool

	// Validate checks for errors without generating files.
	// Returns diagnostics (errors/warnings) found during validation.
	// This is called in dry-run mode to provide IDE integration.
	Validate(gen *Generator, log *Logger) []Diagnostic
}

ValidatableTool extends Tool with validation capability for dry-run mode. Implement this interface to provide detailed diagnostics (errors/warnings) that can be displayed in IDEs without generating files.

Jump to

Keyboard shortcuts

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