git

package
v0.113.0 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2026 License: Apache-2.0 Imports: 38 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultShortSHALength = 7 // Default length for shortened commit SHAs
	RemoteName            = "origin"
	TagPrefix             = "refs/tags/"
	BranchPrefix          = "refs/heads/"
	MainBranch            = "refs/heads/main"
	SwarmModeBranch       = "refs/heads/swarm-mode"
)
View Source
const DefaultHTTPAuthUser = "oauth2"

DefaultHTTPAuthUser is the Basic Auth username used when none is configured. Most providers accept any non-empty username for token auth, but GitLab deploy tokens require their specific username (e.g. gitlab+deploy-token-123), which callers supply via GIT_ACCESS_TOKEN_USER / GIT_AUTH_DOMAINS git_access_token_user.

Variables

View Source
var (
	ErrMissingAuthToken           = errors.New("missing access token")
	ErrCheckoutFailed             = errors.New("failed to checkout repository")
	ErrFetchFailed                = errors.New("failed to fetch repository")
	ErrRepositoryNotExists        = git.ErrRepositoryNotExists
	ErrRepositoryAlreadyExists    = git.ErrRepositoryAlreadyExists
	ErrInvalidReference           = git.ErrInvalidReference
	ErrSSHKeyRequired             = errors.New("ssh URL requires SSH_PRIVATE_KEY to be set")
	ErrPossibleAuthMethodMismatch = errors.New("there might be a mismatch between the authentication method and the repository or submodule remote URL")
	ErrRemoteURLMismatch          = errors.New("remote URL does not match expected URL")
	ErrGetHeadFailed              = errors.New("failed to get HEAD reference")
)

Functions

func AcquirePathLock added in v0.68.0

func AcquirePathLock(key string) func()

AcquirePathLock locks the mutex for the given key and returns a function to unlock it. The returned unlock function is idempotent (safe to call multiple times).

func CheckoutRepository added in v0.13.0

func CheckoutRepository(repo *git.Repository, ref string, auth transport.AuthMethod, cloneSubmodules bool, depth ...int) error

CheckoutRepository checks out the specified reference in the repository, keeping untracked files intact. If cloneSubmodules is true, submodules will be initialized/updated using the provided auth. depth controls the shallow depth for submodule updates (0 = full).

func CloneOrUpdateRepository added in v0.82.0

func CloneOrUpdateRepository(log *slog.Logger,
	cloneUrl string, ref string, internalRepoPath, externalRepoPath string,
	private bool, sshPrivateKey string, sshPrivateKeyPassphrase string, gitAccessToken string,
	skipTLSVerify bool, proxyOpts transport.ProxyOptions, cloneSubmodules bool, depth int,
) (*git.Repository, error)

func CloneRepository

func CloneRepository(path, url, ref string, skipTLSVerify bool, proxyOpts transport.ProxyOptions, auth transport.AuthMethod, cloneSubmodules bool, depth int) (*git.Repository, error)

CloneRepository clones a repository with HTTP or SSH auth. If depth > 0, a shallow clone is performed with the specified number of commits.

func ConfigureAuthResolver added in v0.86.0

func ConfigureAuthResolver(scoped []ScopedAuthConfig,
	globalPrivateKey, globalKeyPassphrase, globalToken, globalHTTPAuthUser string,
	globalGitHubApp GitHubAppConfig,
)

ConfigureAuthResolver configures domain-scoped and global Git credentials. This should be called when application config is loaded or updated.

func ConvertSSHUrl added in v0.65.0

func ConvertSSHUrl(url string) string

ConvertSSHUrl converts SSH URLs to the ssh:// format. e.g. convert git@github.com:user/repo.git to ssh://git@github.com/user/repo.git

func FetchRepository added in v0.66.0

func FetchRepository(repo *git.Repository, url string, skipTLSVerify bool, proxyOpts transport.ProxyOptions, auth transport.AuthMethod, depth int) error

FetchRepository fetches updates from the remote repository, including all branches and tags, and prunes deleted references. If depth > 0, a shallow fetch is performed with the specified number of commits.

func FormatGitErrorMessage added in v0.107.0

func FormatGitErrorMessage(err error) string

FormatGitErrorMessage formats a git operation error message by attempting to decode any localized error response bodies embedded in it (e.g. from Azure DevOps Server). It returns the formatted error message suitable for logging.

func GetAuthMethod added in v0.65.0

func GetAuthMethod(url, privateKey, keyPassphrase, token string) (transport.AuthMethod, error)

GetAuthMethod determines the appropriate authentication method based on the URL and provided credentials.

func GetFullName added in v0.83.0

func GetFullName(cloneURL string) string

GetFullName extracts the full repository name without the domain part from the clone URL. E.g., "github.com/kimdre/doco-cd" becomes "kimdre/doco-cd" or "git.example.com/doco-cd" becomes "doco-cd".

