orchestrator

package
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2026 License: MIT Imports: 22 Imported by: 0

README

GoRefactor Orchestration System

The orchestration system allows you to define refactoring operations in JSON files that are resilient to underlying code changes. This makes refactoring operations more robust and less likely to break when the codebase evolves.

See also the root README.md (CLI overview) and ORCHESTRATION_SYSTEM.md (full schema and examples).

Key Features

  • Resilient Targeting: Use semantic information instead of line numbers to locate code targets
  • Fallback Strategies: Define what to do when targets can't be found
  • Conditional Execution: Only execute operations when certain conditions are met
  • Comprehensive Reporting: Detailed execution results with statistics
  • Template System: Generate JSON templates to get started quickly

Quick Start

1. Generate Templates
# Generate all available templates
./gorefactor generate-templates ./templates

# This creates:
# - basic_plan_template.json
# - extract_method_template.json
# - inline_method_template.json
# - rename_variable_template.json
# - move_method_template.json
# - comprehensive_example.json
2. Create a Refactoring Plan

Edit one of the generated templates or create your own JSON file:

{
  "version": "1.0",
  "name": "my_refactoring_plan",
  "description": "Extract validation logic into separate methods",
  "created": "2024-01-15T10:00:00Z",
  "author": "Developer",
  "operations": [
    {
      "type": "extract_method",
      "description": "Extract user validation logic",
      "file": "user_service.go",
      "target": {
        "functionName": "CreateUser",
        "codePattern": "if err != nil",
        "variableNames": ["user", "err"]
      },
      "parameters": {
        "methodName": "validateUserInput"
      }
    }
  ]
}
3. Execute the Plan
# Execute the plan and output results to stdout
./gorefactor orchestrate my_plan.json

# Execute the plan and save results to a file
./gorefactor orchestrate my_plan.json results.json

Targeting Strategies

1. Line-based Targeting (Traditional)
{
  "target": {
    "startLine": 45,
    "endLine": 67
  }
}

Pros: Precise targeting Cons: Breaks when code changes

2. Function-based Targeting
{
  "target": {
    "functionName": "CreateUser"
  }
}

Pros: Resilient to code changes within the function Cons: Less precise

3. Method-based Targeting
{
  "target": {
    "methodName": "Validate",
    "receiverType": "User"
  }
}

Pros: Targets specific methods on specific types Cons: Requires exact method and receiver names

4. Pattern-based Targeting
{
  "target": {
    "functionName": "CreateUser",
    "codePattern": "if err != nil"
  }
}

Pros: Finds code by content patterns Cons: Pattern must be unique enough

5. Variable-based Targeting
{
  "target": {
    "functionName": "ProcessData",
    "variableNames": ["user", "config", "result"]
  }
}

Pros: Finds code by variable usage Cons: Variables must be distinctive

6. Call-based Targeting
{
  "target": {
    "functionName": "LoadConfig",
    "functionCalls": ["viper.ReadInConfig", "viper.Unmarshal"]
  }
}

Pros: Finds code by function calls Cons: Function calls must be distinctive

7. Combining semantic fields

Prefer combining functionName / codePattern / variableNames / functionCalls rather than context patterns that are not scored.

{
  "target": {
    "functionName": "HandleRequest",
    "codePattern": "log.Info(",
    "variableNames": ["response"]
  }
}

Pros: Uses multiple scored signals Cons: Over-specific combinations can miss after refactors

Fallback Strategies

Skip Operation
{
  "fallback": {
    "type": "skip",
    "description": "Skip if target not found"
  }
}
Use Default Target
{
  "fallback": {
    "type": "use_default",
    "description": "Use the first function if target not found"
  }
}

Conditions

Conditions allow you to only execute operations when certain criteria are met:

{
  "conditions": [
    {
      "type": "complexity",
      "property": "controlStructures",
      "value": 2,
      "operator": "gte"
    },
    {
      "type": "complexity",
      "property": "statementCount",
      "value": 5,
      "operator": "gte"
    }
  ]
}
Available Condition Types
  • complexity: Check code complexity metrics
  • statementCount: Check number of statements
  • controlStructures: Check number of control structures
  • errorHandlingPaths: Check number of error handling paths
  • returnCount: Check number of return statements
