Documentation
¶
Index ¶
- Constants
- func AddLabelsToIssue(ctx context.Context, client *github.Client, owner, repo string, number int, ...) error
- func AppendToFile(path string, data []byte) error
- func AppendToFileString(path string, content string) error
- func CalculateBackoff(attempt int, baseDelay time.Duration, maxDelay time.Duration) time.Duration
- func ContainsAll(s string, substrings ...string) bool
- func ContainsAny(s string, substrings ...string) bool
- func CopyFile(src, dst string) error
- func CreatePullRequest(ctx context.Context, client *github.Client, owner, repo string, ...) (*github.PullRequest, error)
- func CreateRef(ctx context.Context, client *github.Client, owner, repo string, ...) error
- func ExecuteWithRetry(ctx context.Context, client *github.Client, maxRetries int, ...) error
- func FileExists(path string) bool
- func FindFilesWithExtension(dir string, ext string) ([]string, error)
- func GetLatestRelease(ctx context.Context, client *github.Client, owner, repo string) (*github.RepositoryRelease, error)
- func GetRef(ctx context.Context, client *github.Client, owner, repo, ref string) (*github.Reference, error)
- func IsDirectory(path string) bool
- func IsHexString(s string) bool
- func IsPathSafe(baseDir, path string) bool
- func IsRegularFile(path string) bool
- func IsValidGitHubToken(token string) bool
- func JoinAndValidatePath(baseDir string, elements ...string) (string, error)
- func JoinNonEmpty(sep string, parts ...string) string
- func ModifyLines(path string, fn func(line string, lineNum int) string) error
- func NewGitHubClient(options GitHubClientOptions) *github.Client
- func NewGitHubClientWithToken(token string) *github.Client
- func ReadFile(path string) ([]byte, error)
- func ReadFileString(path string) (string, error)
- func ReadFileWithOptions(path string, options FileOptions) ([]byte, error)
- func ReadLines(path string) ([]string, error)
- func ReplaceInFile(path string, oldStr, newStr string) error
- func SafeAbs(baseDir, path string) (string, error)
- func SplitAndTrim(s, sep string) []string
- func TrimPrefixAny(s string, prefixes ...string) string
- func TrimSuffixAny(s string, suffixes ...string) string
- func ValidatePath(baseDir, path string, options PathValidationOptions) error
- func ValidatePathWithDefaults(baseDir, path string) error
- func ValidateTokenScopes(ctx context.Context, client *github.Client) error
- func WriteFile(path string, data []byte) error
- func WriteFileString(path string, content string) error
- func WriteFileWithOptions(path string, data []byte, options FileOptions) error
- func WriteLines(path string, lines []string) error
- type FileLockManager
- type FileOptions
- type GitHubClientOptions
- type PathValidationOptions
- type RateLimitHandler
- type TokenInfo
Constants ¶
const ( // Base directory errors ErrBaseDirectoryNotSet = "base directory not set" ErrEmptyPath = "path is empty" ErrPathContainsNullBytes = "path contains null bytes" ErrPathExceedsMaxLength = "path exceeds maximum length of %d characters" ErrFailedToResolveBasePath = "failed to resolve base path: %w" ErrFailedToResolvePath = "failed to resolve path: %w" ErrPathOutsideAllowedDir = "path is outside of allowed directory: %s" ErrFailedToDetermineRelPath = "failed to determine relative path: %w" ErrPathTraversalDetected = "path traversal attempt detected" // Symlink related errors ErrFailedToEvaluateSymlink = "failed to evaluate symlink: %w" ErrFailedToEvalBaseDir = "failed to evaluate base directory: %w" ErrFailedToResolveSymTarget = "failed to resolve symlink target path: %w" ErrFailedToResolveEvalBase = "failed to resolve evaluated base path: %w" ErrSymlinkOutsideAllowedDir = "symlink points outside allowed directory: path is outside of allowed directory: %s" // File access errors ErrPathDoesNotExist = "path does not exist: %s" ErrFailedToAccessPath = "failed to access path: %w" ErrNotRegularFile = "not a regular file: %s" )
PathValidationErrors contains constants for path validation error messages
const ( ErrInvalidFilePath = "invalid file path: %w" ErrReadingFile = "error reading file: %w" ErrCreatingDirectories = "error creating directories: %w" ErrWritingTempFile = "error writing temporary file: %w" ErrReplacingOriginalFile = "error replacing original file: %w" ErrOpeningSourceFile = "error opening source file: %w" ErrCreatingDestFile = "error creating destination file: %w" ErrCopyingFileContents = "error copying file contents: %w" ErrSyncingFile = "error syncing file: %w" ErrOpeningFileForAppend = "error opening file for append: %w" ErrAppendingToFile = "error appending to file: %w" ErrScanningDirectory = "error scanning directory: %w" )
FileOperationErrors contains constants for file operation error messages
const ( ErrInvalidActionRefFormat = "invalid action reference format: %s" ErrInvalidActionNameFormat = "invalid action name format: %s" ErrInvalidDirectoryPath = "invalid directory path: %w" ErrWorkflowDirNotFound = "workflows directory not found at %s" ErrScanningWorkflows = "error scanning workflows: %w" ErrReadingWorkflowFile = "error reading workflow file: %w" ErrParsingWorkflowYAML = "error parsing workflow YAML: %w" ErrEmptyYAMLDocument = "empty YAML document" ErrParsingWorkflowContent = "error parsing workflow content: %w" )
ScannerErrors contains constants for scanner error messages
const ( ErrFailedToRemoveTempDir = "Failed to remove temp directory: %v" ErrFailedToCreateTempDir = "Failed to create temp directory: %v" ErrFailedToCreateSubdir = "Failed to create subdirectory: %v" ErrFailedToCreateTestFile = "Failed to create test file: %v" ErrFailedToRemoveSymlink = "Failed to remove symlink: %v" ErrFailedToGetWorkingDir = "Failed to get current working directory: %v" ErrFailedToChangeTempDir = "Failed to change to temporary directory: %v" )
TestErrors contains constants for test error messages - these maintain capitalization from the original test file
const ( ErrGettingTags = "error getting tags: %w" ErrNoVersionInfo = "no version information found for %s/%s" ErrGettingRefForTag = "error getting ref for tag %s: %w" ErrNoCommitHashForTag = "no commit hash found for tag %s" ErrGettingAnnotatedTag = "error getting annotated tag %s: %w" ErrNoCommitHashInTag = "no commit hash found in annotated tag %s" ErrContextIsNil = "context is nil" )
VersionCheckerErrors contains constants for version checker error messages
const ( ErrCreatingBranch = "error creating branch: %w" ErrCreatingCommit = "error creating commit: %w" ErrCreatingPR = "error creating pull request: %w" ErrGettingRepository = "error getting repository: %w" ErrGettingDefaultBranchRef = "error getting default branch ref: %w" ErrGettingFileContents = "error getting file contents: %w" ErrDecodingContent = "error decoding content: %w" ErrCreatingBlob = "error creating blob: %w" ErrGettingBranchRef = "error getting branch ref: %w" ErrCreatingTree = "error creating tree: %w" )
PRCreatorErrors contains constants for PR creator error messages
const ( ErrInvalidUpdatePath = "invalid update path: %w" ErrReadingUpdateFile = "error reading file: %w" ErrWritingUpdateFile = "error writing file: %w" ErrApplyingUpdates = "error applying updates: %w" )
UpdateManagerErrors contains constants for update manager error messages
const ( ErrCreatingGitHubClient = "error creating GitHub client: %w" ErrAuthentication = "authentication error: %w" ErrNetworkFailure = "network failure: %w" ErrRateLimitExceeded = "GitHub API rate limit exceeded: %w" ErrNoRateLimitInfo = "No rate limit information available" ErrRateLimitFormat = "Rate limit: %d/%d, resets in %s" ErrInvalidEnterpriseURL = "invalid enterprise URL: %w" // Token validation errors ErrInvalidGitHubToken = "invalid GitHub token: %w" // #nosec G101 - This is an error message, not a credential ErrFailedToValidateToken = "failed to validate token: %w" ErrTokenMissingScope = "token missing required scope: %s" ErrFailedToCheckScopes = "failed to check token scopes: %w" ErrNoScopesInResponse = "no scope information in API response" )
GitHubErrors contains constants for GitHub utility error messages
const ( ErrMissingRequiredFlag = "missing required flag: %s" ErrInvalidFlagValue = "invalid value for flag %s: %s" ErrCommandExecution = "error executing command: %w" ErrNoGithubToken = "" // #nosec G101 /* 163-byte string literal not displayed */ ErrNoWorkflowsFound = "No workflow files found" ErrNoUpdatesAvailable = "No updates available" ErrFailedToParseWorkflow = "Failed to parse %s: %v" ErrFailedToCheckAction = "Failed to check %s/%s: %v" ErrFailedToCheckUpdate = "Failed to check update availability for %s/%s: %v" ErrFailedToCreateUpdate = "Failed to create update for %s/%s: %v" )
CommandErrors contains constants for command line errors
const ( ErrGeneratingTestData = "error generating test data: %w" ErrInvalidTestParameters = "invalid test parameters: %s" ErrWorkflowCountMustBePositive = "Workflow count must be positive" ErrWorkflowCountExceedsLimit = "Workflow count exceeds maximum limit of %d" ErrCouldNotRemoveDummyFile = "Warning: could not remove dummy file: %v" )
TestToolErrors contains constants for test tool error messages
const ( // Repository operation failures ErrFailedToCreateRepoDir = "Failed to create repo directory: %v" ErrFailedToCreateWorkflowsDir = "Failed to create workflows directory: %v" ErrFailedToChangePermissions = "Failed to make directory read-only: %v" ErrFailedToRestorePermissions = "Failed to restore directory permissions: %v" ErrFailedToWriteWorkflowFile = "Failed to write invalid workflow file: %v" // Git operation failures ErrFailedToCloneRepo = "Failed to clone repository: %v" ErrFailedToCommitChanges = "Failed to commit changes: %v" ErrFailedToPushChanges = "Failed to push changes: %v" ErrFailedToCorruptGitConfig = "Failed to corrupt git config: %v" ErrFailedToCreateBranch = "Failed to create branch: %v" ErrFailedToWriteFile = "Failed to write file: %v" ErrFailedToStageChanges = "Failed to stage changes: %v" ErrFailedToAddRemote = "Failed to add remote: %v" ErrFailedToSwitchBranch = "Failed to switch branch: %v" // Setup/Cleanup failures ErrFailedToSetupTestEnv = "Failed to set up test environment: %v" ErrFailedToCleanupTestEnv = "Failed to clean up test environment: %v" // Validation failures ErrExpectedError = "Expected error %s, got nil" ErrUnexpectedError = "Expected no error, got: %v" ErrExpectedResult = "Expected result %v, got %v" ErrExpectedGitConfigError = "Expected error with corrupted git config, got nil" ErrExpectedPushError = "Expected error when pushing to non-existent remote, got nil" ErrUnexpectedErrorMessage = "Unexpected error message: %s" ErrExpectedCommitError = "Expected error when committing without staged changes, got nil" ErrExpectedBranchError = "Expected error when creating branch with invalid name, got nil" ErrExpectedMergeError = "Expected error when merging conflicting branches, got nil" ErrExpectedErrorContaining = "Expected error containing %q, got %q" // Version checker test errors ErrVersionCheckerNil = "NewDefaultVersionChecker() returned nil" ErrVersionCheckerClientNil = "NewDefaultVersionChecker() client is nil" ErrExpectedAuthClient = "Expected authenticated client, got unauthenticated" ErrExpectedUnauthClient = "Expected unauthenticated client, got authenticated" // File update test failures ErrFailedToReadUpdatedFile = "Failed to read updated file: %v" ErrExpectedContentNotFound = "Expected %q to be in the updated content, but it wasn't.\nUpdated content:\n%s" ErrExpectedNonExistentFileError = "Expected error for non-existent file, got nil" ErrExpectedInvalidLineError = "Expected error for invalid line number, got nil" ErrFailedToRemoveTestFile = "Failed to remove test file: %v" ErrExpectedOutsidePathError = "Expected error for file outside base directory, got nil" ErrExpectedReadOnlyFileError = "Expected error for read-only file, but got nil. This might be system-dependent." ErrFailedToCreateEmptyFile = "Failed to create empty file: %v" ErrFailedToReadEmptyFile = "Failed to read empty file after update: %v" ErrExpectedVersionComment = "Expected empty file to contain version comment, got content: %s" ErrFailedToCreateSpecialFile = "Failed to create special file: %v" ErrFailedToReadSpecialFile = "Failed to read updated special file: %v" ErrFailedToCreateSameLineFile = "Failed to create same line file: %v" ErrFailedToReadSameLineFile = "Failed to read updated same line file: %v" // Scanner test errors ErrFailedToSetTempDirPermissions = "Failed to set temp dir permissions: %v" ErrFailedToSetupTest = "Failed to set up test: %v" ErrExpectedActions = "Expected %d actions, got %d" ErrExpectedWorkflows = "Expected %d workflows, got %d" ErrExpectedEmptyCommitHash = "Expected empty commit hash for %s, got %q" ErrExpectedCommitHash = "Expected commit hash %s, got %q" ErrExpectedVersionFromComment = "Expected version %s from comment, got %q" ErrFailedToCreateTestFileNamed = "Failed to create test file %s: %v" ErrSpecificWorkflowNotFound = "%s not found" ErrUnexpectedWorkflowFile = "Unexpected workflow file: %s" ErrUnexpectedActionFound = "Unexpected action: %s/%s@%s" // Additional test failures ErrWorkDirNotCreated = "Work directory not created: %v" ErrWrongDirectoryPermissions = "Wrong directory permissions: got %v, want %v" ErrWorkDirNotCleanedUp = "Work directory not cleaned up properly" ErrFailedToReadGitConfig = "Failed to read git config: %v" ErrGitConfigMissingValue = "Git config missing expected value: %s" ErrExpectedDifferentPaths = "Expected different repo paths for separate clones" ErrWorkflowFileNotFound = "Workflow file not found in %s" ErrFailedToStatFile = "Failed to stat file: %v" ErrWorkflowMissingContent = "Workflow file missing expected content: %s" ErrFailedToChangeFilePermissions = "Failed to change file permissions: %v" )
TestFailureErrors contains constants for test failure messages
const ( // Token type prefixes TokenTypePATClassic = "ghp" TokenTypePATFineGrained = "github_pat" TokenTypeOAuth = "gho" TokenTypeInstallation = "ghs" TokenTypeUserToServer = "ghu" )
const (
ErrFailedToCloseBody = "Failed to close response body: %v"
)
const (
// MaxPathLength defines the maximum allowed path length
MaxPathLength = 255
)
Variables ¶
This section is empty.
Functions ¶
func AddLabelsToIssue ¶
func AddLabelsToIssue(ctx context.Context, client *github.Client, owner, repo string, number int, labels []string) error
AddLabelsToIssue adds labels to an issue or pull request with retry logic
func AppendToFile ¶
AppendToFile appends content to a file
func AppendToFileString ¶
AppendToFileString appends a string to a file
func CalculateBackoff ¶ added in v1.20250601.1
CalculateBackoff returns the next backoff duration with jitter for exponential backoff
func ContainsAll ¶
ContainsAll checks if a string contains all of the given substrings
func ContainsAny ¶
ContainsAny checks if a string contains any of the given substrings
func CreatePullRequest ¶
func CreatePullRequest(ctx context.Context, client *github.Client, owner, repo string, pull *github.NewPullRequest) (*github.PullRequest, error)
CreatePullRequest creates a pull request with retry logic
func CreateRef ¶
func CreateRef(ctx context.Context, client *github.Client, owner, repo string, ref *github.Reference) error
CreateRef creates a reference (branch, tag) with retry logic
func ExecuteWithRetry ¶
func ExecuteWithRetry(ctx context.Context, client *github.Client, maxRetries int, retryDelay time.Duration, fn func() (*github.Response, error)) error
ExecuteWithRetry executes a GitHub API request with retry logic for rate limiting
func FindFilesWithExtension ¶
FindFilesWithExtension finds all files with the given extension in a directory
func GetLatestRelease ¶
func GetLatestRelease(ctx context.Context, client *github.Client, owner, repo string) (*github.RepositoryRelease, error)
GetLatestRelease gets the latest release for a repository with retry logic
func GetRef ¶
func GetRef(ctx context.Context, client *github.Client, owner, repo, ref string) (*github.Reference, error)
GetRef gets a reference (branch, tag) with retry logic
func IsHexString ¶
IsHexString checks if a string is a valid hexadecimal string (for commit SHAs)
func IsPathSafe ¶
IsPathSafe is a simplified version that just checks if a path is within a base directory
func IsRegularFile ¶
IsRegularFile checks if a path is a regular file
func IsValidGitHubToken ¶ added in v1.20250813.1
IsValidGitHubToken is a simple validation check
func JoinAndValidatePath ¶
JoinAndValidatePath joins path elements and validates the result
func JoinNonEmpty ¶
JoinNonEmpty joins non-empty strings with the given separator
func ModifyLines ¶
ModifyLines modifies lines in a file using a function
func NewGitHubClient ¶
func NewGitHubClient(options GitHubClientOptions) *github.Client
NewGitHubClient creates a new GitHub client with the given options
func NewGitHubClientWithToken ¶
NewGitHubClientWithToken creates a new GitHub client with just a token
func ReadFileString ¶
ReadFileString reads a file and returns its contents as a string
func ReadFileWithOptions ¶
func ReadFileWithOptions(path string, options FileOptions) ([]byte, error)
ReadFileWithOptions reads a file with the given options
func ReplaceInFile ¶
ReplaceInFile replaces content in a file
func SplitAndTrim ¶
SplitAndTrim splits a string by the given separator and trims each part
func TrimPrefixAny ¶
TrimPrefixAny trims any of the given prefixes from the string
func TrimSuffixAny ¶
TrimSuffixAny trims any of the given suffixes from the string
func ValidatePath ¶
func ValidatePath(baseDir, path string, options PathValidationOptions) error
ValidatePath ensures the path is safe and within the allowed directory baseDir is the root directory that all paths must be contained within path is the path to validate options provides configuration for the validation process
func ValidatePathWithDefaults ¶
ValidatePathWithDefaults validates a path using default options
func ValidateTokenScopes ¶ added in v1.20250531.2
ValidateTokenScopes validates that the GitHub token has the required scopes It checks if the token is valid and has the necessary permissions to perform operations like reading repositories, modifying workflows, and creating pull requests.
func WriteFileString ¶
WriteFileString writes a string to a file
func WriteFileWithOptions ¶
func WriteFileWithOptions(path string, data []byte, options FileOptions) error
WriteFileWithOptions writes data to a file with the given options
func WriteLines ¶
WriteLines writes lines to a file
Types ¶
type FileLockManager ¶
type FileLockManager struct {
// contains filtered or unexported fields
}
FileLockManager manages locks for file operations to prevent concurrent access
func NewFileLockManager ¶
func NewFileLockManager() *FileLockManager
NewFileLockManager creates a new file lock manager
func (*FileLockManager) GetLock ¶
func (m *FileLockManager) GetLock(path string) *sync.Mutex
GetLock gets or creates a lock for the given file path
func (*FileLockManager) LockFile ¶
func (m *FileLockManager) LockFile(path string)
LockFile locks a file for exclusive access
func (*FileLockManager) UnlockFile ¶
func (m *FileLockManager) UnlockFile(path string)
UnlockFile unlocks a file
func (*FileLockManager) WithFileLock ¶
func (m *FileLockManager) WithFileLock(path string, fn func() error) error
WithFileLock executes a function with a lock on the given file
type FileOptions ¶
type FileOptions struct { // CreateDirs if true, creates parent directories if they don't exist CreateDirs bool // Mode is the file mode to use when creating files Mode os.FileMode // BaseDir is the base directory for path validation BaseDir string // ValidateOptions are the options for path validation ValidateOptions PathValidationOptions }
FileOptions provides options for file operations
func DefaultFileOptions ¶
func DefaultFileOptions() FileOptions
DefaultFileOptions returns the default options for file operations
type GitHubClientOptions ¶
type GitHubClientOptions struct { // Token is the GitHub API token Token string // BaseURL is the base URL for the GitHub API (optional, for GitHub Enterprise) BaseURL string // Timeout is the default timeout for API requests Timeout time.Duration // RetryCount is the number of times to retry failed requests RetryCount int // RetryDelay is the base delay for exponential backoff retries RetryDelay time.Duration // MaxRetryDelay is the maximum delay between retries MaxRetryDelay time.Duration }
GitHubClientOptions provides configuration options for GitHub client creation
func DefaultGitHubClientOptions ¶
func DefaultGitHubClientOptions() GitHubClientOptions
DefaultGitHubClientOptions returns the default options for GitHub client creation
type PathValidationOptions ¶
type PathValidationOptions struct { // RequireRegularFile if true, validates that the path points to a regular file RequireRegularFile bool // AllowNonExistent if true, allows paths that don't exist yet AllowNonExistent bool // CheckSymlinks if true, validates that symlinks don't point outside the base directory CheckSymlinks bool // MaxPathLength specifies the maximum allowed path length (defaults to 255 if not set) MaxPathLength int }
PathValidationOptions provides configuration options for path validation
func DefaultPathValidationOptions ¶
func DefaultPathValidationOptions() PathValidationOptions
DefaultPathValidationOptions returns the default options for path validation
type RateLimitHandler ¶
type RateLimitHandler struct {
// contains filtered or unexported fields
}
RateLimitHandler provides rate limit handling for GitHub API requests
func NewRateLimitHandler ¶
func NewRateLimitHandler(client *github.Client, maxRetries int, baseDelay time.Duration) *RateLimitHandler
NewRateLimitHandler creates a new rate limit handler for the given client
func NewRateLimitHandlerWithOptions ¶ added in v1.20250601.1
func NewRateLimitHandlerWithOptions(client *github.Client, maxRetries int, baseDelay, maxDelay time.Duration) *RateLimitHandler
NewRateLimitHandlerWithOptions creates a new rate limit handler with full configuration
func (*RateLimitHandler) GetRateLimitInfo ¶
func (h *RateLimitHandler) GetRateLimitInfo() string
GetRateLimitInfo returns information about the current rate limit
func (*RateLimitHandler) HandleRateLimit ¶
func (h *RateLimitHandler) HandleRateLimit(resp *github.Response, err error) bool
HandleRateLimit handles rate limiting for GitHub API requests It returns true if the request should be retried, and false otherwise
type TokenInfo ¶ added in v1.20250813.1
TokenInfo contains information about a validated token
func ValidateGitHubToken ¶ added in v1.20250813.1
ValidateGitHubToken validates the format of a GitHub token