git

package
v1.0.6 Latest Latest
Warning

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

Go to latest
Published: May 22, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Overview

Package git provides support for Git operations needed throughout the Terragrunt codebase.

The package primarily uses the `git` binary installed on the host system, but experimentally supports the `go-git` library for some operations. As of yet, the performance of the `go-git` library is not as good as the `git` binary, so we don't use it by default. If we can optimize usage of the `go-git` library so that the performance difference is negligible, we can choose to use it instead of the `git` binary for certain operations.

Even assuming the performance differences are negligible, we'll still prefer to use the `git` binary for certain operations. For example, operations related to remotes are likely easier to support with the `git` binary, as users might have git configurations for authentication that would be inconvenient to port over to configuration of the `go-git` library. This might change in the future.

We'll prefix usage of the `go-git` library with "Go" to make it clear when we're using it.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrCommandSpawn        = errors.New("failed to spawn git command")
	ErrNoMatchingReference = errors.New("no matching reference")
	ErrReadTree            = errors.New("failed to read tree")
	ErrNoWorkDir           = errors.New("working directory not set")
	ErrNoGoRepo            = errors.New("go repository not set")
	ErrUnknownRevision     = errors.New("unknown revision")
)

Git operation errors

Functions

func ExtractRepoName

func ExtractRepoName(repo string) string

ExtractRepoName extracts the repository name from a git URL

Types

type Diffs

type Diffs struct {
	Added   []string
	Removed []string
	Changed []string
}

Diffs represents the diffs between two Git references.

func ParseDiff

func ParseDiff(output []byte) (*Diffs, error)

ParseDiff parses the stdout of a `git diff --name-status --no-renames` into a Diffs object.

type Error

type Error string

Error types that can be returned by the cas package

const (
	// ErrParseTree is returned when failing to parse git tree output
	ErrParseTree Error = "failed to parse git tree output"
	// ErrParseDiff is returned when failing to parse git diff output
	ErrParseDiff Error = "failed to parse git diff output"
	// ErrGitClone is returned when the git clone operation fails
	ErrGitClone Error = "failed to complete git clone"
	// ErrGitInitBare is returned when initializing a bare repository fails
	ErrGitInitBare Error = "failed to initialize bare git repository"
	// ErrGitFetch is returned when a git fetch operation fails
	ErrGitFetch Error = "failed to complete git fetch"
	// ErrCreateTempDir is returned when failing to create a temporary directory
	ErrCreateTempDir Error = "failed to create temporary directory"
	// ErrCleanupTempDir is returned when failing to clean up a temporary directory
	ErrCleanupTempDir Error = "failed to clean up temporary directory"
)

func (Error) Error

func (e Error) Error() string

type GitRunner

type GitRunner struct {
	GitPath string
	WorkDir string
	// contains filtered or unexported fields
}

GitRunner handles git command execution

func NewGitRunner

func NewGitRunner(e vexec.Exec) (*GitRunner, error)

NewGitRunner creates a new GitRunner instance. The provided vexec.Exec is used to resolve the `git` binary on PATH.

func (*GitRunner) CatFile

func (g *GitRunner) CatFile(ctx context.Context, hash string, out io.Writer) error

CatFile writes the contents of a git object to a given writer.

func (*GitRunner) Clone

func (g *GitRunner) Clone(ctx context.Context, repo string, bare bool, depth int, branch string) error

Clone performs a git clone operation

func (*GitRunner) Config added in v0.95.1

func (g *GitRunner) Config(ctx context.Context, name string) (string, error)

Config gets the configuration of the Git repository

func (*GitRunner) CreateDetachedWorktree

func (g *GitRunner) CreateDetachedWorktree(ctx context.Context, dir, ref string) error

CreateDetachedWorktree creates a new detached worktree for a given reference as a given directory

func (*GitRunner) CreateTempDir

func (g *GitRunner) CreateTempDir() (string, func() error, error)

CreateTempDir creates a new temporary directory for git operations

func (*GitRunner) Diff

