utils

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2025 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	Reset     = "\033[0m"
	Red       = "\033[38;5;196m" // Bright red
	Green     = "\033[38;5;46m"  // Neon green
	Yellow    = "\033[38;5;226m" // Warning yellow
	Blue      = "\033[38;5;33m"  // Electric blue
	Magenta   = "\033[38;5;201m" // Cyber pink
	Cyan      = "\033[38;5;51m"  // Holographic cyan
	Black     = "\033[38;5;236m" // Dark background
	Bold      = "\033[1m"
	Underline = "\033[4m"
	Blink     = "\033[5m" // Use sparingly!
	Dim       = "\033[2m"
	BlackBg   = "\033[48;5;235m" // Dark background
)

ANSI color codes - Dark Tech palette

Variables

View Source
var BinaryFileExtensions = map[string]bool{

	".jpg": true, ".jpeg": true, ".png": true, ".gif": true, ".bmp": true, ".tiff": true, ".svg": true, ".webp": true, ".ico": true,

	".mp4": true, ".avi": true, ".mov": true, ".wmv": true, ".flv": true, ".webm": true, ".mkv": true, ".m4v": true,

	".mp3": true, ".wav": true, ".flac": true, ".aac": true, ".ogg": true, ".wma": true, ".m4a": true,

	".zip": true, ".rar": true, ".7z": true, ".tar": true, ".gz": true, ".bz2": true, ".xz": true,

	".exe": true, ".dll": true, ".so": true, ".dylib": true, ".app": true, ".deb": true, ".rpm": true,

	".pdf": true, ".doc": true, ".docx": true, ".xls": true, ".xlsx": true, ".ppt": true, ".pptx": true,

	".ttf": true, ".otf": true, ".woff": true, ".woff2": true, ".eot": true,

	".db": true, ".sqlite": true, ".sqlite3": true,

	".bin": true, ".dat": true, ".dump": true, ".img": true, ".iso": true, ".dmg": true,
}

BinaryFileExtensions contains common binary file extensions

View Source
var LogLevel string = "info"

Functions

func AddStatsPostRunToCommand

func AddStatsPostRunToCommand(cmd *cobra.Command)

AddStatsPostRunToCommand adds a PostRun function to display stats for a command

func CaptureClusteringConfig

func CaptureClusteringConfig()

CaptureClusteringConfig captures clustering configuration from the config package This function should be called when clustering operations begin

func CaptureClusteringConfigFromSettings

func CaptureClusteringConfigFromSettings(
	defaultMethod string,
	enabledMethods []string,
	confidenceThresholds map[string]float64,
	similarityThresholds map[string]float64,
	maxFilesForSemantic int,
	enableFallbackMethods bool,
	performanceMode string,
	maxProcessingTime int,
	enableBenchmarking bool,
	adaptiveOptimization bool,
)

CaptureClusteringConfigFromSettings captures clustering configuration info from provided parameters

func CompleteOperation

func CompleteOperation(name string)

CompleteOperation marks an operation as completed

func ConfirmAction

func ConfirmAction(message string, defaultYes bool) bool

ConfirmAction asks the user to confirm an action with yes/no prompt

func ConfirmActionWithDetails

func ConfirmActionWithDetails(action string, details []string, defaultYes bool) bool

ConfirmActionWithDetails asks for confirmation and shows detailed information

func ContainsString

func ContainsString(s, substr string) bool

ContainsString checks if a string contains a substring

func Debug

func Debug(message string)

Debug logs a message at the debug level

func EnableStats

func EnableStats()

EnableStats turns on statistics tracking

func Error

func Error(message string, fileContext ...string)

Error logs error message

func FailOperation

func FailOperation(name string, reason string)

FailOperation marks an operation as failed

func GenerateBinaryCommitMessage

func GenerateBinaryCommitMessage(filePath string, gitStatus string) string

GenerateBinaryCommitMessage creates appropriate commit messages for binary files

func GetBinaryFileType

func GetBinaryFileType(filePath string) string

GetBinaryFileType returns a descriptive type for binary files

func GetLastSystemInstruction

func GetLastSystemInstruction() string

GetLastSystemInstruction returns the last system instruction used (for testing)

func GetMemoryUsage

func GetMemoryUsage() string

GetMemoryUsage returns current memory usage as a formatted string

func Info

func Info(message string)

Info logs a message at the info level

func IsBinaryFile

func IsBinaryFile(filePath string) bool

IsBinaryFile checks if a file is likely binary based on its extension

func IsCreativeLoaderActive

func IsCreativeLoaderActive() bool