Available Operators
  • eq: Equal to
  • ne: Not equal to
  • gt: Greater than
  • gte: Greater than or equal to
  • lt: Less than
  • lte: Less than or equal to
  • contains: Contains substring
  • regex: Matches regex pattern

Operation Types

1. Extract Method
{
  "type": "extract_method",
  "description": "Extract a code block into a new method",
  "file": "service.go",
  "target": {
    "functionName": "ProcessData"
  },
  "parameters": {
    "methodName": "validateInput"
  }
}
2. Inline Method
{
  "type": "inline_method",
  "description": "Inline a method call",
  "file": "service.go",
  "target": {
    "functionName": "ProcessData",
    "codePattern": "validateInput("
  },
  "parameters": {
    "methodName": "validateInput"
  }
}
3. Rename Variable
{
  "type": "rename_variable",
  "description": "Rename a variable",
  "file": "service.go",
  "target": {
    "functionName": "ProcessData",
    "variableNames": ["oldName"]
  },
  "parameters": {
    "oldName": "oldVariableName",
    "newName": "newVariableName"
  }
}
4. Move Method
{
  "type": "move_method",
  "description": "Move a method to a different receiver type",
  "file": "user.go",
  "target": {
    "methodName": "Validate",
    "receiverType": "User"
  },
  "parameters": {
    "newReceiverType": "UserValidator",
    "newFile": "validator.go"
  }
}

Execution Results

The orchestrator provides detailed execution results:

{
  "planName": "my_refactoring_plan",
  "executed": "2024-01-15T10:30:00Z",
  "success": true,
  "operations": [
    {
      "operation": { /* operation details */ },
      "success": true,
      "message": "Operation completed successfully",
      "applied": true,
      "fallbackUsed": false,
      "changes": [
        {
          "type": "extract_method",
          "file": "service.go",
          "startLine": 45,
          "endLine": 67,
          "description": "Extracted method 'validateInput'",
          "newCode": "Method 'validateInput' extracted with parameters: [user, config]"
        }
      ]
    }
  ],
  "statistics": {
    "totalOperations": 1,
    "successfulOperations": 1,
    "failedOperations": 0,
    "skippedOperations": 0,
    "fallbackUsed": 0,
    "totalChanges": 1
  }
}

Best Practices

1. Use Semantic Targeting

Prefer semantic targeting over line-based targeting:

// Good - resilient to code changes
{
  "target": {
    "functionName": "CreateUser",
    "codePattern": "if err != nil"
  }
}

// Avoid - breaks when code changes
{
  "target": {
    "startLine": 45,
    "endLine": 67
  }
}
2. Combine Multiple Targeting Strategies

Use multiple targeting strategies for better accuracy:

{
  "target": {
    "functionName": "ProcessData",
    "codePattern": "if err != nil",
    "variableNames": ["data", "err"],
    "functionCalls": ["validate", "save"]
  }
}
3. Always Include Fallback Strategies
{
  "fallback": {
    "type": "skip",
    "description": "Skip if target not found"
  }
}
4. Use Conditions for Safety
{
  "conditions": [
    {
      "type": "complexity",
      "property": "controlStructures",
      "value": 2,
      "operator": "gte"
    }
  ]
}
5. Test Plans on Sample Code

Always test your plans on sample code before running them on production code.

Advanced Examples