func GetLatestCommit added in v0.22.0

func GetLatestCommit(repo *git.Repository, ref string) (string, error)

GetLatestCommit retrieves the last commit hash for a given reference in a repository.

func GetRepoName added in v0.65.0

func GetRepoName(cloneURL string) string

GetRepoName returns the repository name in the form "<host>/<owner>/<repo>" from the given clone URL. Supports:

func GetShortestUniqueCommitHash added in v0.89.0

func GetShortestUniqueCommitHash(repo *git.Repository, commitSHA string, minLength int) (string, error)

GetShortestUniqueCommitHash returns the shortest unique prefix of a commit SHA in the repository. Similar to the git command `git rev-parse --short=<length> <commitSHA>`.

func HeadMatchesCommit added in v0.112.0

func HeadMatchesCommit(repoPath, commitSHA string) (bool, error)

HeadMatchesCommit reports whether the repository at path has exactly the given commit SHA at HEAD. Returns false (no error) when the repository does not exist or HEAD cannot be resolved, so callers can treat a false result as "go ahead and fetch".

func HttpTokenAuth added in v0.58.0

func HttpTokenAuth(username, token string) transport.AuthMethod

HttpTokenAuth returns an AuthMethod for HTTP Basic Auth using a token. An empty username falls back to DefaultHTTPAuthUser.

func IsCorruptionError added in v0.89.0

func IsCorruptionError(err error) bool

IsCorruptionError checks if an error indicates repository corruption rather than transient failures. Corruption is indicated by reference not found errors when fetches have completed successfully.

func IsLocalFile added in v0.111.0

func IsLocalFile(url string) bool