IsCreativeLoaderActive returns whether the global loader is active

func IsNumeric

func IsNumeric(s string) bool

func IsQuietMode

func IsQuietMode() bool

IsQuietMode returns whether quiet mode is enabled

func IsStatsEnabled

func IsStatsEnabled() bool

IsStatsEnabled returns whether stats tracking is currently enabled

func ListFiles

func ListFiles(directory string) ([]string, error)

func MarkOperationComplete

func MarkOperationComplete(name string)

MarkOperationComplete is a helper function to mark an operation as complete with proper progress handling

func NewDefaultGeminiRunner

func NewDefaultGeminiRunner() interfaces.GeminiRunner

NewDefaultGeminiRunner creates a new instance of DefaultGeminiRunner

func ParseFloat

func ParseFloat(s string) (float64, error)

func ParseInt

func ParseInt(s string) (int, error)

func Print

func Print(data string)

Print outputs data to the CLI

func PrintStats

func PrintStats()

PrintStats displays comprehensive command statistics

func PromptForInput

func PromptForInput(message string, defaultValue string) string

PromptForInput asks the user for text input with an optional default value

func PromptForSelection

func PromptForSelection(message string, options []string, defaultIndex int) (string, int)

PromptForSelection asks the user to select from a list of options

func SafeExecute

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

SafeExecute runs a function with panic recovery

func SanitizeUserInstructions

func SanitizeUserInstructions(instructions string) string

SanitizeUserInstructions cleans potentially harmful or manipulative instructions

func SendToGemini

func SendToGemini(contextData map[string]map[string]string, apiKey string, customInstructions ...string) (string, error)

func SetClusteringInfo

func SetClusteringInfo(method string, enabledMethods []string, confidenceThresholds, similarityThresholds map[string]float64,
	maxFilesForSemantic int, enableFallbackMethods bool, performanceMode string, maxProcessingTime int,
	enableBenchmarking, adaptiveOptimization bool)

SetClusteringInfo stores clustering configuration information for stats display

func SetLogLevel

func SetLogLevel(level string)

func SetQuietMode

func SetQuietMode(quiet bool)

SetQuietMode sets the global quiet mode flag

func SetTimeoutVar

func SetTimeoutVar(retries, delay int)

func ShowCompletionMessage

func ShowCompletionMessage(message string, success bool)

ShowCompletionMessage displays a completion message with appropriate styling

func ShowProgressiveConfirmation

func ShowProgressiveConfirmation(steps []string, actions []func() error) error

ShowProgressiveConfirmation shows a multi-step confirmation dialog where each step depends on the previous one

func StartCreativeLoader

func StartCreativeLoader(message string, animationType AnimationType)

StartCreativeLoader starts a global creative loader

func StartOperation

func StartOperation(name string)

StartOperation tracks the start of an operation

func StartPromptCoordinator added in v1.5.0

func StartPromptCoordinator(promptChan <-chan PromptRequest)

func StopCreativeLoader

func StopCreativeLoader()

StopCreativeLoader stops the global creative loader

func Success

func Success(message string)

Success logs a success message

func ToJSON

func ToJSON(data interface{}) string

func ToUserFriendlyMessage

func ToUserFriendlyMessage(err error) string

ToUserFriendlyMessage converts an error to a user-friendly message with possible solution

func UpdateCreativeLoaderMessage

func UpdateCreativeLoaderMessage(message string)

UpdateCreativeLoaderMessage updates the global loader message

func UpdateCreativeLoaderPhase

func UpdateCreativeLoaderPhase(phase string)

UpdateCreativeLoaderPhase updates the global loader phase

func UpdateOperationProgress

func UpdateOperationProgress(name string, progress float64)

UpdateOperationProgress is a helper function to update operation progress and ensure consistent progress tracking in the stats system

func UpdateProgress

func UpdateProgress(name string, progress float64, status string)

UpdateProgress updates the progress of an operation

func Warning

func Warning(message string)

Warning logs warning message

func WithRetry

func WithRetry(ctx context.Context, operation string, config RetryConfig, fn func() error) error

WithRetry executes a function with automatic retries using exponential backoff

Types

type AnimationType

type AnimationType int

AnimationType defines the type of animation to use

const (
	SpinnerAnimation AnimationType = iota
	DotsAnimation
	BarAnimation
	BrailleAnimation
	GitAnimation
	ProcessingAnimation
)

type ClusteringMethodInfo

