Help us shape the future of Go! Take the 2026 Go Developer Survey

edit

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Jul 28, 2025 License: AGPL-3.0 Imports: 15 Imported by: 0

README

File Editing System

This package provides advanced file editing capabilities for Matey, including:

Components

diff.go
  • SEARCH/REPLACE format parser inspired by Cline
  • Multi-level fallback matching strategies:
    • Exact string matching
    • Line-trimmed fallback matching
    • Block anchor matching (first/last line anchors)
  • Streaming diff application
  • Out-of-order replacement support
editor.go
  • File reading with encoding detection
  • Multi-edit operations (MultiEdit functionality)
  • Backup and rollback capabilities
  • Kubernetes ConfigMaps integration for persistence
  • File validation and safety checks
fallback.go
  • Smart matching algorithms for when exact string matches fail
  • Whitespace-tolerant line matching
  • Block anchor matching strategy
  • Fuzzy context matching as last resort
  • Matching confidence scoring

Features

  • Streaming Edits: Real-time diff application as AI generates content
  • Smart Fallbacks: Multiple strategies to handle text mismatches
  • Kubernetes Native: Integrates with existing K8s infrastructure
  • Safety First: Comprehensive validation and rollback capabilities

Usage

This package will be used by:

  • MCP tools for file editing
  • CLI commands for interactive editing
  • Chat interface for AI-driven file modifications

Documentation

Index

Constants

View Source
const (
	SearchBlockStart = "------- SEARCH"
	SearchBlockEnd   = "======="
	ReplaceBlockEnd  = "+++++++ REPLACE"
)

Diff markers inspired by Cline's format

Variables

View Source
var (
	SearchBlockStartRegex = regexp.MustCompile(`^[-]{3,}\s*SEARCH>?$`)
	SearchBlockEndRegex   = regexp.MustCompile(`^[=]{3,}$`)
	ReplaceBlockEndRegex  = regexp.MustCompile(`^[+]{3,}\s*REPLACE>?$`)

	// Legacy format support
	LegacySearchStartRegex = regexp.MustCompile(`^[<]{3,}\s*SEARCH>?$`)
	LegacyReplaceEndRegex  = regexp.MustCompile(`^[>]{3,}\s*REPLACE>?$`)
)

Alternative legacy markers for flexibility

View Source
var DefaultValidators = struct {
	Go         ValidationFunc
	JSON       ValidationFunc
	YAML       ValidationFunc
	Dockerfile ValidationFunc
}{
	Go: func(filePath, content string) error {
		if !strings.HasSuffix(filePath, ".go") {
			return nil
		}

		if !strings.Contains(content, "package ") {
			return fmt.Errorf("Go file must contain a package declaration")
		}
		return nil
	},

	JSON: func(filePath, content string) error {
		if !strings.HasSuffix(filePath, ".json") {
			return nil
		}
		var js json.RawMessage
		if err := json.Unmarshal([]byte(content), &js); err != nil {
			return fmt.Errorf("invalid JSON: %w", err)
		}
		return nil
	},

	YAML: func(filePath, content string) error {
		if !strings.HasSuffix(filePath, ".yaml") && !strings.HasSuffix(filePath, ".yml") {
			return nil
		}

		lines := strings.Split(content, "\n")
		for i, line := range lines {
			if strings.Contains(line, "\t") {
				return fmt.Errorf("YAML file contains tabs at line %d (use spaces)", i+1)
			}
		}
		return nil
	},

	Dockerfile: func(filePath, content string) error {
		if filepath.Base(filePath) != "Dockerfile" && !strings.HasSuffix(filePath, ".dockerfile") {
			return nil
		}
		if !strings.Contains(strings.ToUpper(content), "FROM ") {
			return fmt.Errorf("Dockerfile must contain a FROM instruction")
		}
		return nil
	},
}

DefaultValidators provides common validation functions

View Source
var MatchConfidenceThresholds = struct {
	Safe         float64 // Conservative threshold for automated application
	Interactive  float64 // Threshold for interactive approval
	Experimental float64 // Threshold for experimental/debugging
}{
	Safe:         0.9,
	Interactive:  0.7,
	Experimental: 0.5,
}

MatchConfidenceThresholds defines confidence thresholds for different use cases

Functions

This section is empty.

Types

type DiffFormat

type DiffFormat struct {
	SearchContent  string
	ReplaceContent string
	StartLine      int
	EndLine        int
}

DiffFormat defines the structure of a SEARCH/REPLACE diff block

type DiffOperation

type DiffOperation struct {
	Type       string // "search", "replace", "apply"
	Content    string
	LineNumber int
	Confidence float64 // 0-1, higher means more confident match
}

DiffOperation represents a single diff operation with its context

type DiffProcessor

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

DiffProcessor handles parsing and applying SEARCH/REPLACE format diffs

func NewDiffProcessor

func NewDiffProcessor(originalContent string) *DiffProcessor

NewDiffProcessor creates a new diff processor for the given original content

func (*DiffProcessor) ApplyDiff

func (dp *DiffProcessor) ApplyDiff() (string, error)

