git

package
v1.8.9 Latest Latest
Warning

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

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

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidRepoURL = errors.New("repo URL is invalid")
	ErrNoNoteFound    = errors.New("no note found")
)
View Source
var BuiltinGitConfigEnv []string

BuiltinGitConfigEnv contains builtin git configuration in the format acceptable by Git.

View Source
var SupportedFIPSCompliantSSHKeyExchangeAlgorithms = []string{
	"ecdh-sha2-nistp256",
	"ecdh-sha2-nistp384",
	"ecdh-sha2-nistp521",
	"diffie-hellman-group-exchange-sha256",
	"diffie-hellman-group14-sha256",
}

SupportedFIPSCompliantSSHKeyExchangeAlgorithms is a list of all currently supported algorithms for SSH key exchange that are FIPS compliant

View Source
var SupportedSSHKeyExchangeAlgorithms = []string{
	"curve25519-sha256",
	"curve25519-sha256@libssh.org",
	"ecdh-sha2-nistp256",
	"ecdh-sha2-nistp384",
	"ecdh-sha2-nistp521",
	"diffie-hellman-group-exchange-sha256",
	"diffie-hellman-group14-sha256",
	"diffie-hellman-group14-sha1",
}

SupportedSSHKeyExchangeAlgorithms is a list of all currently supported algorithms for SSH key exchange Unfortunately, crypto/ssh does not offer public constants or list for this.

Functions

func DiscoverGitHubAppInstallationID added in v1.8.8

func DiscoverGitHubAppInstallationID(ctx context.Context, appId int64, privateKey, enterpriseBaseURL, org string, httpClient ...*http.Client) (int64, error)

DiscoverGitHubAppInstallationID discovers the GitHub App installation ID for a given organization. It queries the GitHub API to list all installations for the app and returns the installation ID for the matching organization. Results are cached to avoid redundant API calls. An optional HTTP client can be provided for custom transport (e.g., for metrics tracking).

func ExtractOrgFromRepoURL added in v1.8.8

func ExtractOrgFromRepoURL(repoURL string) (string, error)

ExtractOrgFromRepoURL extracts the organization/owner name from a GitHub repository URL. Supports formats:

  • HTTPS: https://github.com/org/repo.git
  • SSH: git@github.com:org/repo.git
  • SSH with port: git@github.com:22/org/repo.git or ssh://git@github.com:22/org/repo.git

func GetRepoHTTPClient added in v1.2.0

func GetRepoHTTPClient(repoURL string, insecure bool, creds Creds, proxyURL string, noProxy string) *http.Client

Returns a HTTP client object suitable for go-git to use using the following pattern:

  • If insecure is true, always returns a client with certificate verification turned off.
  • If one or more custom certificates are stored for the repository, returns a client with those certificates in the list of root CAs used to verify the server's certificate.
  • Otherwise (and on non-fatal errors), a default HTTP client is returned.

func IsCommitSHA added in v0.6.0

func IsCommitSHA(sha string) bool

IsCommitSHA returns whether or not a string is a 40 character SHA-1

func IsHTTPSURL added in v1.2.0

func IsHTTPSURL(url string) bool

IsHTTPSURL returns true if supplied URL is HTTPS URL

func IsHTTPURL added in v1.8.8

func IsHTTPURL(url string) bool

IsHTTPURL returns true if supplied URL is HTTP URL

func IsSSHURL added in v0.4.0

func IsSSHURL(url string) (bool, string)

IsSSHURL returns true if supplied URL is SSH URL

func IsShortRef added in v1.8.8

func IsShortRef(revision string) bool

IsShortRef determines if the supplied revision is a short ref (e.g. "master" instead of "refs/heads/master"). ref.Name().Short() is an expensive call to be performed in a loop over all refs in a repository, so we want to avoid calling it if we can determine up front that the supplied revision is not a short ref. The intention is to optimize for a case where the full ref string is supplied, as comparing the full ref string is cheaper than calling Short() on every ref in the loop. If the supplied revision is a short ref, we will compare it with the short version of each ref in the loop. If the supplied revision is not a short ref, we will compare it with the full ref string in the loop, which is cheaper than calling Short() on every ref. This performance optimization is based on the observation coming from larger repositories where the number of refs can be in the order of tens of thousands, and we want to avoid calling Short() on every ref if we can determine up front that the supplied revision is not a short ref.

