utils

package
v0.8.3 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2025 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CapitalizeWords added in v0.5.0

func CapitalizeWords(s string) string

CapitalizeWords capitalizes the first letter of each word in a string.

func ClearLine added in v0.5.0

func ClearLine()

ClearLine clears the current line and moves cursor to beginning

func ClearScreen added in v0.5.0

func ClearScreen()

ClearScreen clears the entire screen

func ContextCancelledError added in v0.5.0

func ContextCancelledError(operation string) error

ContextCancelledError creates a context cancelled error

func CreateBackup added in v0.5.0

func CreateBackup(filePath string) error

CreateBackup creates a timestamped backup of a file. It reads the content of the file at filePath, and saves it to a backup directory (.ledit/backups) with a timestamped filename.

func DeadlineExceededError added in v0.5.0

func DeadlineExceededError(operation string) error

DeadlineExceededError creates a deadline exceeded error

func EstimateTokens added in v0.3.0

func EstimateTokens(text string) int

EstimateTokens provides a rough estimate of the number of tokens in a given text. This is a simple character-based estimation (e.g., 4 chars per token) and may not be accurate for all models or languages, but provides a general idea for prompt length management.

func ExtractJSON added in v0.5.0

func ExtractJSON(input string) (string, error)

ExtractJSON extracts JSON from any source (LLM responses, plain text, markdown, etc.) This is the primary JSON extraction function that handles all common scenarios: - Plain JSON objects/arrays - Markdown code blocks (```json, ```) - Multiple extraction strategies with fallbacks - Robust error handling and validation

func FileNotFoundError added in v0.5.0

func FileNotFoundError(path string) error

FileNotFoundError creates a file not found error

func FormatError added in v0.5.0

func FormatError(err error) string

FormatError formats an error for display

func FormatFileSize added in v0.5.0

func FormatFileSize(size int64) string

FormatFileSize converts a file size in bytes to a human-readable string (e.g., "1.2 MB", "345 KB").

func GenerateFileRevisionHash

func GenerateFileRevisionHash(filename, code string) string

GenerateFileRevisionHash generates a SHA256 hash for a file based on its name and code content.

func GenerateRequestHash

func GenerateRequestHash(instructions string) string

GenerateRequestHash generates a SHA256 hash for a given set of instructions.

func GetCurrentTimestamp added in v0.5.0

func GetCurrentTimestamp() int64

GetCurrentTimestamp returns the current timestamp

func GetTimestamp added in v0.3.0

func GetTimestamp() string

GetTimestamp returns a formatted timestamp string suitable for filenames.

func HandleError added in v0.5.0

func HandleError(ctx context.Context, err error, context string, enableRecovery bool) error

HandleError is a convenience function for handling errors globally

func HandleFatalError added in v0.5.0

func HandleFatalError(err error, context string)

HandleFatalError is a convenience function for handling fatal errors

func HandleValidationError added in v0.5.0

func HandleValidationError(err error, field string) error

HandleValidationError is a convenience function for validation errors

func HideCursor added in v0.5.0

func HideCursor()

HideCursor hides the terminal cursor

func InitErrorHandling added in v0.5.0

func InitErrorHandling(logger *Logger)

InitErrorHandling initializes the global error handling system

func InvalidArgumentError added in v0.5.0

func InvalidArgumentError(argument, reason string) error

InvalidArgumentError creates an invalid argument error

func IsCriticalError added in v0.5.0

func IsCriticalError(err error) bool

IsCriticalError checks if an error is critical

func IsEmptyString added in v0.5.0

func IsEmptyString(s string) bool

IsEmptyString checks if a string is empty.

func IsNetworkError added in v0.5.0

func IsNetworkError(err error) bool

IsNetworkError checks if an error is network-related

func IsValidFileExtension added in v0.5.0

func IsValidFileExtension(filename string, allowedExtensions []string) bool

IsValidFileExtension checks if the given filename has one of the allowed extensions. Extensions should be provided with a leading dot, e.g., ".go", ".txt".

func IsValidationError added in v0.5.0

func IsValidationError(err error) bool

IsValidationError checks if an error is validation-related

func LogAndContinue added in v0.5.0

