infrastructure

package
v4.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 33 Imported by: 3 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	DefaultGitTag               = "0.1.0"
	MaxAcceptableInitialCommits = 5
)

Variables

View Source
var (
	ErrNoAuthMethodFound  = errors.New("no authentication method found")
	ErrAuthNotImplemented = errors.New("authentication method not implemented")
	ErrNoRemoteURL        = errors.New("no remote URL found for repository")
	ErrNoTagsFound        = errors.New("no tags found in Git history")
)

Functions

func CheckBranchExists

func CheckBranchExists(repo *git.Repository, branchName string) (bool, error)

CheckBranchExists checks if a given Git branch exists (local or remote). Exported for use by autobump (github.com/rios0rios0/autobump).

func CheckoutBranch

func CheckoutBranch(w *git.Worktree, branchName string) error

CheckoutBranch switches to the given branch. It never forces the checkout: a forced go-git checkout resets the working tree hard, deleting untracked and ignored files. Exported for use by autobump (github.com/rios0rios0/autobump).

func CommitChanges

func CommitChanges(
	repo *git.Repository,
	workTree *git.Worktree,
	commitMessage string,
	signer globalEntities.CommitSigner,
	name string,
	email string,
) (plumbing.Hash, error)

CommitChanges commits the changes in the given worktree with optional signing. The repo parameter is required when using a CommitSigner that produces post-commit signatures (e.g. SSH). Exported for use by autobump (github.com/rios0rios0/autobump).

func CreateAndSwitchBranch

func CreateAndSwitchBranch(
	repo *git.Repository,
	workTree *git.Worktree,
	branchName string,
	hash plumbing.Hash,
) error

CreateAndSwitchBranch creates a new branch at hash and makes it the current branch. Exported for use by autobump (github.com/rios0rios0/autobump).

When hash is the commit HEAD already points to -- what every caller passes -- the switch needs nothing but HEAD itself: the branch is created and HEAD is pointed at it, leaving the index and the working tree exactly as they are, as `git switch -c` does. A go-git checkout is not used for that, in either of its forms. The plain one rejects the switch when the index differs from the working tree for reasons that would not stop git, such as line-ending normalisation after a native clone; and the forced one resets the working tree hard, which discards local changes and deletes every untracked and ignored file -- in an operator's own checkout, their `.env`, build output and editor settings -- even though no file needs to change.

A hash HEAD does not point to needs the working tree to change, so it gets a regular checkout, which refuses when local changes are in the way instead of discarding them. HEAD is compared before the branch is written: when branchName is the current branch, writing it first makes HEAD resolve to hash, which passes a move to another commit off as a switch with no file to change.

func DeleteLocalBranch

func DeleteLocalBranch(repo *git.Repository, branchName string) error

DeleteLocalBranch removes the local refs/heads/<branchName> reference when it exists.

This is the necessary companion to DeleteRemoteBranch: deleting a branch on the remote leaves the local branch untouched, and CheckBranchExists reports a branch as existing when it finds either one. A caller that deletes a branch remotely and then asks whether it exists would still be told "yes", and so would never recreate it.

A branch that is absent is not an error. The currently checked-out branch is never removed, because dropping HEAD's reference leaves the repository unusable.

Exported for use by autobump (github.com/rios0rios0/autobump) and autoupdate (github.com/rios0rios0/autoupdate).

func DeleteRemoteBranch

func DeleteRemoteBranch(
	repo *git.Repository,
	branchName string,
	authMethods []transport.AuthMethod,
) error

DeleteRemoteBranch deletes the given branch on the origin remote by pushing an empty source to its ref. go-git drops the matching remote-tracking reference as part of that push, so only the remote side is handled here; a local branch of the same name survives and must be removed with DeleteLocalBranch.

Exported for use by autobump (github.com/rios0rios0/autobump) and autoupdate (github.com/rios0rios0/autoupdate).

func DetectSSHAgentSockets added in v4.5.0

func DetectSSHAgentSockets() []string

DetectSSHAgentSockets returns the SSH agent sockets that exist on this host, in the order they are worth trying: SSH_AUTH_SOCK, then 1Password's ~/.1password/agent.sock. A socket that exists may still have nothing listening on it -- a relay that exited leaves its socket behind -- which NewSSHAgentAuthFromSocket finds out by dialing it.

func GetAmountCommits

func GetAmountCommits(repo *git.Repository) (int, error)