type ClusteringMethodInfo struct {
	Method                string             `json:"method"`
	EnabledMethods        []string           `json:"enabledMethods"`
	ConfidenceThresholds  map[string]float64 `json:"confidenceThresholds"`
	SimilarityThresholds  map[string]float64 `json:"similarityThresholds"`
	MaxFilesForSemantic   int                `json:"maxFilesForSemantic"`
	EnableFallbackMethods bool               `json:"enableFallbackMethods"`
	PerformanceMode       string             `json:"performanceMode"`
	MaxProcessingTime     int                `json:"maxProcessingTime"`
	EnableBenchmarking    bool               `json:"enableBenchmarking"`
	AdaptiveOptimization  bool               `json:"adaptiveOptimization"`
}

func GetClusteringInfo

func GetClusteringInfo() *ClusteringMethodInfo

GetClusteringInfo returns the stored clustering configuration

type CommandStats

type CommandStats struct {
	Command        string
	StartTime      time.Time
	EndTime        time.Time
	Duration       time.Duration
	Operations     []ProgressInfo
	TotalOps       int
	CompletedOps   int
	SuccessRate    float64
	MemoryUsed     string
	CPUTime        string
	ClusteringInfo *ClusteringMethodInfo // New field for clustering info
}

type CreativeLoader

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

CreativeLoader provides a more engaging progress display with various animations

func NewCreativeLoader

func NewCreativeLoader(message string, animationType AnimationType) *CreativeLoader

NewCreativeLoader creates a new creative loader

func (*CreativeLoader) SetHideInQuiet

func (cl *CreativeLoader) SetHideInQuiet(hide bool) *CreativeLoader

SetHideInQuiet sets whether to hide in quiet mode

func (*CreativeLoader) SetPhase

func (cl *CreativeLoader) SetPhase(phase string)

SetPhase updates the current phase for dynamic messages

func (*CreativeLoader) SetWriter

func (cl *CreativeLoader) SetWriter(writer io.Writer) *CreativeLoader

SetWriter sets the output writer

func (*CreativeLoader) Start

func (cl *CreativeLoader) Start()

Start begins the creative loader animation

func (*CreativeLoader) Stop

func (cl *CreativeLoader) Stop()

Stop stops the creative loader animation

func (*CreativeLoader) UpdateMessage

func (cl *CreativeLoader) UpdateMessage(message string)

UpdateMessage updates the loader message

type DefaultGeminiRunner

type DefaultGeminiRunner struct{}

DefaultGeminiRunner implements the GeminiRunner interface using the real Gemini API

func (*DefaultGeminiRunner) SendToGemini

func (r *DefaultGeminiRunner) SendToGemini(contextData map[string]map[string]string, apiKey string, customInstructions ...string) (string, error)

SendToGemini delegates to the real SendToGemini function

type ErrorType

type ErrorType string

ErrorType represents the category of an error

const (
	// Error categories
	ConfigError     ErrorType = "CONFIG"
	GitError        ErrorType = "GIT"
	APIError        ErrorType = "API"
	ValidationError ErrorType = "VALIDATION"
	SystemError     ErrorType = "SYSTEM"
	UserError       ErrorType = "USER"
)

type ProgressInfo

type ProgressInfo struct {
	Name      string
	StartTime time.Time
	EndTime   *time.Time
	Duration  time.Duration
	Progress  float64
	Status    string
}

type ProgressReporter

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

ProgressReporter provides an interface for reporting progress of long-running operations

func NewIndeterminateProgressReporter

func NewIndeterminateProgressReporter(message string) *ProgressReporter

NewIndeterminateProgressReporter creates a progress reporter for operations where the total amount of work is unknown

func NewProgressReporter

func NewProgressReporter(total int64, message string) *ProgressReporter

NewProgressReporter creates a new progress reporter

func (*ProgressReporter) Done

func (p *ProgressReporter) Done()

Done completes the progress reporting

func (*ProgressReporter) Increment

func (p *ProgressReporter) Increment(amount int64)

Increment increases the current progress by the specified amount

func (*ProgressReporter) SetHideInQuiet

func (p *ProgressReporter) SetHideInQuiet(hide bool) *ProgressReporter

SetHideInQuiet sets whether the progress bar should be hidden in quiet mode

func (*ProgressReporter) SetWidth

func (p *ProgressReporter) SetWidth(width int) *ProgressReporter

SetWidth sets the width of the progress bar

func (*ProgressReporter) SetWriter

func (p *ProgressReporter) SetWriter(writer io.Writer) *ProgressReporter

SetWriter sets the io.Writer where progress updates are written

func (*ProgressReporter) Start

func (p *ProgressReporter) Start() *ProgressReporter