Complex Multi-Operation Plan
{
  "version": "1.0",
  "name": "api_refactoring",
  "description": "Comprehensive API refactoring",
  "operations": [
    {
      "type": "extract_method",
      "description": "Extract error handling",
      "file": "api/handlers.go",
      "target": {
        "functionName": "handleRequest",
        "codePattern": "if err != nil {"
      },
      "parameters": {
        "methodName": "handleError"
      },
      "conditions": [
        {
          "type": "complexity",
          "property": "errorHandlingPaths",
          "value": 1,
          "operator": "gte"
        }
      ]
    },
    {
      "type": "extract_method",
      "description": "Extract validation logic",
      "file": "models/user.go",
      "target": {
        "methodName": "Validate",
        "receiverType": "User",
        "variableNames": ["user", "errors"]
      },
      "parameters": {
        "methodName": "validateUserData"
      },
      "fallback": {
        "type": "skip"
      }
    }
  ]
}
Conditional Refactoring
{
  "version": "1.0",
  "name": "conditional_refactoring",
  "description": "Only refactor complex functions",
  "operations": [
    {
      "type": "extract_method",
      "description": "Extract complex logic",
      "file": "service.go",
      "target": {
        "functionName": "ProcessComplexData"
      },
      "parameters": {
        "methodName": "processDataStep1"
      },
      "conditions": [
        {
          "type": "complexity",
          "property": "statementCount",
          "value": 10,
          "operator": "gte"
        },
        {
          "type": "complexity",
          "property": "controlStructures",
          "value": 3,
          "operator": "gte"
        }
      ]
    }
  ]
}

Troubleshooting

Common Issues
  1. Target not found: Use more specific targeting or add fallback strategies
  2. Operation fails: Check that the target file exists and is valid Go code
  3. Unexpected results: Review the execution results and adjust targeting
Debug Mode

Add debug information to your plans:

{
  "metadata": {
    "debug": true,
    "verbose": true
  }
}

Integration with CI/CD

You can integrate refactoring plans into your CI/CD pipeline:

# GitHub Actions example
- name: Run Refactoring Plan
  run: |
    ./gorefactor orchestrate refactoring_plan.json results.json
    if [ $? -ne 0 ]; then
      echo "Refactoring failed"
      exit 1
    fi

This system provides a robust, resilient way to orchestrate refactoring operations that can survive code changes and provide detailed feedback about what was executed.

Documentation

Index

Constants

View Source
const ReceiverNone = "-"

ReceiverNone is the TargetSpecification.ReceiverType value that restricts matching to plain functions (no receiver). It disambiguates a top-level function from a method of the same name.

Variables

View Source
var ErrFileNotFound = fmt.Errorf("file not found")

ErrFileNotFound indicates file doesn't exist

Functions

func DropJournalEntry added in v0.5.0

func DropJournalEntry(id string) error

DropJournalEntry removes an entry (and its snapshots) without restoring files. Used when the caller has already rolled back the operation.

func EndBatch added in v0.12.0

func EndBatch()

EndBatch clears batch mode. Safe to defer and safe to call when no batch is active.

func FormatDryRunDiff

func FormatDryRunDiff(diff *FileDiff) string

FormatDryRunDiff returns a colorized diff representation

func FormatImports

func FormatImports(path string) error

FormatImports is the exported version of formatImports for use by callers outside the orchestrator package (e.g. the top-level format command).

func KnownOperationTypes added in v0.12.0

func KnownOperationTypes() []string

KnownOperationTypes returns every operation type a plan can currently execute: the built-in dispatch set plus any registered external handlers.

func ReceiverTypeName added in v0.12.0

func ReceiverTypeName(fn *ast.FuncDecl) string

receiverTypeName returns the receiver type name of a method declaration ("" for plain functions). Pointer receivers are reported without the '*'; generic receivers without their type arguments.

func RegisterExternalHandler added in v0.12.0

func RegisterExternalHandler(opType string, h ExternalOperationHandler)

RegisterExternalHandler wires an operation type to an external engine. Init-time wiring only; not safe for concurrent registration.

func SaveDryRunReport

func SaveDryRunReport(result *DryRunResult, outputPath string) error

SaveDryRunReport saves a dry-run report to a file

Types

type Batch added in v0.12.0

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

Batch is the journal's transaction mode. It accumulates the pre-mutation state of every file touched across a group of operations so the whole group commits as one journal entry and rolls back as one unit. While a batch is active (BeginBatch/EndBatch), RecordOperation folds each operation into the batch instead of writing a per-operation journal entry — this is how `txn` turns many mutation commands into a single undo unit without a second snapshot system.

func BeginBatch added in v0.12.0

func BeginBatch() (*Batch, error)

BeginBatch starts journal batch mode and returns the active batch. It errors if a batch is already active — batches do not nest. Callers must pair it with EndBatch (typically deferred).

func (*Batch) Commit added in v0.12.0