func LogAndContinue(err error, ctx string)

LogAndContinue logs an error but continues execution

func LogAndExit added in v0.5.0

func LogAndExit(err error, ctx string)

LogAndExit logs an error and exits (for use in main functions)

func LogLLMResponse added in v0.3.0

func LogLLMResponse(filename, response string)

LogLLMResponse logs the LLM's response to a file in the .ledit/llm_responses directory.

func LogUserPrompt added in v0.3.0

func LogUserPrompt(prompt string)

LogUserPrompt logs the user's original prompt to a file in the .ledit/prompts directory.

func MoveCursor added in v0.5.0

func MoveCursor(row, col int)

MoveCursor moves the cursor to the specified position (1-based)

func NetworkTimeoutError added in v0.5.0

func NetworkTimeoutError(operation string, timeout int) error

NetworkTimeoutError creates a network timeout error

func PermissionDeniedError added in v0.5.0

func PermissionDeniedError(resource string) error

PermissionDeniedError creates a permission denied error

func RecoverableError added in v0.5.0

func RecoverableError(err error, message string) error

RecoverableError creates a recoverable error

func ResourceExhaustedError added in v0.5.0

func ResourceExhaustedError(resource string) error

ResourceExhaustedError creates a resource exhausted error

func RestoreCursorPosition added in v0.5.0

func RestoreCursorPosition()

RestoreCursorPosition restores the saved cursor position

func RetryableError added in v0.5.0

func RetryableError(err error, maxRetries int) error

RetryableError creates a retryable error

func SafeExecute added in v0.5.0

func SafeExecute(fn func() error, recoveryMsg string) (err error)

SafeExecute executes a function safely and handles any panics

func SafeGo added in v0.5.0

func SafeGo(fn func(), recoveryMsg string)

SafeGo starts a goroutine with panic recovery

func SaveCursorPosition added in v0.5.0

func SaveCursorPosition()

SaveCursorPosition saves the current cursor position

func ShowCursor added in v0.5.0

func ShowCursor()

ShowCursor shows the terminal cursor

func SplitTopLevelJSONObjects added in v0.5.0

func SplitTopLevelJSONObjects(s string) []string

SplitTopLevelJSONObjects splits a string containing multiple concatenated top-level JSON objects It properly handles string escaping and nested braces/brackets

func StringSliceEqual added in v0.3.0

func StringSliceEqual(a, b []string) bool

StringSliceEqual checks if two string slices are equal, ignoring order.

func TruncateString added in v0.5.0

func TruncateString(s string, maxLength int) string

TruncateString truncates a string to a specified maximum length, appending "..." if truncation occurs.

func UnrecoverableError added in v0.5.0

func UnrecoverableError(err error, message string) error

UnrecoverableError creates an unrecoverable error

func ValidateFileExists added in v0.5.0

func ValidateFileExists(path, name string) error

ValidateFileExists validates that a file exists

func ValidateJSONFields added in v0.5.0

func ValidateJSONFields(jsonStr string, requiredFields []string) error

ValidateJSONFields validates that a JSON string contains the required fields This is useful for ensuring API responses have expected structure

func ValidateNotEmpty added in v0.5.0

func ValidateNotEmpty(value, name string) error

ValidateNotEmpty validates that a string is not empty

func ValidateNotNil added in v0.5.0

func ValidateNotNil(value interface{}, name string) error

ValidateNotNil validates that a value is not nil

func ValidatePositive added in v0.5.0

func ValidatePositive(value int, name string) error

ValidatePositive validates that a number is positive

func ValidateRange added in v0.5.0

func ValidateRange(value, min, max int, name string) error

ValidateRange validates that a number is within a range

func WithErrorHandling added in v0.5.0

func WithErrorHandling(fn func() error, ctx string) error

WithErrorHandling wraps a function with error handling

func WrapError added in v0.5.0

func WrapError(err error, message string) error

WrapError wraps an error with additional context

func WrapErrorWithContext added in v0.5.0

func WrapErrorWithContext(err error, code, message string, severity ErrorSeverity, category ErrorCategory) error

WrapErrorWithContext wraps an error with structured context

Types

type CircuitBreakerStrategy added in v0.5.0

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