Start begins the progress reporting

func (*ProgressReporter) Update

func (p *ProgressReporter) Update(current int64)

Update updates the current progress

func (*ProgressReporter) UpdateMessage

func (p *ProgressReporter) UpdateMessage(message string)

UpdateMessage updates the message displayed with the progress bar

type PromptRequest added in v1.5.0

type PromptRequest struct {
	Question string
	Default  bool
	RespChan chan bool
}

type ResourceManager

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

ResourceManager monitors and manages system resources for the application

func GetResourceManager

func GetResourceManager() *ResourceManager

GetResourceManager returns the default resource manager instance

func NewResourceManager

func NewResourceManager() *ResourceManager

NewResourceManager creates a resource manager with default settings

func (*ResourceManager) GetRecommendedWorkerCount

func (rm *ResourceManager) GetRecommendedWorkerCount(defaultWorkers int) int

GetRecommendedWorkerCount returns the recommended number of worker goroutines based on current system load and available CPU cores

func (*ResourceManager) GetResourceUsage

func (rm *ResourceManager) GetResourceUsage() map[string]interface{}

GetResourceUsage returns the current resource usage metrics

func (*ResourceManager) IsRunning

func (rm *ResourceManager) IsRunning() bool

IsRunning returns whether resource monitoring is active

func (*ResourceManager) SetCheckInterval

func (rm *ResourceManager) SetCheckInterval(interval time.Duration)

SetCheckInterval sets how often resources are checked

func (*ResourceManager) SetMaxCPUPercent

func (rm *ResourceManager) SetMaxCPUPercent(percent float64)

SetMaxCPUPercent sets the maximum allowed CPU usage as a percentage

func (*ResourceManager) SetMaxMemoryPercent

func (rm *ResourceManager) SetMaxMemoryPercent(percent float64)

SetMaxMemoryPercent sets the maximum allowed memory usage as a percentage

func (*ResourceManager) Start

func (rm *ResourceManager) Start()

Start begins monitoring system resources

func (*ResourceManager) Stop

func (rm *ResourceManager) Stop()

Stop ends resource monitoring

type RetryConfig

type RetryConfig struct {
	MaxRetries   int
	InitialDelay time.Duration
	MaxDelay     time.Duration
	Factor       float64 // Exponential backoff factor
}

RetryConfig holds the configuration for retry operations

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns the default retry configuration

type StructuredError

type StructuredError struct {
	Type          ErrorType
	Message       string
	Cause         error
	Context       map[string]interface{}
	ProcessedFile string
}

StructuredError represents an error with additional context

func NewAPIError

func NewAPIError(message string, cause error, context map[string]interface{}, processedFile ...string) *StructuredError

NewAPIError creates a new API-related error

func NewConfigError

func NewConfigError(message string, cause error, context map[string]interface{}, processedFile ...string) *StructuredError

NewConfigError creates a new configuration error

func NewGitError

func NewGitError(message string, cause error, context map[string]interface{}, processedFile ...string) *StructuredError

NewGitError creates a new Git-related error

func NewSystemError

func NewSystemError(message string, cause error, context map[string]interface{}, processedFile ...string) *StructuredError

NewSystemError creates a new system-related error

func NewUserError

func NewUserError(message string, cause error, context map[string]interface{}) *StructuredError

NewUserError creates a new user-related error

func NewValidationError

func NewValidationError(message string, cause error, context map[string]interface{}, processedFile ...string) *StructuredError

NewValidationError creates a new validation error

func (*StructuredError) Error

func (e *StructuredError) Error() string

Error implements the error interface

func (*StructuredError) Unwrap

func (e *StructuredError) Unwrap() error

Unwrap implements the errors.Unwrap interface

type WorkerPool

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

WorkerPool implements a reusable worker pool with configurable concurrency limit

func NewWorkerPool

func NewWorkerPool(maxWorkers int) *WorkerPool

NewWorkerPool creates a new worker pool with the specified maximum concurrent workers

func (*WorkerPool) Errors

func (wp *WorkerPool) Errors() []error

Errors returns all errors collected from task execution

func (*WorkerPool) HasErrors

func (wp *WorkerPool) HasErrors() bool

HasErrors returns true if any tasks have reported errors

func (*WorkerPool) Submit

func (wp *WorkerPool) Submit(taskName string, timeout time.Duration, task func() error)

Submit adds a task to the worker pool with the specified timeout

func (*WorkerPool) Wait

func (wp *WorkerPool) Wait() []error

Wait blocks until all tasks have completed

Jump to

Keyboard shortcuts

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