func IsTruncatedCommitSHA added in v0.9.0

func IsTruncatedCommitSHA(sha string) bool

IsTruncatedCommitSHA returns whether or not a string is a truncated SHA-1

func NormalizeGitURL

func NormalizeGitURL(repo string) string

NormalizeGitURL normalizes a git URL for purposes of comparison, as well as preventing redundant local clones (by normalizing various forms of a URL to a consistent location). Prefer using SameURL() over this function when possible. This algorithm may change over time and should not be considered stable from release to release

func NormalizeGitURLAllowInvalid added in v1.8.8

func NormalizeGitURLAllowInvalid(repo string) string

NormalizeGitURLAllowInvalid is similar to NormalizeGitURL, except returning an original url if the url is invalid. Needed to allow a deletion of repos with invalid urls. See https://github.com/argoproj/argo-cd/issues/20921.

func SSHHostWithPort added in v1.8.8

func SSHHostWithPort(repoURL string) string

SSHHostWithPort returns host:port for the given SSH repo URL in the format expected by known_hosts lookups (net.JoinHostPort). Returns an empty string for non-SSH URLs, URLs that cannot be parsed, or URLs without a host. Port defaults to 22 when not present.

func SameURL added in v0.11.0

func SameURL(leftRepo, rightRepo string) bool

func SanitizeRepoURL added in v1.8.8

func SanitizeRepoURL(repoURL string) string