CircuitBreakerStrategy implements circuit breaker pattern

func NewCircuitBreakerStrategy added in v0.5.0

func NewCircuitBreakerStrategy(failureThreshold int, resetTimeout time.Duration) *CircuitBreakerStrategy

NewCircuitBreakerStrategy creates a new circuit breaker strategy

func (*CircuitBreakerStrategy) CanRecover added in v0.5.0

func (c *CircuitBreakerStrategy) CanRecover(err error) bool

CanRecover checks if the circuit breaker allows recovery

func (*CircuitBreakerStrategy) GetName added in v0.5.0

func (c *CircuitBreakerStrategy) GetName() string

GetName returns the strategy name

func (*CircuitBreakerStrategy) Recover added in v0.5.0

func (c *CircuitBreakerStrategy) Recover(ctx context.Context, err error) error

Recover attempts to recover using circuit breaker logic

type DiffOptimizer added in v0.7.0

type DiffOptimizer struct {
	// Configuration for optimization thresholds
	MaxDiffLines          int      // Maximum lines to include in full diff
	MaxFileSize           int      // Maximum file size in bytes for full content
	LargeFileExtensions   []string // File extensions considered as large files
	LockFilePatterns      []string // Patterns for lock files
	GeneratedFilePatterns []string // Patterns for generated files
}

DiffOptimizer provides utilities for optimizing diff content for API endpoints

func NewDiffOptimizer added in v0.7.0

func NewDiffOptimizer() *DiffOptimizer

NewDiffOptimizer creates a new diff optimizer with default settings

func (*DiffOptimizer) OptimizeDiff added in v0.7.0

func (do *DiffOptimizer) OptimizeDiff(diff string) *OptimizedDiffResult

OptimizeDiff optimizes a git diff by replacing large files with summaries

type ErrorCategory added in v0.5.0

type ErrorCategory int

ErrorCategory represents the category of an error

const (
	CategorySystem ErrorCategory = iota
	CategoryNetwork
	CategoryFileSystem
	CategoryConfiguration
	CategoryValidation
	CategoryExecution
	CategoryUser
)

type ErrorContext added in v0.5.0

type ErrorContext struct {
	Component string
	Operation string
	UserID    string
	RequestID string
	Resource  string
	Metadata  map[string]interface{}
}

ErrorContext provides additional context for errors

type ErrorHandler added in v0.5.0

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

ErrorHandler provides high-level error handling with recovery

func NewErrorHandler added in v0.5.0

func NewErrorHandler(logger *Logger) *ErrorHandler

NewErrorHandler creates a new error handler with recovery capabilities

func (*ErrorHandler) AddRecoveryStrategy added in v0.5.0

func (e *ErrorHandler) AddRecoveryStrategy(strategy RecoveryStrategy)

AddRecoveryStrategy adds a custom recovery strategy

func (*ErrorHandler) GetRecoveryManager added in v0.5.0

func (e *ErrorHandler) GetRecoveryManager() *RecoveryManager

GetRecoveryManager returns the recovery manager

func (*ErrorHandler) HandleError added in v0.5.0

func (e *ErrorHandler) HandleError(ctx context.Context, err error, context string, enableRecovery bool) error

HandleError handles an error with optional recovery

func (*ErrorHandler) HandleFatalError added in v0.5.0

func (e *ErrorHandler) HandleFatalError(err error, context string)

HandleFatalError handles a fatal error that should terminate the application

func (*ErrorHandler) HandleFileSystemError added in v0.5.0

func (e *ErrorHandler) HandleFileSystemError(ctx context.Context, err error, operation, path string) error

HandleFileSystemError handles filesystem errors

func (*ErrorHandler) HandleNetworkError added in v0.5.0

func (e *ErrorHandler) HandleNetworkError(ctx context.Context, err error, operation string) error

HandleNetworkError handles network errors with retry logic

func (*ErrorHandler) HandleSystemError added in v0.5.0

func (e *ErrorHandler) HandleSystemError(ctx context.Context, err error, component string) error

HandleSystemError handles system-level errors with recovery attempts

func (*ErrorHandler) HandleValidationError added in v0.5.0

func (e *ErrorHandler) HandleValidationError(err error, field string) error