func (b *Batch) Commit(command, detail string) (*JournalEntry, error)

Commit writes the whole batch as a single journal entry. It writes directly (bypassing the active-batch redirect) so it can run while the batch is still active.

func (*Batch) Empty added in v0.12.0

func (b *Batch) Empty() bool

Empty reports whether the batch captured no files.

func (*Batch) Rollback added in v0.12.0

func (b *Batch) Rollback()

Rollback restores every touched file to its pre-batch state and removes files the batch created.

func (*Batch) Touched added in v0.12.0

func (b *Batch) Touched() []string

Touched returns every path the batch modified or created, sorted.

type CallSiteRef added in v0.5.0

type CallSiteRef struct {
	File string
	Line int
	Pkg  string
}

CallSiteRef is a file:line reference to a call of the moved function.

func (CallSiteRef) String added in v0.5.0

func (c CallSiteRef) String() string

type CodeChange

type CodeChange struct {
	Type        string `json:"type"`
	File        string `json:"file"`
	StartLine   int    `json:"startLine"`
	EndLine     int    `json:"endLine"`
	Description string `json:"description"`
	OldCode     string `json:"oldCode,omitempty"`
	NewCode     string `json:"newCode,omitempty"`
}

CodeChange represents a specific change made to the code.

type CodeInserter

type CodeInserter struct{}

CodeInserter handles inserting new code snippets into existing Go files

func NewCodeInserter

func NewCodeInserter() *CodeInserter

NewCodeInserter creates a new code inserter instance

func (*CodeInserter) FindFunction

func (ci *CodeInserter) FindFunction(node *ast.File, functionName, methodName, receiverType string) *ast.FuncDecl

FindFunction is the exported version of findFunction for callers outside this package.

func (*CodeInserter) InsertCode

func (ci *CodeInserter) InsertCode(filePath string, location *InsertionLocation, codeSnippet string) (*InsertionResult, error)

func (*CodeInserter) RemoveCodeBlock

func (ci *CodeInserter) RemoveCodeBlock(filePath string, location *InsertionLocation, codePattern string) (*InsertionResult, error)

func (*CodeInserter) ReplaceCodeBlock

func (ci *CodeInserter) ReplaceCodeBlock(filePath string, location *InsertionLocation, codePattern string, replacementCode string) (*InsertionResult, error)

type Condition

type Condition struct {
	Type     string      `json:"type"`
	Property string      `json:"property"`
	Value    interface{} `json:"value"`
	Operator string      `json:"operator,omitempty"` // eq, ne, gt, lt, contains, regex
}

Condition represents a condition that must be met for the operation.

type CrossPackageMoveReport added in v0.5.0

type CrossPackageMoveReport struct {
	SourceFile       string   `json:"sourceFile"`
	DestFile         string   `json:"destFile"`
	FuncName         string   `json:"funcName"`
	SourcePackage    string   `json:"sourcePackage"`
	DestPackage      string   `json:"destPackage"`
	SourceImportPath string   `json:"sourceImportPath"`
	DestImportPath   string   `json:"destImportPath"`
	QualifiedSymbols []string `json:"qualifiedSymbols,omitempty"` // source symbols qualified inside the moved code
	RewrittenFiles   []string `json:"rewrittenFiles,omitempty"`   // call-site files updated
	SourceStartLine  int      `json:"sourceStartLine"`
	SourceEndLine    int      `json:"sourceEndLine"`
	DeclCode         string   `json:"-"`
}

CrossPackageMoveReport describes what a cross-package move did.

type CrossPackageOperationHandler

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

CrossPackageOperationHandler manages cross-package refactoring operations

func NewCrossPackageOperationHandler

func NewCrossPackageOperationHandler() *CrossPackageOperationHandler

NewCrossPackageOperationHandler creates a new handler

func (*CrossPackageOperationHandler) CanMoveSafely

func (h *CrossPackageOperationHandler) CanMoveSafely(
	sourceFile, destFile, funcName string) (bool, []string, error)

CanMoveSafely checks if a function can be safely moved to another package

func (*CrossPackageOperationHandler) MoveAcrossPackages

func (h *CrossPackageOperationHandler) MoveAcrossPackages(sourceFile, destFile, funcName string) error