ApplyDiff applies all parsed diff blocks to the original content

func (*DiffProcessor) GetBlocks

func (dp *DiffProcessor) GetBlocks() []DiffFormat

GetBlocks returns the parsed diff blocks

func (*DiffProcessor) GetOperations

func (dp *DiffProcessor) GetOperations() []DiffOperation

GetOperations returns the diff operations

func (*DiffProcessor) ParseDiff

func (dp *DiffProcessor) ParseDiff(diffContent string, isFinal bool) error

ParseDiff parses SEARCH/REPLACE format diff content into structured blocks

type EditorConfig

type EditorConfig struct {
	BackupDir     string
	MaxBackups    int
	ValidateFunc  func(string, string) error
	K8sIntegrated bool
}

EditorConfig configures the FileEditor behavior

type FallbackMatcher

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

FallbackMatcher implements sophisticated matching strategies for diff application

func NewFallbackMatcher

func NewFallbackMatcher(content, searchContent string, startIndex int, config MatcherConfig) *FallbackMatcher

NewFallbackMatcher creates a new matcher with the given configuration

func (*FallbackMatcher) FindBestMatch

func (fm *FallbackMatcher) FindBestMatch() (*MatchResult, error)

FindBestMatch attempts to find the best match using all available strategies

type FileEdit

type FileEdit struct {
	FilePath   string `json:"file_path"`
	OldContent string `json:"old_content,omitempty"`
	NewContent string `json:"new_content"`
	Backup     string `json:"backup,omitempty"`
	Timestamp  int64  `json:"timestamp"`
	Applied    bool   `json:"applied"`
	Error      string `json:"error,omitempty"`
}

FileEdit represents a single file editing operation

type FileEditor

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

FileEditor handles file operations with backup, rollback, and validation

func NewFileEditor

func NewFileEditor(config EditorConfig) *FileEditor

NewFileEditor creates a new FileEditor with the given configuration

func (*FileEditor) ApplyDiff

func (fe *FileEditor) ApplyDiff(filePath string, diffContent string) (*FileEdit, error)

ApplyDiff applies a diff to a file using the DiffProcessor

func (*FileEditor) ApplyMultiEdit

func (fe *FileEditor) ApplyMultiEdit(operation MultiEditOperation) (*MultiEditOperation, error)

ApplyMultiEdit applies multiple edits as a single atomic operation

func (*FileEditor) CleanupBackups

func (fe *FileEditor) CleanupBackups(filePath string) error

CleanupBackups removes old backups beyond the max backup limit

func (*FileEditor) GetBackupHistory

func (fe *FileEditor) GetBackupHistory(filePath string) ([]string, error)

GetBackupHistory returns the backup history for a file

func (*FileEditor) ReadFile

func (fe *FileEditor) ReadFile(filePath string) (string, error)

ReadFile reads a file with automatic encoding detection

func (*FileEditor) RollbackEdit

func (fe *FileEditor) RollbackEdit(edit FileEdit) error

RollbackEdit rolls back a single edit operation

func (*FileEditor) RollbackMultiEdit

func (fe *FileEditor) RollbackMultiEdit(operation MultiEditOperation) error

RollbackMultiEdit rolls back a multi-edit operation

func (*FileEditor) WriteFile

func (fe *FileEditor) WriteFile(filePath string, content string) error

WriteFile writes content to a file with backup and validation

type MatchResult

type MatchResult struct {
	Strategy      MatchStrategy `json:"strategy"`
	StartIndex    int           `json:"start_index"`
	EndIndex      int           `json:"end_index"`
	Confidence    float64       `json:"confidence"`
	MatchedText   string        `json:"matched_text"`
	Context       string        `json:"context,omitempty"`
	Modifications []string      `json:"modifications,omitempty"`
}

MatchResult contains information about a successful match

type MatchStrategy

type MatchStrategy int

MatchStrategy represents different matching strategies for diff application

const (
	StrategyExact MatchStrategy = iota
	StrategyLineTrimmed
	StrategyBlockAnchor
	StrategyFuzzyContext
	StrategyLineNumber
	StrategyRegexPattern
)

type MatcherConfig

type MatcherConfig struct {
	MinConfidence float64 // Minimum confidence score (0.0-1.0)
	MaxDistance   int     // Maximum edit distance for fuzzy matching
	ContextLines  int     // Number of context lines to consider
	StrictMode    bool    // Whether to use strict matching rules
}

MatcherConfig configures the FallbackMatcher behavior

type MultiEditOperation

type MultiEditOperation struct {
	ID          string     `json:"id"`
	Description string     `json:"description"`
	Edits       []FileEdit `json:"edits"`
	Timestamp   int64      `json:"timestamp"`
	Applied     bool       `json:"applied"`
	Rollback    bool       `json:"rollback"`
}

MultiEditOperation represents a collection of related file edits

type ValidationFunc

type ValidationFunc func(filePath, content string) error

ValidationFunc is a type for content validation functions

func CombineValidators

func CombineValidators(validators ...ValidationFunc) ValidationFunc

CombineValidators combines multiple validation functions

Jump to

Keyboard shortcuts

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