HandleValidationError handles validation errors specifically

func (*ErrorHandler) LogError added in v0.5.0

func (h *ErrorHandler) LogError(err error, context string)

LogError logs an error with context

type ErrorManager added in v0.5.0

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

ErrorManager provides centralized error management and handling

func GetErrorManager added in v0.5.0

func GetErrorManager() *ErrorManager

GetErrorManager returns the global error manager

func NewErrorManager added in v0.5.0

func NewErrorManager(logger *Logger) *ErrorManager

NewErrorManager creates a new error manager

func (*ErrorManager) AddObserver added in v0.5.0

func (em *ErrorManager) AddObserver(observer ErrorObserver)

AddObserver adds an error observer

func (*ErrorManager) AddRecoveryStrategy added in v0.5.0

func (em *ErrorManager) AddRecoveryStrategy(strategy RecoveryStrategy)

AddRecoveryStrategy adds a custom recovery strategy

func (*ErrorManager) ClearStats added in v0.5.0

func (em *ErrorManager) ClearStats()

ClearStats clears error statistics

func (*ErrorManager) GetErrorHandler added in v0.5.0

func (em *ErrorManager) GetErrorHandler() *ErrorHandler

GetErrorHandler returns the underlying error handler

func (*ErrorManager) GetRecentErrors added in v0.5.0

func (em *ErrorManager) GetRecentErrors(limit int) []error

GetRecentErrors returns recent errors

func (*ErrorManager) GetStats added in v0.5.0

func (em *ErrorManager) GetStats() ErrorStats

GetStats returns error statistics

func (*ErrorManager) HandleError added in v0.5.0

func (em *ErrorManager) HandleError(ctx context.Context, err error, context string, enableRecovery bool) error

HandleError handles an error with optional recovery

func (*ErrorManager) HandleFatalError added in v0.5.0

func (em *ErrorManager) HandleFatalError(err error, context string)

HandleFatalError handles a fatal error

func (*ErrorManager) HandleFileSystemError added in v0.5.0

func (em *ErrorManager) HandleFileSystemError(ctx context.Context, err error, operation, path string) error

HandleFileSystemError handles filesystem errors

func (*ErrorManager) HandleNetworkError added in v0.5.0

func (em *ErrorManager) HandleNetworkError(ctx context.Context, err error, operation string) error

HandleNetworkError handles network errors with retry

func (*ErrorManager) HandleSystemError added in v0.5.0

func (em *ErrorManager) HandleSystemError(ctx context.Context, err error, component string) error

HandleSystemError handles system errors with recovery

func (*ErrorManager) HandleValidationError added in v0.5.0

func (em *ErrorManager) HandleValidationError(err error, field string) error

HandleValidationError handles validation errors

func (*ErrorManager) RemoveObserver added in v0.5.0

func (em *ErrorManager) RemoveObserver(observer ErrorObserver)

RemoveObserver removes an error observer

type ErrorObserver added in v0.5.0

type ErrorObserver interface {
	OnError(err error, context string)
	OnRecovery(success bool, err error, strategy string)
}

ErrorObserver can observe error events

type ErrorSeverity added in v0.5.0

type ErrorSeverity int

ErrorSeverity represents the severity level of an error

const (
	SeverityLow ErrorSeverity = iota
	SeverityMedium
	SeverityHigh
	SeverityCritical
)

type ErrorStats added in v0.5.0

type ErrorStats struct {
	TotalErrors      int64
	ErrorsByCode     map[string]int64
	ErrorsByCategory map[ErrorCategory]int64
	RecoveryRate     float64
}

ErrorStats contains error statistics

type FallbackStrategy added in v0.5.0

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

FallbackStrategy implements fallback-based recovery

func NewFallbackStrategy added in v0.5.0

func NewFallbackStrategy(fallbacks map[string]interface{}) *FallbackStrategy

NewFallbackStrategy creates a new fallback strategy

func (*FallbackStrategy) CanRecover added in v0.5.0

func (f *FallbackStrategy) CanRecover(err error) bool

CanRecover checks if fallback is available for the error

func (*FallbackStrategy) GetName added in v0.5.0

func (f *FallbackStrategy) GetName() string