GetAmountCommits returns the number of commits in the repository.

func GetLatestTag

func GetLatestTag(repo *git.Repository) (*globalEntities.LatestTag, error)

GetLatestTag finds the latest release tag in the Git history: the highest tag that reads as a semantic version, together with the date of the commit it points to. Exported for use by autobump (github.com/rios0rios0/autobump).

The highest version, not the tag the repository lists last. Tags are listed in no particular version order -- `1.10.0` sorts before `1.9.0` as text -- and a tag that is not a version, such as the four-part tags a fork carries from its upstream, used to come back with a nil version that callers printed as `<nil>`. Tags that are not versions are ignored, so a repository holding nothing else is treated like one without tags.

func GetRemoteRepoURL

func GetRemoteRepoURL(repo *git.Repository) (string, error)

GetRemoteRepoURL returns the URL of the remote repository. Exported for use by autobump (github.com/rios0rios0/autobump).

func InstallSSHTransport added in v4.5.0

func InstallSSHTransport()

InstallSSHTransport makes every SSH connection go-git opens in this process honour the operator's SSH client configuration, the way the ssh binary does for git: a consumer calls it once, at startup, before any push, clone or listing. It

  • installs NewSSHTransport(gitssh.DefaultClient) for the "ssh" scheme;
  • switches off go-git's own ssh_config reader (gitssh.DefaultSSHConfig), which applies only HostName and Port, since the transport has already replaced an alias with the HostName it names, which must not be resolved a second time;
  • hands SSHHostKeyCallback to SetDefaultSSHHostKeyCallback, so the default SSH agent fallback verifies hosts against the same known_hosts discovery.

The transport asks the server only for the host key types known_hosts records, and reads them from the files KnownHostsCallback verifies against: an auth method a consumer builds should carry KnownHostsCallback, as a callback verifying against other files may be asked for a key type it does not hold.

A consumer with SSHTransportOptions of its own calls InstallSSHTransportWith instead.

func InstallSSHTransportWith added in v4.6.0

func InstallSSHTransportWith(options SSHTransportOptions)

InstallSSHTransportWith does what InstallSSHTransport does, but installs the transport with the options a consumer adds to it (see SSHTransportOptions). With the zero value it is InstallSSHTransport.

func KnownHostsCallback added in v4.5.0

func KnownHostsCallback() ssh.HostKeyCallback

KnownHostsCallback returns an ssh.HostKeyCallback that validates against every known_hosts file this host offers (see discoverKnownHostsFiles), or nil when there is none, letting go-git fall back to its own default host key verification. A consumer gives it to the SSH auth methods it builds, so the host key types the SSH transport negotiates are always ones the callback can verify.

func ListRemoteBranches

func ListRemoteBranches(repo *git.Repository, authMethods []transport.AuthMethod) ([]string, error)

ListRemoteBranches returns the short names of every branch present on the origin remote. It queries the remote directly rather than reading remote-tracking references, so the result reflects the current server state even when the local clone is stale.

Exported for use by autobump (github.com/rios0rios0/autobump) and autoupdate (github.com/rios0rios0/autoupdate).

func NewSSHAgentAuthFromSocket added in v4.5.0

func NewSSHAgentAuthFromSocket(socketPath string) transport.AuthMethod

NewSSHAgentAuthFromSocket returns an SSH agent auth method for the agent listening on a Unix socket, or nil when nothing answers there. The method verifies host keys with KnownHostsCallback, so the SSH transport can negotiate the host key types it can verify.

Every use dials the socket afresh -- one connection to list the keys, then one per signature (see sshAgentSigner) -- so no connection outlives the call that needed it. go-git's own NewSSHAgentAuth reads only SSH_AUTH_SOCK; this one takes any socket, which lets a consumer offer an agent its operator configured, or one DetectSSHAgentSockets found.

func NewSSHTransport added in v4.5.0

func NewSSHTransport(next transport.Transport) transport.Transport

NewSSHTransport wraps go-git's SSH transport (gitssh.DefaultClient) so every connection it opens honours the operator's ssh_config and known_hosts; InstallSSHTransport installs the result for the "ssh" scheme, and InstallSSHTransportWith the same transport with a consumer's SSHTransportOptions. The files are discovered on the first connection, not here, so a run that never touches SSH neither pays for the discovery nor sees its warnings.

func OpenRepo

func OpenRepo(projectPath string) (*git.Repository, error)