IsLocalFile checks if a given URL points to a local filesystem Git repository (file:// scheme).

func IsRefUnreachableError added in v0.107.0

func IsRefUnreachableError(err error) bool

IsRefUnreachableError returns true when the error indicates the requested ref could not be found, which in a shallow clone likely means the ref is outside the fetched depth.

func IsSSH added in v0.57.0

func IsSSH(url string) bool

IsSSH checks if a given URL is an SSH URL.

func MatchesHead added in v0.68.0

func MatchesHead(path, ref string) (bool, error)

MatchesHead inspects an existing repository at path and determines if HEAD is at the specified reference (branch, tag, or commit SHA).

func OpenRepository added in v0.64.0

func OpenRepository(path string) (*git.Repository, error)

OpenRepository opens an existing git repository at the specified path. This is a lightweight operation that doesn't fetch or update the repository.

func RepairRepository added in v0.89.0

func RepairRepository(
	path, url, ref string,
	skipTLSVerify bool, proxyOpts transport.ProxyOptions, auth transport.AuthMethod,
	cloneSubmodules bool, depth int,
	logger *slog.Logger,
) (*git.Repository, error)

RepairRepository attempts to fix a corrupted Git repository. It first tries lightweight repairs (validation), then falls back to re-cloning if needed. It emits warnings when corruption is detected and recovered. Returns the repaired repository or an error if repair fails.

func ResetTrackedFiles added in v0.26.1

func ResetTrackedFiles(repo *git.Repository) error

ResetTrackedFiles resets all tracked files in the worktree To their last committed state while leaving untracked files intact.

func ResolveHTTPToken added in v0.110.0

func ResolveHTTPToken(url string, resolved ResolvedAuthConfig) (string, error)

ResolveHTTPToken returns the access token to use for HTTP(S) requests (git transport as well as SCM API calls like commit status posting) against a repository URL. It prefers an explicit GitAccessToken and falls back to minting a short-lived GitHub App installation token from resolved.GitHubApp when no access token is configured. Returns an empty string (and no error) when neither credential is configured.

func ResolveScopedCredentials added in v0.86.0

func ResolveScopedCredentials(url, privateKey, keyPassphrase, token string) (string, string, string)

ResolveScopedCredentials resolves credentials for a repository URL using exact domain matches, then the most specific wildcard suffix, and finally global fallback credentials.

func SSHAuth added in v0.58.0

func SSHAuth(privateKey, keyPassphrase string) (transport.AuthMethod, error)

SSHAuth creates an SSH authentication method using the provided private key.

func SwapGitHubAppTokenProviderForTest added in v0.110.0

func SwapGitHubAppTokenProviderForTest(provider func(string, GitHubAppConfig) (string, error)) func()

SwapGitHubAppTokenProviderForTest replaces the GitHub App token provider and returns a restore function.

func UpdateRepository added in v0.16.0

func UpdateRepository(path, url, ref string, skipTLSVerify bool, proxyOpts transport.ProxyOptions, auth transport.AuthMethod, cloneSubmodules bool, depth int) (*git.Repository, error)

UpdateRepository fetches and checks out the requested ref. If depth > 0, shallow fetches are used. When the requested ref is not reachable within the current depth, the repository is incrementally deepened before falling back to a full fetch.

func WatchLocalGitRef added in v0.111.0

func WatchLocalGitRef(ctx context.Context, repoURL string, log *slog.Logger) (<-chan struct{}, error)

WatchLocalGitRef watches a local git repository for changes to branch refs or packed-refs, signaling on the returned channel whenever new commits may have landed.

The channel is buffered (capacity 1) so a missed tick is never blocking; at most one pending notification is queued at a time. The watcher stops and closes the channel when ctx is canceled.

repoURL must be a file:// URL (e.g. "file:///path/to/repo").

Types

type ChangedFile added in v0.29.0

type ChangedFile struct {
	// From represents the file state before the change.
	From diff.File
	// To represents the file state after the change.
	To diff.File
}

ChangedFile represents a file that has changed between two commits.

func GetChangedFilesBetweenCommits added in v0.29.0

func GetChangedFilesBetweenCommits(repo *git.Repository, commitHash1, commitHash2 plumbing.Hash) ([]ChangedFile, error)

GetChangedFilesBetweenCommits retrieves a list of changed files between two commits in a repository.

type CommitInfo added in v0.104.0

type CommitInfo struct {
	Hash      string
	ShortHash string
	Subject   string
	Author    string
}

CommitInfo is a single commit exposed to notification templates.

func GetCommitsBetween added in v0.104.0

func GetCommitsBetween(repo *git.Repository, oldHash, newHash plumbing.Hash, maxCommits int) ([]CommitInfo, error)

GetCommitsBetween returns commits reachable from newHash but not from oldHash, newest first, capped at maxCommits.

func (CommitInfo) String added in v0.104.0

func (c CommitInfo) String() string

String renders "shortHash subject", the default when a template prints a commit directly.

type GitHubAppConfig added in v0.88.0

type GitHubAppConfig struct {
	ID             string
	PrivateKey     string
	InstallationID int64
}

GitHubAppConfig contains credentials used to mint short-lived GitHub App installation tokens.

type RefSet added in v0.22.0

type RefSet struct {
	LocalRef   plumbing.ReferenceName
	RemoteRef  plumbing.ReferenceName
	RemoteHash plumbing.Hash
}

func GetReferenceSet added in v0.22.0

func GetReferenceSet(repo *git.Repository, ref string) (RefSet, error)

GetReferenceSet resolves ref to the local and remote plumbing.ReferenceName to use during checkout, along with the resolved remote commit hash.

Resolution order (first match wins):

  1. Commit SHA — returned directly; no reference store lookup is performed.
  2. For refs/-prefixed names: the exact name, then its remote-tracking counterpart.
  3. For short names: refs/heads/<ref>, refs/remotes/origin/<ref>, refs/tags/<ref>, then the bare name (which only resolves for uppercase pseudo-refs like HEAD).

Candidates whose name cannot be stored safely (see plumbing.ReferenceName.IsSafe) are skipped rather than queried, so a malformed ref yields ErrInvalidReference instead of a storage-layer error. Any other storage error is treated as a transient failure and returned immediately.

type ResolvedAuthConfig added in v0.88.0

type ResolvedAuthConfig struct {
	SSHPrivateKey           string
	SSHPrivateKeyPassphrase string
	GitAccessToken          string
	HTTPAuthUser            string // HTTPAuthUser is the Basic Auth username for token auth; empty defaults to DefaultHTTPAuthUser.
	GitHubApp               GitHubAppConfig
}

ResolvedAuthConfig contains the final credentials selected for a given repository URL.

func ResolveAuthConfig added in v0.88.0

func ResolveAuthConfig(url, privateKey, keyPassphrase, token string) ResolvedAuthConfig

ResolveAuthConfig resolves credentials for a repository URL using exact domain matches, then the most specific wildcard suffix, and finally global fallback credentials.

type ScopedAuthConfig added in v0.86.0

type ScopedAuthConfig struct {
	Domains                 []string `yaml:"domains"`
	GitAccessToken          string   `yaml:"git_access_token"`
	GitAccessTokenUser      string   `yaml:"git_access_token_user"` // GitAccessTokenUser is the username paired with GitAccessToken (e.g. a GitLab deploy token username). Empty defaults to DefaultHTTPAuthUser.
	SSHPrivateKey           string   `yaml:"ssh_private_key"`
	SSHPrivateKeyPassphrase string   `yaml:"ssh_private_key_passphrase"`
	GitHubAppID             string   `yaml:"github_app_id"`
	GitHubAppPrivateKey     string   `yaml:"github_app_private_key"`
	GitHubAppInstallationID int64    `yaml:"github_app_installation_id"`
}

ScopedAuthConfig maps credentials to one or more Git host/domain patterns. Patterns support exact hosts (e.g. github.com) and wildcard subdomains (e.g. *.example.com).

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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