func (g *GitRunner) Diff(ctx context.Context, fromRef, toRef string) (*Diffs, error)

Diff determines the diff between two Git references.

func (*GitRunner) Fetch added in v1.0.5

func (g *GitRunner) Fetch(ctx context.Context, repo, ref string, depth int) error

Fetch runs `git fetch` for a single ref against the given remote URL. A positive depth adds --depth and --no-tags. A zero or negative depth fetches full history.

func (*GitRunner) GetCurrentBranch added in v0.96.1

func (g *GitRunner) GetCurrentBranch(ctx context.Context) string

GetCurrentBranch returns the current branch name, or empty string on error.

func (*GitRunner) GetDefaultBranch added in v0.96.1

func (g *GitRunner) GetDefaultBranch(ctx context.Context, l log.Logger) string

GetDefaultBranch implements the hybrid approach to detect the default branch: 1. Tries to determine the default branch of the remote repository using the fast local method first 2. Falls back to the network method if the local method fails 3. Attempts to update local cache for future use Returns the branch name (e.g., "main") or an error if both methods fail.

func (*GitRunner) GetDefaultBranchLocal added in v0.96.1

func (g *GitRunner) GetDefaultBranchLocal(ctx context.Context) (string, error)

GetDefaultBranchLocal attempts to get the default branch using the local cached remote HEAD. Returns the branch name (e.g., "main") if successful, or an error if the local ref is not set. This is fast and works offline, but requires that `git remote set-head origin --auto` has been run.

func (*GitRunner) GetDefaultBranchRemote added in v0.96.1

func (g *GitRunner) GetDefaultBranchRemote(ctx context.Context) (string, error)

GetDefaultBranchRemote queries the remote repository to determine the default branch. This is the most accurate method but requires network access. Returns the branch name (e.g., "main") if successful.

func (*GitRunner) GetHeadCommit added in v0.96.1

func (g *GitRunner) GetHeadCommit(ctx context.Context) string

GetHeadCommit returns the current HEAD commit hash, or empty string on error.

func (*GitRunner) GetRemoteURL added in v0.96.1

func (g *GitRunner) GetRemoteURL(ctx context.Context) string

GetRemoteURL returns the origin remote URL, or empty string on error.

func (*GitRunner) GetRepoRoot

func (g *GitRunner) GetRepoRoot(ctx context.Context) (string, error)

GetRepoRoot returns the root directory of the git repository. The successful result is memoized per-runner so subsequent calls skip the `git rev-parse` fork; failures are not cached so callers can retry. WithWorkDir clears the memo so a derived runner resolves its own root.

func (*GitRunner) GoAdd

func (g *GitRunner) GoAdd(paths ...string) error

GoAdd adds a file to the Git repository.

func (*GitRunner) GoCheckout added in v0.95.1

func (g *GitRunner) GoCheckout(opts *git.CheckoutOptions) error

GoCheckout checks out a branch in the Git repository.

func (*GitRunner) GoCloseStorage

func (g *GitRunner) GoCloseStorage() error

GoCloseStorage closes the storage for a Git repository.

func (*GitRunner) GoCommit

func (g *GitRunner) GoCommit(message string, opts *git.CommitOptions) error

GoCommit commits changes to the Git repository.

func (*GitRunner) GoLsTreeRecursive

func (g *GitRunner) GoLsTreeRecursive(ref string) ([]TreeEntry, error)

GoLsTreeRecursive uses the `go-git` library to recursively list the contents of a git tree.

In testing, this is significantly slower than LsTreeRecursive, so we don't use it right now. We'll keep it here and benchmark it again later if we can optimize it.

func (*GitRunner) GoOpenGitDir

func (g *GitRunner) GoOpenGitDir() error

GoOpenGitDir opens a Git repository using the `go-git` library, but chroots to the `.git` directory if present.

Use this for operations that don't need access to the rest of the repository for read-only access, etc.

Opening a Git repository leaves the storage open, so it's the responsibility of the caller to close the storage with `GoCloseStorage` when it is no longer needed.

func (*GitRunner) GoOpenRepo