OpenRepo opens a git repository at the given path. Exported for use by autobump (github.com/rios0rios0/autobump).

func PushChangesSSH

func PushChangesSSH(repo *git.Repository, refSpec config.RefSpec, authMethods []transport.AuthMethod) error

PushChangesSSH pushes the changes to the remote repository over SSH. If authMethods is non-empty, each method is tried in order until one succeeds. If all explicit methods fail or authMethods is empty, it falls back to go-git's default SSH agent behaviour (SSH_AUTH_SOCK), carrying the host key callback installed via SetDefaultSSHHostKeyCallback so the fallback verifies hosts against the consumer's own known_hosts discovery rather than go-git's.

When both an explicit method and the fallback fail, the returned error names the explicit failure too: the fallback's own error (often "unable to find any valid known_hosts file", or an agent that answered nothing) otherwise masks the credential problem the operator actually has to fix.

func PushWithTransportDetection

func PushWithTransportDetection(
	repo *git.Repository,
	refSpec config.RefSpec,
	authMethods []transport.AuthMethod,
) error

PushWithTransportDetection pushes the given refSpec to the origin remote, auto-detecting the transport (SSH or HTTPS) from the remote URL.

For SSH remotes (git@ or ssh://), authMethods are tried in order; if all fail or none are provided, it falls back to go-git's default SSH agent.

For HTTPS/HTTP remotes, authMethods are tried in order until one succeeds. An empty authMethods slice returns an error for HTTPS remotes.

Exported for use by autobump (github.com/rios0rios0/autobump) and autoupdate (github.com/rios0rios0/autoupdate).

func RunningUnderWSL added in v4.5.0

func RunningUnderWSL() bool

RunningUnderWSL reports whether the current kernel is a WSL one. The environment variables WSL sets are checked first because they cost nothing; the kernel release is the fallback for a shell that did not inherit them.

func SSHConfigSearchDescription added in v4.5.0

func SSHConfigSearchDescription() string

SSHConfigSearchDescription names the ssh_config files the SSH transport reads on this host, for a consumer's error message that has to send the operator to one of them -- an SSH host that does not resolve is usually an alias defined in a file the transport does not read.

func SSHHostKeyCallback added in v4.5.0

func SSHHostKeyCallback() ssh.HostKeyCallback

SSHHostKeyCallback returns a host key callback for the default SSH agent fallback — the push and remote listing PushChangesSSH and ListRemoteBranches perform with no explicit auth method — which InstallSSHTransport installs with SetDefaultSSHHostKeyCallback. Without a callback that fallback verifies hosts through go-git's own lookup, which knows nothing about the Windows-side files discovered here and fails when ~/.ssh/known_hosts is absent.

The returned callback resolves discovery lazily, on the first host key check, so a run that never touches SSH neither pays for the discovery nor emits its warnings. knownHostsDB memoizes, so repeated checks are cheap. When no known_hosts file exists at all it fails the check with a clear message rather than silently accepting any host key.

func SetDefaultSSHHostKeyCallback added in v4.3.0

func SetDefaultSSHHostKeyCallback(callback ssh.HostKeyCallback)

SetDefaultSSHHostKeyCallback installs the host key callback used by the default SSH agent fallback in PushChangesSSH and remote reference listing.

Without it the fallback pushes with a nil auth method, and go-git then builds its own host key verification from SSH_KNOWN_HOSTS or ~/.ssh/known_hosts alone. On a host that keeps its known_hosts somewhere else — a WSL machine whose file belongs to the Windows profile is the common case — every fallback fails with "unable to find any valid known_hosts file" even though the consumer already discovered the file and verified against it for the explicit auth methods. A consumer that does its own discovery hands the resulting callback here so the fallback verifies hosts against the same data.

Passing nil restores go-git's own default behaviour.

func StageAll

func StageAll(workTree *git.Worktree) error

StageAll adds all changes in the working tree to the index, equivalent to `git add -A`. It stages new, modified, and deleted files. Exported for use by autoupdate (github.com/rios0rios0/autoupdate).

func WorktreeIsClean

func WorktreeIsClean(workTree *git.Worktree) (bool, error)

WorktreeIsClean returns true when the working tree has no uncommitted changes (staged or unstaged). This is the go-git equivalent of `git status --porcelain` returning empty output. Exported for use by autoupdate (github.com/rios0rios0/autoupdate).

Types

type GitOperations

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

GitOperations encapsulates git operations with an adapter finder for service type resolution.

func NewGitOperations

func NewGitOperations(finder gitEntities.AdapterFinder) *GitOperations

NewGitOperations creates a new GitOperations with the given adapter finder.

func (*GitOperations) CloneRepo

func (o *GitOperations) CloneRepo(
	url, dir string,
	authMethods []transport.AuthMethod,
) (*git.Repository, error)

CloneRepo clones a remote repository into the given directory. It prepares the clone URL via the adapter finder (if one matches the URL) and tries each provided authentication method until one succeeds.

func (*GitOperations) GetAuthMethods

func (o *GitOperations) GetAuthMethods(
	service globalEntities.ServiceType,
	username string,
) ([]transport.AuthMethod, error)

GetAuthMethods returns the authentication methods for the given service type. It delegates to the appropriate adapter based on the service type. Exported for use by autobump (github.com/rios0rios0/autobump).

func (*GitOperations) GetRemoteServiceType

func (o *GitOperations) GetRemoteServiceType(repo *git.Repository) (globalEntities.ServiceType, error)

GetRemoteServiceType returns the type of the remote service (e.g. GitHub, GitLab). Exported for use by autobump (github.com/rios0rios0/autobump).

func (*GitOperations) GetServiceTypeByURL

func (o *GitOperations) GetServiceTypeByURL(remoteURL string) globalEntities.ServiceType

GetServiceTypeByURL returns the type of the remote service by URL. Exported for use by autobump (github.com/rios0rios0/autobump).

func (*GitOperations) PushChangesHTTPS

func (o *GitOperations) PushChangesHTTPS(
	repo *git.Repository,
	username string,
	refSpec config.RefSpec,
) error

PushChangesHTTPS pushes the changes to the remote repository over HTTPS. It tries each authentication method returned by the adapter until one succeeds.

type PullRequestURLInfo

type PullRequestURLInfo struct {
	ServiceType  globalEntities.ServiceType
	Organization string
	Project      string // Azure DevOps only; empty for GitHub/GitLab
	RepoName     string
	PRID         int
}

PullRequestURLInfo holds the parsed components of a pull request URL.

func ParsePullRequestURL

func ParsePullRequestURL(rawURL string) (*PullRequestURLInfo, error)

ParsePullRequestURL extracts provider, organization, project, repository, and PR ID from a PR URL. Supported formats:

type RemoteURLInfo

type RemoteURLInfo struct {
	ServiceType  globalEntities.ServiceType
	Organization string
	Project      string // Azure DevOps only; empty for GitHub/GitLab
	RepoName     string
}

RemoteURLInfo holds the parsed components of a Git remote URL.

func ParseRemoteURL

func ParseRemoteURL(rawURL string) (*RemoteURLInfo, error)

ParseRemoteURL extracts provider, organization, project, and repository name from a Git remote URL. Supported formats:

type SSHTransportOptions added in v4.6.0

type SSHTransportOptions struct {
	// MissingKeyRemedy is a way the consumer itself offers to provide a key, such as a
	// setting that names a key file. When IdentitiesOnly leaves a host alias no key to
	// offer, the transport warns once for that alias, and the warning ends "add that key to
	// the SSH agent". A non-empty MissingKeyRemedy is appended to it after ", or ", so it
	// should be an instruction about that key: "configure it as ssh_key_path", for example.
	// Empty leaves the warning as it is.
	MissingKeyRemedy string
}

SSHTransportOptions is what a consumer adds to the SSH transport InstallSSHTransportWith installs: what only the consumer knows, such as settings of its own. The zero value adds nothing, and is what InstallSSHTransport installs the transport with.

type UserConfig

type UserConfig struct {
	Name          string
	Email         string
	SigningKey    string
	SigningFormat string
	SSHProgram    string // gpg.ssh.program — custom signing binary (e.g. op-ssh-sign-wsl)
}

UserConfig holds user-specific git configuration values read from local and global git config. Exported for use by autobump (github.com/rios0rios0/autobump) and autoupdate (github.com/rios0rios0/autoupdate) as the canonical way to read user identity and signing settings before committing.

func ReadUserConfig

func ReadUserConfig(repo *git.Repository) (*UserConfig, error)

ReadUserConfig reads user name, email, signing key, and signing format from the repository's local config, falling back to the global ~/.gitconfig. Exported for use by autobump (github.com/rios0rios0/autobump) and autoupdate (github.com/rios0rios0/autoupdate).

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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