GetName returns the strategy name

func (*FallbackStrategy) Recover added in v0.5.0

func (f *FallbackStrategy) Recover(ctx context.Context, err error) error

Recover attempts to recover using fallback values

type FileChangeSummary added in v0.7.0

type FileChangeSummary struct {
	AddedLines   int
	DeletedLines int
	ContextLines int
	TotalLines   int
}

FileChangeSummary tracks changes in a file

type LogErrorObserver added in v0.5.0

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

LogErrorObserver is an observer that logs errors

func NewLogErrorObserver added in v0.5.0

func NewLogErrorObserver(logger *Logger) *LogErrorObserver

NewLogErrorObserver creates a new logging error observer

func (*LogErrorObserver) OnError added in v0.5.0

func (o *LogErrorObserver) OnError(err error, context string)

OnError handles error notifications

func (*LogErrorObserver) OnRecovery added in v0.5.0

func (o *LogErrorObserver) OnRecovery(success bool, err error, strategy string)

OnRecovery handles recovery notifications

type Logger

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

Logger represents a workspace logger.

func GetLogger

func GetLogger(skipPrompts bool) *Logger

GetLogger returns the singleton instance of Logger. It initializes the logger with a file handler that rotates logs. The skipPrompts parameter determines if user interaction is enabled. This value can be overridden on subsequent calls to GetLogger.

func (*Logger) AskForConfirmation

func (w *Logger) AskForConfirmation(prompt string, default_response bool, required bool) bool

AskForConfirmation prompts the user with a message and waits for a 'yes' or 'no' response. It returns true for 'yes' and false for 'no'.

func (*Logger) Close

func (w *Logger) Close() error

Close closes the logger resources.

func (*Logger) Log

func (w *Logger) Log(message string)

Log logs a general message only to the log file.

func (*Logger) LogAnalysisResult

func (w *Logger) LogAnalysisResult(filePath, success, summary, err string)

LogAnalysisResult logs analysis results. These messages go only to the log file.

func (*Logger) LogError

func (w *Logger) LogError(err error)

func (*Logger) LogProcessStep

func (w *Logger) LogProcessStep(step string)

LogProcessStep logs the current step in a process, with smart UI filtering.

func (*Logger) LogUserInteraction

func (w *Logger) LogUserInteraction(message string)

LogUserInteraction logs user interactions that require a response, and prints to stdout.

func (*Logger) LogWorkspaceOperation

func (w *Logger) LogWorkspaceOperation(operation, details string)

LogWorkspaceOperation logs workspace operations. These messages go only to the log file.

func (*Logger) Logf

func (w *Logger) Logf(format string, v ...interface{})

Logf logs a formatted general message only to the log file.

type MetricsErrorObserver added in v0.5.0

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

MetricsErrorObserver is an observer that collects error metrics

func NewMetricsErrorObserver added in v0.5.0

func NewMetricsErrorObserver() *MetricsErrorObserver

NewMetricsErrorObserver creates a new metrics error observer

func (*MetricsErrorObserver) GetMetrics added in v0.5.0

func (o *MetricsErrorObserver) GetMetrics() map[string]int64

GetMetrics returns the collected metrics

func (*MetricsErrorObserver) OnError added in v0.5.0

func (o *MetricsErrorObserver) OnError(err error, context string)

OnError handles error notifications

func (*MetricsErrorObserver) OnRecovery added in v0.5.0

func (o *MetricsErrorObserver) OnRecovery(success bool, err error, strategy string)

OnRecovery handles recovery notifications

type OptimizedDiffResult added in v0.7.0

type OptimizedDiffResult struct {
	OptimizedContent string            // The optimized diff content
	FileSummaries    map[string]string // Summary for each optimized file
	OriginalLines    int               // Original number of lines
	OptimizedLines   int               // Optimized number of lines
	BytesSaved       int               // Estimated bytes saved
}

OptimizedDiffResult represents the result of diff optimization

type RateLimitBackoff added in v0.6.0

type RateLimitBackoff struct {
	MaxRetries int
	BaseDelay  time.Duration
	MaxDelay   time.Duration
	BufferTime time.Duration
	// contains filtered or unexported fields
}