func (g *GitRunner) GoOpenRepo() error

GoOpenRepo opens a Git repository using the `go-git` library.

func (*GitRunner) GoOpenRepoCommitObject

func (g *GitRunner) GoOpenRepoCommitObject(hash plumbing.Hash) (*object.Commit, error)

GoOpenRepoCommitObject gets a commit object from the Git repository.

func (*GitRunner) GoOpenRepoHead

func (g *GitRunner) GoOpenRepoHead() (*plumbing.Reference, error)

GoOpenRepoHead gets the head of the Git repository.

func (*GitRunner) GoStatus

func (g *GitRunner) GoStatus() (git.Status, error)

GoStatus gets the status of the Git repository.

func (*GitRunner) HasObject added in v1.0.5

func (g *GitRunner) HasObject(ctx context.Context, hash string) (bool, error)

HasObject reports whether the given object exists in the configured working-directory repository. Exit code 1 from `git cat-file -e` means the object is absent. Other non-zero exits (e.g. 128 for a corrupted repo or unreadable .git) are returned as errors so callers do not loop into a refetch against a broken store.

func (*GitRunner) HasUncommittedChanges added in v0.95.1

func (g *GitRunner) HasUncommittedChanges(ctx context.Context) bool

HasUncommittedChanges checks if there are uncommitted changes in the working directory. Returns true if there are uncommitted changes, false otherwise (including if git command fails or not in a git repo).

func (*GitRunner) Init

func (g *GitRunner) Init(ctx context.Context) error

Init initializes a Git repository

func (*GitRunner) InitBare added in v1.0.5

func (g *GitRunner) InitBare(ctx context.Context) error

InitBare runs `git init --bare` in the configured working directory. `git init --bare` is itself idempotent (it reinitializes an existing bare repo as a no-op), so callers may invoke this freely.

func (*GitRunner) LatestReleaseTag added in v1.0.2

func (g *GitRunner) LatestReleaseTag(ctx context.Context, remote string) (string, error)

LatestReleaseTag returns the highest semver release tag from the given remote. It uses `git ls-remote --tags` against the named remote (e.g. "origin") and returns the tag with the greatest semantic version, or "" if none exist.

func (*GitRunner) LsRemote

func (g *GitRunner) LsRemote(ctx context.Context, repo, ref string) ([]LsRemoteResult, error)

LsRemote runs git ls-remote for a specific reference. If ref is empty, we check HEAD instead.

func (*GitRunner) LsTreeRecursive

func (g *GitRunner) LsTreeRecursive(ctx context.Context, ref string) (*Tree, error)

LsTreeRecursive runs git ls-tree -r and returns all blobs recursively This eliminates the need for multiple separate ls-tree calls on subtrees

func (*GitRunner) ObjectFormat added in v1.0.3

func (g *GitRunner) ObjectFormat(ctx context.Context) (string, error)

ObjectFormat returns the object format (hash algorithm) used by the repository in the working directory. Returns "sha1" or "sha256". Requires a working directory with a git repository (bare or non-bare).

func (*GitRunner) RemoveWorktree

func (g *GitRunner) RemoveWorktree(ctx context.Context, path string) error

RemoveWorktree removes a Git worktree for a given path

func (*GitRunner) RequiresGoRepo

func (g *GitRunner) RequiresGoRepo() error

RequiresGoRepo returns an error if no go repository is set

func (*GitRunner) RequiresWorkDir

func (g *GitRunner) RequiresWorkDir() error

RequiresWorkDir returns an error if no working directory is set

func (*GitRunner) RevParseCommit added in v1.0.5

func (g *GitRunner) RevParseCommit(ctx context.Context, ref string) (string, error)

RevParseCommit resolves ref to its canonical commit hash in the configured working-directory repository. ref may be a full SHA (SHA-1 or SHA-256) or an abbreviated SHA that disambiguates inside the repo. The `^{commit}` peeling suffix is what enforces that the object actually exists locally and is a commit; plain rev-parse (even with --verify) only checks revision syntax and would let a caller treat an empty bare repo as already containing the commit. A non-zero exit returns ErrUnknownRevision so callers can branch on the typed error without parsing stderr.

