utils

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2026 License: AGPL-3.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultPollInterval = 5 * time.Second
	MinPollInterval     = 1 * time.Second
	MaxPollInterval     = 30 * time.Second
)

Variables

View Source
var DefaultIgnorePatterns = []string{
	"node_modules", ".git", "build", "dist", "target",
	"bin", ".cache", ".next", ".vscode", ".idea",
	"vendor", "__pycache__", ".nuxt", ".output",
	".svelte-kit", ".turbo", "coverage", ".nyc_output",
}

Functions

func CalculateProgress

func CalculateProgress(current, total int) float64

CalculateProgress returns a progress percentage

func ClearByteSlice

func ClearByteSlice(b []byte)

ClearByteSlice overwrites a byte slice with zeros

func ClearLine

func ClearLine()

func ClearString

func ClearString(s *string)

ClearString attempts to clear a string from memory (best effort) Note: In Go, this is not guaranteed due to garbage collection and string immutability

func ContainsURL

func ContainsURL(fieldLabel string) bool

ContainsURL checks if a field label typically contains URLs

func CopyFile

func CopyFile(src, dst string) error

CopyFile copies a file from source to destination

func EnsureDirectory

func EnsureDirectory(path string, perm os.FileMode) error

EnsureDirectory ensures a directory exists, creating it if necessary

func ExtractURL

func ExtractURL(text string) string

ExtractURL extracts the first URL from a string

func FileExists

func FileExists(path string) bool

FileExists checks if a file exists

func FindConfigFiles

func FindConfigFiles(rootPath string) ([]string, error)

FindConfigFiles finds all config files (JSON, YAML, and Markdown) in a directory structure

func FindFiles

func FindFiles(rootPath string, opts FileDiscoveryOptions) ([]string, error)

FindFiles recursively finds files matching the given options

func FindJSONFiles

func FindJSONFiles(rootPath string) ([]string, error)

FindJSONFiles finds JSON files in the given directory with default options

func FormatDuration

func FormatDuration(d time.Duration) string

FormatDuration formats a duration in a human-readable way

func FormatDurationLong

func FormatDurationLong(d time.Duration) string

FormatDurationLong formats a duration in a detailed human-readable format

func FormatTimeAgo

func FormatTimeAgo(t time.Time) string

FormatTimeAgo formats a time as a human-readable "ago" string

func GenerateRepoBirdURL

func GenerateRepoBirdURL(runID string) string

GenerateRepoBirdURL generates a RepoBird URL for a given run ID

func GetAPIURL

func GetAPIURL(configFallback ...string) string

GetAPIURL returns the appropriate API URL based on environment Priority: REPOBIRD_API_URL > REPOBIRD_ENV=dev > configFallback > default

func InitClipboard

func InitClipboard() error

InitClipboard tries to initialize the clipboard It will detect if CGO is available and set the appropriate mode

func IsDirectory

func IsDirectory(path string) bool

IsDirectory checks if a path is a directory

func IsNonEmptyNumber

func IsNonEmptyNumber(s string) bool

IsNonEmptyNumber checks if a string contains a non-empty number (digits only)

func IsTerminalStatus

func IsTerminalStatus(status models.RunStatus) bool

func IsURL

func IsURL(text string) bool

IsURL checks if a string contains a valid URL

func LoadConfigFromFile

func LoadConfigFromFile(filepath string) (*models.RunConfig, string, error)

LoadConfigFromFile loads configuration from JSON, YAML, or Markdown files

func LoadConfigFromFileNoPrompts

func LoadConfigFromFileNoPrompts(filepath string) (*models.RunConfig, string, error)

LoadConfigFromFileNoPrompts loads config without showing validation prompts

func LoadConfigFromFileWithPrompts

func LoadConfigFromFileWithPrompts(filepath string) (*models.RunConfig, string, *prompts.ValidationPromptHandler, error)

LoadConfigFromFileWithPrompts loads configuration and returns validation prompts for processing

func LoadMarkdownOrJSONConfig

func LoadMarkdownOrJSONConfig(filepath string) (*models.RunConfig, string, error)

LoadMarkdownOrJSONConfig loads configuration from either markdown or JSON file

func MarshalJSON

func MarshalJSON(v interface{}) ([]byte, error)

MarshalJSON marshals an interface to JSON with standardized error handling

func MarshalJSONIndent