MoveAcrossPackages moves a top-level function from one package to another, qualifying references it keeps into the source package, rewriting call sites in the source package and across the module, and fixing imports on every touched file. It fails loudly — with the affected call sites listed — whenever the move would break the build.

type DryRunOperationResult

type DryRunOperationResult struct {
	Operation *RefactoringOperation
	Changes   []*FileDiff
	Success   bool
	Error     string
}

DryRunOperationResult shows what would change for a single operation

type DryRunResult

type DryRunResult struct {
	Plan       *RefactoringPlan
	Operations []*DryRunOperationResult
	Summary    string
}

DryRunResult represents the preview of changes without applying them

type ExecutionResult

type ExecutionResult struct {
	PlanName   string               `json:"planName"`
	Executed   time.Time            `json:"executed"`
	Success    bool                 `json:"success"`
	Operations []*OperationResult   `json:"operations"`
	Errors     []string             `json:"errors,omitempty"`
	Warnings   []string             `json:"warnings,omitempty"`
	Statistics *ExecutionStatistics `json:"statistics,omitempty"`
}

ExecutionResult represents the result of executing a refactoring plan.

type ExecutionStatistics

type ExecutionStatistics struct {
	TotalOperations      int `json:"totalOperations"`
	SuccessfulOperations int `json:"successfulOperations"`
	FailedOperations     int `json:"failedOperations"`
	SkippedOperations    int `json:"skippedOperations"`
	FallbackUsed         int `json:"fallbackUsed"`
	TotalChanges         int `json:"totalChanges"`
}

ExecutionStatistics provides metrics about the execution.

type ExternalOperationHandler added in v0.12.0

type ExternalOperationHandler func(op *RefactoringOperation, target *TargetLocation) ([]*CodeChange, error)