func (*GitRunner) SetRemoteHeadAuto added in v0.96.1

func (g *GitRunner) SetRemoteHeadAuto(ctx context.Context) error

SetRemoteHeadAuto runs `git remote set-head origin --auto` to update the local cached remote HEAD. This makes future calls to GetDefaultBranchLocal faster.

func (*GitRunner) WithWorkDir

func (g *GitRunner) WithWorkDir(workDir string) *GitRunner

WithWorkDir returns a new GitRunner with the specified working directory

type LsRemoteResult

type LsRemoteResult struct {
	Hash string
	Ref  string
}

LsRemoteResult represents the output of git ls-remote

type Server added in v1.0.2

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

Server is a pure-Go HTTP Git server backed by in-memory storage. It is intended for use in tests.

func NewServer added in v1.0.2

func NewServer() (*Server, error)

NewServer creates a Server with an empty in-memory repository.

func (*Server) Branch added in v1.0.5

func (s *Server) Branch(name string) error

Branch creates a branch at the current HEAD with the given name.

func (*Server) Close added in v1.0.2

func (s *Server) Close() error

Close shuts down the server.

func (*Server) CommitFile added in v1.0.2

func (s *Server) CommitFile(path string, data []byte, msg string) error

CommitFile is a convenience that writes a single file to the worktree and commits it. It returns the commit hash.

func (s *Server) CommitSymlink(link, target, msg string) error

CommitSymlink creates a symlink in the worktree pointing at target and commits it. The recorded tree entry is mode 120000 (git's symlink type), matching the on-disk representation produced by `git add` on a symlink.

func (*Server) Head added in v1.0.5

func (s *Server) Head() (string, error)

Head returns the canonical hash of the current HEAD commit. Useful in tests that need to capture a non-tip commit hash before adding further commits.

func (*Server) Repo added in v1.0.2

func (s *Server) Repo() *gogit.Repository

Repo returns the underlying go-git repository so callers can create commits, branches, etc. before starting the server.

func (*Server) SetBranch added in v1.0.5

func (s *Server) SetBranch(name, hash string) error

SetBranch points the named branch at the given commit hash, creating it if missing. Tests use this to rewind a branch past a tagged commit so the commit is reachable only via the tag.

func (*Server) Start added in v1.0.2

func (s *Server) Start(ctx context.Context) (string, error)

Start begins serving Git HTTP on a random local port. Returns the base URL (e.g. "http://127.0.0.1:12345").

func (*Server) Tag added in v1.0.5

func (s *Server) Tag(name string) error

Tag creates an annotated tag at the current HEAD with the given name.

type Tree

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

Tree represents a git tree object with its entries

func ParseTree

func ParseTree(output []byte, path string) (*Tree, error)

ParseTree parses the stdout of git ls-tree [-r] into a Tree object.

func (*Tree) Data

func (t *Tree) Data() []byte

Data returns the tree data

func (*Tree) Entries

func (t *Tree) Entries() []TreeEntry

Entries returns the tree entries

func (*Tree) Path

func (t *Tree) Path() string

Path returns the tree path

func (*Tree) Write

func (t *Tree) Write(w io.Writer) error

Write writes a tree to a given writer

type TreeEntry

type TreeEntry struct {
	Mode string
	Type string
	Hash string
	Path string
}

TreeEntry represents a single entry in a git tree

func ParseTreeEntry

func ParseTreeEntry(line string) (TreeEntry, error)

ParseTreeEntry parses a single line from git ls-tree output

type WrappedError

type WrappedError struct {
	Op      string // Operation that failed
	Path    string // File path if applicable
	Err     error  // Original error
	Context string // Additional context
}

WrappedError provides additional context for errors

func (*WrappedError) Error

func (e *WrappedError) Error() string

func (*WrappedError) Unwrap

func (e *WrappedError) Unwrap() error

Jump to

Keyboard shortcuts

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