func MarshalJSONIndent(v interface{}, prefix, indent string) ([]byte, error)

MarshalJSONIndent marshals an interface to pretty-printed JSON with standardized error handling

func MarshalJSONIndentToString

func MarshalJSONIndentToString(v interface{}) (string, error)

MarshalJSONIndentToString marshals an interface to a pretty-printed JSON string

func MarshalJSONToString

func MarshalJSONToString(v interface{}) (string, error)

MarshalJSONToString marshals an interface to a JSON string

func MaskAPIKey

func MaskAPIKey(apiKey string) string

MaskAPIKey masks an API key for secure display, showing only the first 4 characters

func MaskSensitiveString

func MaskSensitiveString(value string, showChars int) string

MaskSensitiveString masks any sensitive string for display

func NewClipboardError

func NewClipboardError(message string) error

NewClipboardError creates a new clipboard error

func OpenURL

func OpenURL(ctx context.Context, urlStr string) error

OpenURL opens a URL in the default browser with context support

func OpenURLWithTimeout

func OpenURLWithTimeout(urlStr string) error

OpenURLWithTimeout is a convenience function that creates a context with default timeout

func ParseJSONFromStdin

func ParseJSONFromStdin() (*models.RunConfig, error)

ParseJSONFromStdin parses JSON from stdin with unknown field support and warnings

func ParseJSONFromStdinWithPrompts

func ParseJSONFromStdinWithPrompts() (*models.RunConfig, *prompts.ValidationPromptHandler, error)

ParseJSONFromStdinWithPrompts parses JSON from stdin with validation prompts

func ParseMarkdownConfig

func ParseMarkdownConfig(filepath string) (*models.RunConfig, string, error)

ParseMarkdownConfig reads and parses a markdown file with frontmatter

func ParseMarkdownConfigFromReader

func ParseMarkdownConfigFromReader(r io.Reader) (*models.RunConfig, string, error)

ParseMarkdownConfigFromReader parses markdown config from an io.Reader

func ParseYAMLConfig

func ParseYAMLConfig(filepath string) (*models.RunConfig, error)

ParseYAMLConfig reads and parses a YAML configuration file

func ParseYAMLConfigFromReader

func ParseYAMLConfigFromReader(r io.Reader) (*models.RunConfig, error)

ParseYAMLConfigFromReader parses YAML config from an io.Reader

func ParseYAMLConfigFromReaderWithPrompts

func ParseYAMLConfigFromReaderWithPrompts(r io.Reader) (*models.RunConfig, *prompts.ValidationPromptHandler, error)

ParseYAMLConfigFromReaderWithPrompts parses YAML config from an io.Reader with validation prompts

func ParseYAMLConfigWithPrompts

func ParseYAMLConfigWithPrompts(filepath string) (*models.RunConfig, *prompts.ValidationPromptHandler, error)

ParseYAMLConfigWithPrompts reads and parses a YAML configuration file with validation prompts

func ReadFileWithError

func ReadFileWithError(path string) ([]byte, error)

ReadFileWithError reads a file and returns standardized error messages

func ReadPromptInput added in v0.1.5

func ReadPromptInput(input string) (string, error)

ReadPromptInput reads prompt content from either a literal string or a file. If the input starts with '@', it reads from the file specified after the @. If the input is '-', it reads from stdin. Otherwise, it returns the input as-is.

Examples:

  • "Fix the bug" returns "Fix the bug"
  • "@prompt.txt" reads content from prompt.txt
  • "@/path/to/prompt.md" reads content from /path/to/prompt.md
  • "-" reads from stdin
  • "@@literal" returns "@literal" (double @ escapes the @)

func RedactAuthHeader

func RedactAuthHeader(headerValue string) string

RedactAuthHeader redacts the Authorization header value for logging

func RemoveFileIfExists

func RemoveFileIfExists(path string) error

RemoveFileIfExists removes a file if it exists, ignoring not-exist errors

func SanitizeErrorMessage

func SanitizeErrorMessage(err error, apiKey string) string

SanitizeErrorMessage removes sensitive information from error messages

func ShowPollingProgress

func ShowPollingProgress(startTime time.Time, status string, message string)

func SuggestFieldName

func SuggestFieldName(input string, validFields []string) string

SuggestFieldName suggests the most similar field name for an unknown field

func TruncateMultiline

func TruncateMultiline(s string, maxWidth int) string