RateLimitBackoff handles rate limit detection and backoff calculations

func NewRateLimitBackoff added in v0.6.0

func NewRateLimitBackoff() *RateLimitBackoff

NewRateLimitBackoff creates a new rate limit backoff handler with sensible defaults

func (*RateLimitBackoff) CalculateBackoffDelay added in v0.6.0

func (rlb *RateLimitBackoff) CalculateBackoffDelay(resp *http.Response, attempt int) time.Duration

CalculateBackoffDelay calculates how long to wait before retrying

func (*RateLimitBackoff) IsRateLimitError added in v0.6.0

func (rlb *RateLimitBackoff) IsRateLimitError(err error, resp *http.Response) bool

IsRateLimitError checks if an error or HTTP response indicates a rate limit

func (*RateLimitBackoff) LogRateLimit added in v0.6.0

func (rlb *RateLimitBackoff) LogRateLimit(provider, model string, totalTokens int, err error, resp *http.Response)

LogRateLimit logs rate limit information for analysis

func (*RateLimitBackoff) SetOutputFunc added in v0.8.3

func (rlb *RateLimitBackoff) SetOutputFunc(fn func(string))

SetOutputFunc overrides the default output function for user-facing messages

func (*RateLimitBackoff) ShouldRetry added in v0.6.0

func (rlb *RateLimitBackoff) ShouldRetry(attempt int) bool

ShouldRetry determines if we should retry based on attempt count

func (*RateLimitBackoff) WaitWithProgress added in v0.6.0

func (rlb *RateLimitBackoff) WaitWithProgress(duration time.Duration, provider string)

WaitWithProgress waits for the specified duration while showing progress

type RecoveryManager added in v0.5.0

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

RecoveryManager manages error recovery strategies

func NewRecoveryManager added in v0.5.0

func NewRecoveryManager(logger *Logger) *RecoveryManager

NewRecoveryManager creates a new recovery manager

func (*RecoveryManager) AddStrategy added in v0.5.0

func (r *RecoveryManager) AddStrategy(strategy RecoveryStrategy)

AddStrategy adds a recovery strategy

func (*RecoveryManager) CanRecover added in v0.5.0

func (r *RecoveryManager) CanRecover(err error) bool

CanRecover checks if any strategy can recover from the error

func (*RecoveryManager) GetApplicableStrategies added in v0.5.0

func (r *RecoveryManager) GetApplicableStrategies(err error) []RecoveryStrategy

GetApplicableStrategies returns strategies that can handle the error

func (*RecoveryManager) Recover added in v0.5.0

func (r *RecoveryManager) Recover(ctx context.Context, err error) error

Recover attempts to recover from an error using available strategies

type RecoveryStrategy added in v0.5.0

type RecoveryStrategy interface {
	CanRecover(err error) bool
	Recover(ctx context.Context, err error) error
	GetName() string
}

RecoveryStrategy defines how to recover from different types of errors

type RetryStrategy added in v0.5.0

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

RetryStrategy implements retry-based recovery

func NewRetryStrategy added in v0.5.0

func NewRetryStrategy(maxRetries int, baseDelay time.Duration) *RetryStrategy

NewRetryStrategy creates a new retry strategy

func (*RetryStrategy) CanRecover added in v0.5.0

func (r *RetryStrategy) CanRecover(err error) bool

CanRecover checks if the error can be recovered with retry

func (*RetryStrategy) GetName added in v0.5.0

func (r *RetryStrategy) GetName() string

GetName returns the strategy name

func (*RetryStrategy) Recover added in v0.5.0

func (r *RetryStrategy) Recover(ctx context.Context, err error) error

Recover attempts to recover by retrying the operation

type RunLogger added in v0.5.0

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

RunLogger writes structured JSONL events for a single agent run.

func GetRunLogger added in v0.5.0

func GetRunLogger() *RunLogger

GetRunLogger creates (once) and returns the run logger. Log file: .ledit/runlogs/run-YYYYmmdd_HHMMSS.jsonl

func (*RunLogger) Close added in v0.5.0

func (r *RunLogger) Close() error

Close closes the underlying file, if open.

func (*RunLogger) LogEvent added in v0.5.0