SanitizeRepoURL strips any embedded userinfo (e.g. https://token@host/org/repo) from a repository URL so credentials are not leaked when the URL is logged or exported (e.g. as a tracing span attribute). If the URL cannot be parsed it is returned unchanged.

func TestRepo

func TestRepo(repo string, creds Creds, insecure bool, enableLfs bool, proxy string, noProxy string) error

TestRepo tests if a repo exists and is accessible with the given credentials

Types

type AzureServicePrincipalCreds added in v1.8.8

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

AzureServicePrincipalCreds to authenticate to Azure DevOps using a Service Principal

func NewAzureServicePrincipalCreds added in v1.8.8

func NewAzureServicePrincipalCreds(tenantID string, clientID string, clientSecret string, store CredsStore) AzureServicePrincipalCreds

NewAzureServicePrincipalCreds creates new Azure Service Principal credentials

func (AzureServicePrincipalCreds) Environ added in v1.8.8

func (a AzureServicePrincipalCreds) Environ() (io.Closer, []string, error)

func (AzureServicePrincipalCreds) GetClientCertData added in v1.8.8

func (a AzureServicePrincipalCreds) GetClientCertData() string

func (AzureServicePrincipalCreds) GetClientCertKey added in v1.8.8

func (a AzureServicePrincipalCreds) GetClientCertKey() string

func (AzureServicePrincipalCreds) GetUserInfo added in v1.8.8

GetUserInfo doesn't return any user info as they are not present for Azure Service Principals.

func (AzureServicePrincipalCreds) HasClientCert added in v1.8.8

func (a AzureServicePrincipalCreds) HasClientCert() bool

func (AzureServicePrincipalCreds) WithActiveDirectoryEndpoint added in v1.8.8

func (a AzureServicePrincipalCreds) WithActiveDirectoryEndpoint(activeDirectoryEndpoint string) AzureServicePrincipalCreds

WithActiveDirectoryEndpoint sets a custom Active Directory endpoint. When not set, the default Azure public cloud is used.

func (AzureServicePrincipalCreds) WithClientCert added in v1.8.8

WithClientCert sets the client certificate data and key

func (AzureServicePrincipalCreds) WithNoProxy added in v1.8.8

WithNoProxy sets a comma separated list of IPs/hostnames that should not use the proxy

func (AzureServicePrincipalCreds) WithProxy added in v1.8.8

WithProxy sets the HTTP/HTTPS proxy used to access the repo

type AzureWorkloadIdentityCreds added in v1.8.8

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

func NewAzureWorkloadIdentityCreds added in v1.8.8

func NewAzureWorkloadIdentityCreds(store CredsStore, tokenProvider workloadidentity.TokenProvider) AzureWorkloadIdentityCreds

func (AzureWorkloadIdentityCreds) Environ added in v1.8.8

func (creds AzureWorkloadIdentityCreds) Environ() (io.Closer, []string, error)

func (AzureWorkloadIdentityCreds) GetAzureDevOpsAccessToken added in v1.8.8

func (creds AzureWorkloadIdentityCreds) GetAzureDevOpsAccessToken() (string, error)

func (AzureWorkloadIdentityCreds) GetUserInfo added in v1.8.8

func (creds AzureWorkloadIdentityCreds) GetUserInfo(_ context.Context) (string, string, error)

GetUserInfo returns the username and email address for the credentials, if they're available.

type Client

type Client interface {
	Root() string
	RepoURL() string
	Init() error
	Fetch(ctx context.Context, revision string, depth int64) error
	Submodule(ctx context.Context) error
	Checkout(ctx context.Context, revision string, submoduleEnabled bool, cleanState bool) (string, error)
	LsRefs() (*Refs, error)
	LsRemote(revision string) (string, error)
	LsFiles(ctx context.Context, path string, enableNewGitFileGlobbing bool) ([]string, error)
	LsLargeFiles(ctx context.Context) ([]string, error)
	CommitSHA(ctx context.Context) (string, error)
	RevisionMetadata(ctx context.Context, revision string) (*RevisionMetadata, error)
	// Deprecated: To be removed in the next major version when Signature verification is replaced with Source Integrity.
	VerifyCommitSignature(ctx context.Context, revision string) (string, error)
	// IsAnnotatedTag determines if the revision is, or resolves to an annotated tag.
	IsAnnotatedTag(ctx context.Context, revision string) bool
	// LsSignatures gets a list of revisions including their GPG signature info.
	// If revision is an annotated tag or a semantic constraint matching an annotated tag, its signature is reported as well
	// If deep==true, list the commits backwards in history until a signed "seal commit" or repo init commit. The listing includes those seal commits.
	// If deep==false, examines the revision only. Checking the annotated tag signature if the revision is an annotated tag, commit signature otherwise.
	LsSignatures(ctx context.Context, revision string, deep bool) ([]RevisionSignatureInfo, string, error)
	ChangedFiles(ctx context.Context, revision string, targetRevision string) ([]string, error)
	IsRevisionPresent(ctx context.Context, revision string) bool
	// SetAuthor sets the author name and email in the git configuration.
	SetAuthor(ctx context.Context, name, email string) (string, error)
	// CheckoutOrOrphan checks out the branch. If the branch does not exist, it creates an orphan branch.
	CheckoutOrOrphan(ctx context.Context, branch string, submoduleEnabled bool) (string, error)
	// CheckoutOrNew checks out the given branch. If the branch does not exist, it creates an empty branch based on
	// the base branch.
	CheckoutOrNew(ctx context.Context, branch, base string, submoduleEnabled bool) (string, error)
	// RemoveContents removes all files from the given paths in the git repository.
	RemoveContents(ctx context.Context, paths []string) (string, error)
	// CommitAndPush commits and pushes changes to the target branch.
	CommitAndPush(ctx context.Context, branch, message string) (string, error)
	// GetCommitNote gets the note associated with the DRY sha stored in the specific namespace
	GetCommitNote(ctx context.Context, sha string, namespace string) (string, error)
	// AddAndPushNote adds a note to a DRY sha and then pushes it.
	AddAndPushNote(ctx context.Context, sha string, namespace string, note string) error
	// HasFileChanged returns the outout of git diff considering whether it is tracked or un-tracked
	HasFileChanged(ctx context.Context, filePath string) (bool, error)
}

Client is a generic git client interface

func NewClient added in v1.3.0

func NewClient(rawRepoURL string, creds Creds, insecure bool, enableLfs bool, proxy string, noProxy string, opts ...ClientOpts) (Client, error)

func NewClientExt added in v1.3.0

func NewClientExt(rawRepoURL string, root string, creds Creds, insecure bool, enableLfs bool, proxy string, noProxy string, opts ...ClientOpts) (Client, error)

type ClientOpts added in v1.8.8

type ClientOpts func(c *nativeGitClient)

func WithBuiltinGitConfig added in v1.8.8

func WithBuiltinGitConfig(enable bool) ClientOpts

func WithCache added in v1.8.8

func WithCache(cache gitRefCache, loadRefFromCache bool) ClientOpts

WithCache sets git revisions cacher as well as specifies if client should tries to use cached resolved revision

func WithEventHandlers added in v1.8.8

func WithEventHandlers(handlers EventHandlers) ClientOpts

WithEventHandlers sets the git client event handlers

func WithTagPrefix added in v1.8.8

func WithTagPrefix(prefix string) ClientOpts

WithTagPrefix sets a tag prefix to filter and strip when resolving semver constraints via LsRemote. Only tags with this prefix are considered; the prefix is stripped before comparison and re-added to the result.

type CommitMetadata added in v1.8.8

type CommitMetadata struct {
	// Author is the author of the commit.
	// Comes from the Argocd-reference-commit-author trailer.
	Author mail.Address
	// Date is the date of the commit, formatted as by `git show -s --format=%aI`.
	// May be an empty string if the date is unknown.
	// Comes from the Argocd-reference-commit-date trailer.
	Date string
	// Subject is the commit message subject, i.e. `git show -s --format=%s`.
	// Comes from the Argocd-reference-commit-subject trailer.
	Subject string
	// Body is the commit message body, excluding the subject, i.e. `git show -s --format=%b`.
	// Comes from the Argocd-reference-commit-body trailer.
	Body string
	// SHA is the commit hash.
	// Comes from the Argocd-reference-commit-sha trailer.
	SHA string
	// RepoURL is the URL of the repository where the commit is located.
	// Comes from the Argocd-reference-commit-repourl trailer.
	// This value is not validated beyond confirming that it's a URL, and it should not be used to construct UI links
	// unless it is properly validated and/or sanitized first.
	RepoURL string
}

CommitMetadata contains metadata about a commit that is related in some way to another commit.

type Creds added in v1.1.0

type Creds interface {
	Environ() (io.Closer, []string, error)
	// GetUserInfo gets the username and email address for the credentials, if they're available.
	GetUserInfo(ctx context.Context) (string, string, error)
}

type CredsStore added in v1.8.8

type CredsStore interface {
	Add(username string, password string) string
	Remove(id string)
	// Environ returns the environment variables that should be set to use the credentials for the given credential ID.
	Environ(id string) []string
}

type EventHandlers added in v1.8.8

type EventHandlers struct {
	OnLsRemote func(repo string) func()
	OnFetch    func(repo string) func()
	OnPush     func(repo string) func()
}

type GPGVerificationResult added in v1.8.8

type GPGVerificationResult string
const (
	GPGVerificationResultGood             GPGVerificationResult = "signed"                         // All good
	GPGVerificationResultBad              GPGVerificationResult = "bad signature"                  // Not able to cryptographically verify signature
	GPGVerificationResultUntrusted        GPGVerificationResult = "signed with untrusted key"      // The trust level of the key in the gpg keyring is not sufficient
	GPGVerificationResultExpiredSignature GPGVerificationResult = "expired signature"              // Signature have expired
	GPGVerificationResultExpiredKey       GPGVerificationResult = "signed with expired key"        // Signed with a key expired at the time of the signing
	GPGVerificationResultRevokedKey       GPGVerificationResult = "signed with revoked key"        // Signed with a key that is revoked
	GPGVerificationResultMissingKey       GPGVerificationResult = "signed with key not in keyring" // The key used to sign was not added to the gpg keyring
	GPGVerificationResultUnsigned         GPGVerificationResult = "unsigned"                       // Commit it not signed at all
)

type GenericHTTPSCreds added in v1.8.8

type GenericHTTPSCreds interface {
	HasClientCert() bool
	GetClientCertData() string
	GetClientCertKey() string
	Creds
}

func NewGitHubAppCreds added in v1.8.8

func NewGitHubAppCreds(appID int64, appInstallId int64, privateKey string, baseURL string, clientCertData string, clientCertKey string, insecure bool, proxy string, noProxy string, store CredsStore, repoURL string) GenericHTTPSCreds

NewGitHubAppCreds provide github app credentials repoURL is required for automatic installation ID discovery when appInstallId is 0

func NewHTTPSCreds added in v1.1.0

func NewHTTPSCreds(username string, password string, bearerToken string, clientCertData string, clientCertKey string, insecure bool, store CredsStore, forceBasicAuth bool) GenericHTTPSCreds

type GitHubAppCreds added in v1.8.8

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

GitHubAppCreds to authenticate as GitHub application

func (GitHubAppCreds) Environ added in v1.8.8

func (g GitHubAppCreds) Environ() (io.Closer, []string, error)

func (GitHubAppCreds) GetClientCertData added in v1.8.8

func (g GitHubAppCreds) GetClientCertData() string

func (GitHubAppCreds) GetClientCertKey added in v1.8.8

func (g GitHubAppCreds) GetClientCertKey() string

func (GitHubAppCreds) GetUserInfo added in v1.8.8

func (g GitHubAppCreds) GetUserInfo(ctx context.Context) (string, string, error)

GetUserInfo returns the username and email address for the credentials, if they're available.

func (GitHubAppCreds) HasClientCert added in v1.8.8

func (g GitHubAppCreds) HasClientCert() bool

type GoogleCloudCreds added in v1.8.8

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

GoogleCloudCreds to authenticate to Google Cloud Source repositories

func NewGoogleCloudCreds added in v1.8.8

func NewGoogleCloudCreds(jsonData string, store CredsStore) GoogleCloudCreds

func (GoogleCloudCreds) Environ added in v1.8.8

func (c GoogleCloudCreds) Environ() (io.Closer, []string, error)

func (GoogleCloudCreds) GetUserInfo added in v1.8.8

func (c GoogleCloudCreds) GetUserInfo(_ context.Context) (string, string, error)

GetUserInfo returns the username and email address for the credentials, if they're available. TODO: implement getting email instead of just username.

type HTTPSCreds added in v1.1.0

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

HTTPS creds implementation

func (HTTPSCreds) BasicAuthHeader added in v1.8.8

func (creds HTTPSCreds) BasicAuthHeader() string

func (HTTPSCreds) BearerAuthHeader added in v1.8.8

func (creds HTTPSCreds) BearerAuthHeader() string

func (HTTPSCreds) Environ added in v1.1.0

func (creds HTTPSCreds) Environ() (io.Closer, []string, error)

Get additional required environment variables for executing git client to access specific repository via HTTPS.

func (HTTPSCreds) GetClientCertData added in v1.8.8

func (creds HTTPSCreds) GetClientCertData() string

func (HTTPSCreds) GetClientCertKey added in v1.8.8

func (creds HTTPSCreds) GetClientCertKey() string

func (HTTPSCreds) GetUserInfo added in v1.8.8

func (creds HTTPSCreds) GetUserInfo(_ context.Context) (string, string, error)

GetUserInfo returns the username and email address for the credentials, if they're available.

func (HTTPSCreds) HasClientCert added in v1.8.8

func (creds HTTPSCreds) HasClientCert() bool

type NoopCredsStore added in v1.8.8

type NoopCredsStore struct{}

func (NoopCredsStore) Add added in v1.8.8

func (d NoopCredsStore) Add(_ string, _ string) string

func (NoopCredsStore) Environ added in v1.8.8

func (d NoopCredsStore) Environ(_ string) []string

func (NoopCredsStore) Remove added in v1.8.8

func (d NoopCredsStore) Remove(_ string)

type NopCloser added in v1.1.0

type NopCloser struct{}

nop implementation

func (NopCloser) Close added in v1.1.0

func (c NopCloser) Close() error

type NopCreds added in v1.1.0

type NopCreds struct{}

func (NopCreds) Environ added in v1.1.0

func (c NopCreds) Environ() (io.Closer, []string, error)

func (NopCreds) GetUserInfo added in v1.8.8

func (c NopCreds) GetUserInfo(_ context.Context) (name string, email string, err error)

GetUserInfo returns empty strings for user info

type PublicKeysWithOptions added in v1.8.8

type PublicKeysWithOptions struct {
	KexAlgorithms []string
	// HostKeyAlgorithms restricts the host key algorithms advertised during
	// the SSH handshake to those known for the target host. go-git v5.16+
	// only auto-configures this when the user's AuthMethod does not set a
	// HostKeyCallback; since we always set one, we must populate this
	// ourselves or the handshake can fail with "knownhosts: key mismatch"
	// when the server offers a key of a type that isn't in known_hosts.
	// See go-git/go-git#1551.
	HostKeyAlgorithms []string
	gitssh.PublicKeys
}

PublicKeysWithOptions is an auth method for go-git's SSH client that inherits from PublicKeys, but provides the possibility to override some client options.

func (*PublicKeysWithOptions) ClientConfig added in v1.8.8

func (a *PublicKeysWithOptions) ClientConfig() (*ssh.ClientConfig, error)

ClientConfig returns a custom SSH client configuration

func (*PublicKeysWithOptions) Name added in v1.8.8

func (a *PublicKeysWithOptions) Name() string

Name returns the name of the auth method

func (*PublicKeysWithOptions) String added in v1.8.8

func (a *PublicKeysWithOptions) String() string

String returns the configured user and auth method name as string

type Refs added in v1.8.8

type Refs struct {
	Branches []string
	Tags     []string
}

this should match reposerver/repository/repository.proto/RefsList

type RevisionMetadata added in v1.2.0

type RevisionMetadata struct {
	// Author is the author of the commit. Corresponds to the output of `git log -n 1 --pretty='format:%an <%ae>'`.
	Author string
	// Date is the date of the commit. Corresponds to the output of `git log -n 1 --pretty='format:%ad'`.
	Date time.Time
	Tags []string
	// Message is the commit message.
	Message string
	// References contains metadata about information that is related in some way to this commit. This data comes from
	// git commit trailers starting with "Argocd-reference-". We currently only support a single reference to a commit,
	// but we return an array to allow for future expansion.
	References []RevisionReference
}

type RevisionReference added in v1.8.8

type RevisionReference struct {
	// Commit contains metadata about the commit that is related in some way to another commit.
	Commit *CommitMetadata
}

RevisionReference contains a reference to a some information that is related in some way to another commit. For now, it supports only references to a commit. In the future, it may support other types of references.

func GetReferences added in v1.8.8

func GetReferences(logCtx *log.Entry, commitMessageBody string) ([]RevisionReference, string)

GetReferences extracts related commit metadata from the commit message trailers. If referenced commit metadata is present, we return a slice containing a single metadata object. If no related commit metadata is found, we return a nil slice.

If a trailer fails validation, we log an error and skip that trailer. We truncate the trailer values to 100 characters to avoid excessively long log messages.

We also return the commit message body with all valid Argocd-reference-commit-* trailers removed.

type RevisionSignatureInfo added in v1.8.8

type RevisionSignatureInfo struct {
	Revision           string
	VerificationResult GPGVerificationResult
	SignatureKeyID     string
	Date               string
	AuthorIdentity     string
}

type SSHCreds added in v1.1.0

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

SSH implementation

func NewSSHCreds added in v1.1.0

func NewSSHCreds(sshPrivateKey string, caPath string, insecureIgnoreHostKey bool, proxy string) SSHCreds

func (SSHCreds) Environ added in v1.1.0

func (c SSHCreds) Environ() (io.Closer, []string, error)

func (SSHCreds) GetUserInfo added in v1.8.8

func (c SSHCreds) GetUserInfo(_ context.Context) (string, string, error)

GetUserInfo returns empty strings for user info. TODO: Implement this method to return the username and email address for the credentials, if they're available.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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