TruncateMultiline truncates a string handling newlines and tabs. Takes only the first line and converts tabs to spaces. Uses rune counting for proper unicode handling.

func TruncateSimple

func TruncateSimple(s string, maxLen int) string

TruncateSimple truncates a string based on byte length. This is faster but doesn't handle unicode display width correctly. Use this for non-display purposes or when you know the string is ASCII.

func TruncateWithEllipsis

func TruncateWithEllipsis(s string, maxWidth int) string

TruncateWithEllipsis truncates a string to fit within maxWidth using display width (handles unicode/emoji properly). This should be used for terminal display where visual width matters.

func UnmarshalJSON

func UnmarshalJSON(data []byte, v interface{}) error

UnmarshalJSON unmarshals JSON data into an interface with standardized error handling

func ValidateAPIKeyFormat

func ValidateAPIKeyFormat(apiKey string) error

ValidateAPIKeyFormat performs basic validation on API key format without revealing specifics about what's wrong

func ValidateRunConfig

func ValidateRunConfig(config *models.RunConfig) error

ValidateRunConfig validates a RunConfig structure and applies defaults

func WriteFileWithError

func WriteFileWithError(path string, data []byte, perm os.FileMode) error

WriteFileWithError writes data to a file with standardized error messages

func WriteToClipboard

func WriteToClipboard(ctx context.Context, text string) error

WriteToClipboard writes text to the system clipboard with context support It uses CGO clipboard if available, otherwise falls back to OS commands

func WriteToClipboardWithTimeout

func WriteToClipboardWithTimeout(text string) error

WriteToClipboardWithTimeout is a convenience function that creates a context with default timeout

Types

type ClipboardError

type ClipboardError struct {
	Message string
}

ClipboardError represents a clipboard operation error

func (ClipboardError) Error

func (e ClipboardError) Error() string

type CompletionFunc

type CompletionFunc[T any] func(T) bool

CompletionFunc checks if the result is in a terminal state

type FileDiscoveryOptions

type FileDiscoveryOptions struct {
	MaxDepth       int
	IgnorePatterns []string
	FileExtensions []string
	SortByModTime  bool
	MaxFiles       int // Limit number of results for performance
}

type FileInfo

type FileInfo struct {
	Path    string
	ModTime time.Time
	Size    int64
}

type GenericPollConfig

type GenericPollConfig struct {
	Interval      time.Duration
	MaxInterval   time.Duration
	BackoffFactor float64
	Timeout       time.Duration
	ShowProgress  bool
	Debug         bool
}

GenericPollConfig holds configuration for polling operations

type GenericPollFunc

type GenericPollFunc[T any] func(ctx context.Context) (T, error)

PollFunc is a generic function that fetches the current state

type GenericPoller

type GenericPoller[T any] struct {
	// contains filtered or unexported fields
}

GenericPoller handles polling operations with exponential backoff

func NewGenericPoller

func NewGenericPoller[T any](config *GenericPollConfig) *GenericPoller[T]

NewGenericPoller creates a new generic poller

func (*GenericPoller[T]) PollUntilComplete

func (p *GenericPoller[T]) PollUntilComplete(
	ctx context.Context,
	pollFunc GenericPollFunc[T],
	isComplete CompletionFunc[T],
	onUpdate UpdateCallback[T],
) (T, error)

PollUntilComplete polls until the completion function returns true

type MarkdownConfig