func (r *RunLogger) LogEvent(eventType string, fields map[string]any)

LogEvent writes a JSON line with the provided type and fields.

type StructuredError added in v0.5.0

type StructuredError struct {
	Code        string
	Message     string
	Severity    ErrorSeverity
	Category    ErrorCategory
	Context     *ErrorContext
	RootCause   error
	StackTrace  string
	Timestamp   int64
	Recoverable bool
}

StructuredError represents a standardized error with rich context

func NewConfigError added in v0.5.0

func NewConfigError(key string, rootCause error) *StructuredError

NewConfigError creates a configuration-related error

func NewExecutionError added in v0.5.0

func NewExecutionError(component, operation string, rootCause error) *StructuredError

NewExecutionError creates an execution error

func NewFileSystemError added in v0.5.0

func NewFileSystemError(operation, path string, rootCause error) *StructuredError

NewFileSystemError creates a filesystem-related error

func NewNetworkError added in v0.5.0

func NewNetworkError(operation string, rootCause error) *StructuredError

NewNetworkError creates a network-related error

func NewStructuredError added in v0.5.0

func NewStructuredError(code, message string, severity ErrorSeverity, category ErrorCategory, rootCause error) *StructuredError

NewStructuredError creates a new structured error

func NewSystemError added in v0.5.0

func NewSystemError(operation string, rootCause error) *StructuredError

NewSystemError creates a system-level error

func NewUserError added in v0.5.0

func NewUserError(message string, rootCause error) *StructuredError

NewUserError creates a user-facing error

func NewValidationError added in v0.5.0

func NewValidationError(field, reason string) *StructuredError

NewValidationError creates a validation error

func (*StructuredError) Error added in v0.5.0

func (e *StructuredError) Error() string

Error implements the error interface

func (*StructuredError) GetCategory added in v0.5.0

func (e *StructuredError) GetCategory() ErrorCategory

GetCategory returns the error category

func (*StructuredError) GetCode added in v0.5.0

func (e *StructuredError) GetCode() string

GetCode returns the error code

func (*StructuredError) GetContext added in v0.5.0

func (e *StructuredError) GetContext() *ErrorContext

GetContext returns the error context

func (*StructuredError) GetSeverity added in v0.5.0

func (e *StructuredError) GetSeverity() ErrorSeverity

GetSeverity returns the error severity

func (*StructuredError) GetStackTrace added in v0.5.0

func (e *StructuredError) GetStackTrace() string

GetStackTrace returns the stack trace if available

func (*StructuredError) IsRecoverable added in v0.5.0

func (e *StructuredError) IsRecoverable() bool

IsRecoverable checks if the error can be recovered from

func (*StructuredError) MakeUnrecoverable added in v0.5.0

func (e *StructuredError) MakeUnrecoverable() *StructuredError

MakeUnrecoverable marks the error as unrecoverable

func (*StructuredError) Unwrap added in v0.5.0

func (e *StructuredError) Unwrap() error

Unwrap returns the underlying error for compatibility with errors.Is and errors.As

func (*StructuredError) WithComponent added in v0.5.0

func (e *StructuredError) WithComponent(component string) *StructuredError

WithComponent adds component context

func (*StructuredError) WithContext added in v0.5.0

func (e *StructuredError) WithContext(ctx *ErrorContext) *StructuredError

WithContext adds context to the error

func (*StructuredError) WithMetadata added in v0.5.0

func (e *StructuredError) WithMetadata(key string, value interface{}) *StructuredError

WithMetadata adds metadata to the error

func (*StructuredError) WithOperation added in v0.5.0

func (e *StructuredError) WithOperation(operation string) *StructuredError

WithOperation adds operation context

func (*StructuredError) WithResource added in v0.5.0

func (e *StructuredError) WithResource(resource string) *StructuredError

WithResource adds resource context

type TerminalSize added in v0.5.0

type TerminalSize struct {
	Width  int
	Height int
}

TerminalSize represents the dimensions of the terminal

func GetTerminalSize added in v0.5.0

func GetTerminalSize() (*TerminalSize, error)

GetTerminalSize returns the terminal size using multiple detection methods

Jump to

Keyboard shortcuts

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