git

package
v0.99.0 Latest Latest
Warning

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

Go to latest
Published: Jan 26, 2026 License: MIT Imports: 21 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")
)

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 (
	// ErrTempDir is returned when failing to create or close a temporary directory
	ErrTempDir Error = "failed to create or manage temporary directory"
	// ErrCreateDir is returned when failing to create a directory
	ErrCreateDir Error = "failed to create directory"
	// ErrReadFile is returned when failing to read a file
	ErrReadFile Error = "failed to read file"
	// 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"
	// 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() (*GitRunner, error)

NewGitRunner creates a new GitRunner instance

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

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