type MarkdownConfig struct {
	Prompt                string                          `yaml:"prompt" json:"prompt"`
	Repository            string                          `yaml:"repository" json:"repository"`
	Source                string                          `yaml:"source" json:"source"`
	Target                string                          `yaml:"target" json:"target"`
	BaseBranch            string                          `yaml:"baseBranch" json:"baseBranch"`
	OutputMode            string                          `yaml:"outputMode" json:"outputMode"`
	OutputBranch          string                          `yaml:"outputBranch" json:"outputBranch"`
	PRTargetBranch        string                          `yaml:"prTargetBranch" json:"prTargetBranch"`
	OutputBranchPolicy    string                          `yaml:"outputBranchPolicy" json:"outputBranchPolicy"`
	RunType               string                          `yaml:"runType" json:"runType"`
	Title                 string                          `yaml:"title" json:"title"`
	Context               string                          `yaml:"context" json:"context"`
	Files                 []string                        `yaml:"files" json:"files"`
	ProviderCredentialID  string                          `yaml:"providerCredentialId" json:"providerCredentialId"`
	ProviderMode          string                          `yaml:"providerMode" json:"providerMode"`
	OpenCodeModel         string                          `yaml:"opencodeModel,omitempty" json:"opencodeModel,omitempty"`
	OpenCodeProvider      string                          `yaml:"opencodeProvider,omitempty" json:"opencodeProvider,omitempty"`
	ReasoningEffort       string                          `yaml:"reasoningEffort,omitempty" json:"reasoningEffort,omitempty"`
	GitLabCredential      *models.GitLabCredentialRequest `yaml:"gitlabCredential,omitempty" json:"gitlabCredential,omitempty"`
	BranchOnly            bool                            `yaml:"branchOnly" json:"branchOnly"`
	AcknowledgePromptRisk bool                            `yaml:"acknowledgePromptRisk" json:"acknowledgePromptRisk"`
	PullRequest           *PullRequestConfig              `yaml:"pullRequest,omitempty" json:"pullRequest,omitempty"`
	Metadata              map[string]interface{}          `yaml:"metadata,omitempty" json:"metadata,omitempty"`
}

MarkdownConfig represents the frontmatter structure in markdown task files

type PollConfig

type PollConfig struct {
	Interval     time.Duration
	MaxDuration  time.Duration
	ShowProgress bool
	Debug        bool
}

func DefaultPollConfig

func DefaultPollConfig() *PollConfig

type PollFunc

type PollFunc func(ctx context.Context) (*models.RunResponse, error)

type Poller

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

func NewPoller

func NewPoller(config *PollConfig) *Poller

func (*Poller) Poll

func (p *Poller) Poll(ctx context.Context, fn PollFunc, onUpdate func(*models.RunResponse)) (*models.RunResponse, error)

type PullRequestConfig

type PullRequestConfig struct {
	Create bool `yaml:"create" json:"create"`
	Draft  bool `yaml:"draft" json:"draft"`
}

PullRequestConfig represents pull request configuration

type UpdateCallback

type UpdateCallback[T any] func(T)

UpdateCallback is called with each poll result

type YAMLConfig

type YAMLConfig struct {
	Prompt                string                          `yaml:"prompt" json:"prompt"`
	Repository            string                          `yaml:"repository" json:"repository"`
	Source                string                          `yaml:"source" json:"source"`
	Target                string                          `yaml:"target" json:"target"`
	BaseBranch            string                          `yaml:"baseBranch" json:"baseBranch"`
	OutputMode            string                          `yaml:"outputMode" json:"outputMode"`
	OutputBranch          string                          `yaml:"outputBranch" json:"outputBranch"`
	PRTargetBranch        string                          `yaml:"prTargetBranch" json:"prTargetBranch"`
	OutputBranchPolicy    string                          `yaml:"outputBranchPolicy" json:"outputBranchPolicy"`
	RunType               string                          `yaml:"runType" json:"runType"`
	Title                 string                          `yaml:"title" json:"title"`
	Context               string                          `yaml:"context" json:"context"`
	Files                 []string                        `yaml:"files" json:"files"`
	ProviderCredentialID  string                          `yaml:"providerCredentialId" json:"providerCredentialId"`
	ProviderMode          string                          `yaml:"providerMode" json:"providerMode"`
	OpenCodeModel         string                          `yaml:"opencodeModel,omitempty" json:"opencodeModel,omitempty"`
	OpenCodeProvider      string                          `yaml:"opencodeProvider,omitempty" json:"opencodeProvider,omitempty"`
	ReasoningEffort       string                          `yaml:"reasoningEffort,omitempty" json:"reasoningEffort,omitempty"`
	GitLabCredential      *models.GitLabCredentialRequest `yaml:"gitlabCredential,omitempty" json:"gitlabCredential,omitempty"`
	BranchOnly            bool                            `yaml:"branchOnly" json:"branchOnly"`
	AcknowledgePromptRisk bool                            `yaml:"acknowledgePromptRisk" json:"acknowledgePromptRisk"`
	PullRequest           *PullRequestConfig              `yaml:"pullRequest,omitempty" json:"pullRequest,omitempty"`
	Metadata              map[string]interface{}          `yaml:"metadata,omitempty" json:"metadata,omitempty"`
}

YAMLConfig represents the structure of a YAML configuration file

Jump to

Keyboard shortcuts

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