git

package
v0.89.0-rc.2 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	ZeroSHA               = "0000000000000000000000000000000000000000" // ZeroSHA represents a non-existent commit
	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"
)

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 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 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

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 HttpTokenAuth added in v0.58.0

func HttpTokenAuth(token string) transport.AuthMethod

HttpTokenAuth returns an AuthMethod for HTTP Basic Auth using a token.

func IsCorruptionError

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 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

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 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 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.

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 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 retrieves a RefSet of local and remote references for a given reference name. It also resolves the remote reference to a commit hash (when available) and fills RemoteHash.

type ResolvedAuthConfig added in v0.88.0

type ResolvedAuthConfig struct {
	SSHPrivateKey           string
	SSHPrivateKeyPassphrase string
	GitAccessToken          string
	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"`
	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