ExternalOperationHandler executes a plan operation whose engine lives outside this package (e.g. the CLI's type-aware extractor, which needs go/packages and lives in cmd/gorefactor). The handler receives the operation and its resolved semantic target (nil when the operation had no target spec) and returns the changes it made.

This registry exists because plan-level extract_method/inline_method were advertised (templates, CLAUDE.md) but not dispatchable: the engines were CLI-only, so `orchestrate` failed with "unknown operation type" on the tool's own generated templates. Handlers are wired at init time by the binary that owns the engine.

type FallbackStrategy

type FallbackStrategy struct {
	Type        string                 `json:"type"`
	Description string                 `json:"description"`
	Parameters  map[string]interface{} `json:"parameters,omitempty"`
}

FallbackStrategy defines what to do if the primary target cannot be found.

type FileDiff

type FileDiff struct {
	File      string
	OldCode   string
	NewCode   string
	StartLine int
	EndLine   int
	Summary   string
}

FileDiff represents the differences for a single file

type InsertionLocation

type InsertionLocation struct {
	Type         string `json:"type"` // "before_function", "after_function", "inside_function", "at_end", "at_beginning"
	FunctionName string `json:"functionName,omitempty"`
	MethodName   string `json:"methodName,omitempty"`
	ReceiverType string `json:"receiverType,omitempty"`
	LineNumber   int    `json:"lineNumber,omitempty"`
	CodePattern  string `json:"codePattern,omitempty"`
}

InsertionLocation defines where to insert new code

type InsertionResult

type InsertionResult struct {
	File         string `json:"file"`
	Location     string `json:"location"`
	StartLine    int    `json:"startLine"`
	EndLine      int    `json:"endLine"`
	Description  string `json:"description"`
	InsertedCode string `json:"insertedCode"`
}

InsertionResult represents the result of a code insertion

type JournalEntry added in v0.5.0

type JournalEntry struct {
	ID        string        `json:"id"`
	Command   string        `json:"command"`
	Detail    string        `json:"detail,omitempty"`
	Timestamp time.Time     `json:"timestamp"`
	Files     []JournalFile `json:"files"`
}

JournalEntry is one mutation recorded in .gorefactor/journal.json.

func LoadJournal added in v0.5.0

func LoadJournal() ([]JournalEntry, error)

LoadJournal returns all journaled operations, oldest first.

func RecordOperation added in v0.5.0

func RecordOperation(command, detail string, before map[string][]byte, created []string) (*JournalEntry, error)

RecordOperation snapshots the pre-mutation content of changed files and appends an entry to the journal. before maps path -> content as it was before the mutation; created lists files the operation newly created.

When a journal batch is active (see BeginBatch), the operation is folded into that batch instead — one journal entry is written for the whole batch on Commit — and this returns (nil, nil).

func UndoLast added in v0.5.0

func UndoLast() (*JournalEntry, int, error)

UndoLast restores exactly the most recent journaled operation and pops it from the journal. It returns the undone entry and the number of files restored or removed.

type JournalFile added in v0.5.0

type JournalFile struct {
	Path     string `json:"path"`
	Snapshot string `json:"snapshot,omitempty"`
	Created  bool   `json:"created,omitempty"`
}

JournalFile records one file touched by a journaled operation. Snapshot is the file name inside the operation's snapshot directory holding the pre-mutation content; Created marks files the operation created (undo removes them instead of restoring content).

type OperationResult

type OperationResult struct {
	Operation    *RefactoringOperation `json:"operation"`
	Success      bool                  `json:"success"`
	Message      string                `json:"message"`
	Applied      bool                  `json:"applied"`
	FallbackUsed bool                  `json:"fallbackUsed,omitempty"`
	Changes      []*CodeChange         `json:"changes,omitempty"`
	Error        string                `json:"error,omitempty"`
}

OperationResult represents the result of a single operation.

type Orchestrator

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

Orchestrator manages the execution of refactoring plans.

func NewOrchestrator

func NewOrchestrator() *Orchestrator

NewOrchestrator creates a new orchestrator instance

func (*Orchestrator) ExecuteOperations

func (o *Orchestrator) ExecuteOperations(ops []*RefactoringOperation) (*ExecutionResult, error)

func (*Orchestrator) ExecutePlan

func (o *Orchestrator) ExecutePlan(planName string) (*ExecutionResult, error)

ExecutePlan executes a refactoring plan. It never snapshots on its own: the mutation journal (RecordOperation / UndoLast) is the single undo system, and callers that want a plan run to be undoable journal it themselves (see orchestrate's journalPlanRun and the CLI mutation runner).

func (*Orchestrator) ExecutePlanDryRun

func (o *Orchestrator) ExecutePlanDryRun(planName string) (*DryRunResult, error)

ExecutePlanDryRun executes a plan in dry-run mode without writing files

func (*Orchestrator) LoadPlan

func (o *Orchestrator) LoadPlan(filePath string) (*RefactoringPlan, error)

LoadPlan loads a refactoring plan from a JSON file

func (*Orchestrator) RegisterPlan

func (o *Orchestrator) RegisterPlan(plan *RefactoringPlan) error

RegisterPlan registers a refactoring plan for execution

func (*Orchestrator) SaveResult

func (o *Orchestrator) SaveResult(result *ExecutionResult, filePath string) error

SaveResult saves an execution result to a JSON file

type PackageTestResult

type PackageTestResult struct {
	Package  string
	Passed   bool
	Tests    int
	Failures int
	Duration string
}

PackageTestResult represents test results for a package

type RefactoringOperation

type RefactoringOperation struct {
	Type        string                 `json:"type"`
	Description string                 `json:"description"`
	File        string                 `json:"file"`
	Target      *TargetSpecification   `json:"target"`
	Parameters  map[string]interface{} `json:"parameters,omitempty"`
	Conditions  []*Condition           `json:"conditions,omitempty"`
	Fallback    *FallbackStrategy      `json:"fallback,omitempty"`
}

RefactoringOperation represents a single refactoring operation.

type RefactoringPlan

type RefactoringPlan struct {
	Version     string                  `json:"version"`
	Name        string                  `json:"name"`
	Description string                  `json:"description"`
	Created     time.Time               `json:"created"`
	Author      string                  `json:"author,omitempty"`
	Operations  []*RefactoringOperation `json:"operations"`
	Metadata    map[string]interface{}  `json:"metadata,omitempty"`
}

RefactoringPlan represents a complete refactoring plan.

type TargetLocation

type TargetLocation struct {
	File      string `json:"file"`
	StartLine int    `json:"startLine"`
	EndLine   int    `json:"endLine"`
	Function  string `json:"function,omitempty"`
	Method    string `json:"method,omitempty"`
}

TargetLocation represents a location in the code

type TargetSpecification

type TargetSpecification struct {
	// Line-based targeting (traditional)
	StartLine *int `json:"startLine,omitempty"`
	EndLine   *int `json:"endLine,omitempty"`

	// Semantic targeting (resilient to code changes)
	FunctionName  string   `json:"functionName,omitempty"`
	MethodName    string   `json:"methodName,omitempty"`
	ReceiverType  string   `json:"receiverType,omitempty"`
	CodePattern   string   `json:"codePattern,omitempty"`
	VariableNames []string `json:"variableNames,omitempty"`
	FunctionCalls []string `json:"functionCalls,omitempty"`

	// Declaration-level targeting
	TypeName  string `json:"typeName,omitempty"`  // For type declarations
	ConstName string `json:"constName,omitempty"` // For const declarations
	VarName   string `json:"varName,omitempty"`   // For var declarations
}

TargetSpecification defines how to locate the target for refactoring. Strategies can be combined; the orchestrator scores candidates against every populated field (see targeting.go).

type TemplateGenerator

type TemplateGenerator struct{}

TemplateGenerator helps create JSON refactoring plans

func NewTemplateGenerator

func NewTemplateGenerator() *TemplateGenerator

NewTemplateGenerator creates a new template generator

func (*TemplateGenerator) GenerateAllTemplates

func (tg *TemplateGenerator) GenerateAllTemplates(outputDir string) error

GenerateAllTemplates generates all available templates

func (*TemplateGenerator) GenerateBasicTemplate

func (tg *TemplateGenerator) GenerateBasicTemplate(name, description string) *RefactoringPlan

GenerateBasicTemplate creates a basic refactoring plan template

func (*TemplateGenerator) GenerateExtractionTemplate

func (tg *TemplateGenerator) GenerateExtractionTemplate() *RefactoringOperation

GenerateExtractionTemplate creates a template for method extraction

func (*TemplateGenerator) GenerateInlineTemplate

func (tg *TemplateGenerator) GenerateInlineTemplate() *RefactoringOperation

GenerateInlineTemplate creates a template for method inlining

func (*TemplateGenerator) GenerateInsertCodeTemplate

func (tg *TemplateGenerator) GenerateInsertCodeTemplate() *RefactoringOperation

GenerateInsertCodeTemplate creates a template for code insertion

func (*TemplateGenerator) GenerateMoveTemplate

func (tg *TemplateGenerator) GenerateMoveTemplate() *RefactoringOperation

GenerateMoveTemplate creates a template for method moving

func (*TemplateGenerator) GenerateRenameTemplate

func (tg *TemplateGenerator) GenerateRenameTemplate() *RefactoringOperation

GenerateRenameTemplate creates a template for declaration renaming. It emits rename_declaration — the executable rename op — rather than the historical rename_variable, which no executor ever dispatched (a harness-integrity review finding: templates advertised ops that failed with "unknown operation type").

func (*TemplateGenerator) PrintTemplateHelp

func (tg *TemplateGenerator) PrintTemplateHelp()

PrintTemplateHelp prints help information about templates

func (*TemplateGenerator) SaveTemplate

func (tg *TemplateGenerator) SaveTemplate(template interface{}, filePath string) error

SaveTemplate saves a template to a JSON file

type TestResult

type TestResult struct {
	Success      bool
	Output       string
	ErrorOutput  string
	ExitCode     int
	TestsPassed  int
	TestsFailed  int
	Duration     string
	PackageTests map[string]PackageTestResult
}

TestResult represents test execution results

type TestRunner

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

TestRunner executes tests and reports results

func NewTestRunner

func NewTestRunner(workDir string) *TestRunner

NewTestRunner creates a new test runner

func (*TestRunner) RunTests

func (tr *TestRunner) RunTests() *TestResult

RunTests executes go test in the working directory

Jump to

Keyboard shortcuts

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