git

package
v1.10.2 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CmdMergeBase = "merge-base"
	CmdDiff      = "diff"
	CmdLog       = "log"
)
View Source
const DefaultRemote = "origin"

DefaultRemote is the conventional name for the primary upstream remote.

Variables

View Source
var ComputePatchIDs = func(ctx context.Context, diff string) (map[string]bool, error) {
	if diff == "" {
		return map[string]bool{}, nil
	}
	cmd := exec.CommandContext(ctx, "git", "patch-id", "--stable")
	cmd.Env = stableGitEnv(os.Environ())
	cmd.Stdin = strings.NewReader(diff)
	var stderr bytes.Buffer
	cmd.Stderr = &stderr
	out, err := cmd.Output()
	if err != nil {
		if msg := strings.TrimSpace(stderr.String()); msg != "" {
			return nil, fmt.Errorf("git patch-id --stable: %s: %w", msg, err)
		}
		return nil, fmt.Errorf("git patch-id --stable: %w", err)
	}

	ids := make(map[string]bool)
	for line := range strings.SplitSeq(string(out), "\n") {
		line = strings.TrimSpace(line)
		if line == "" {
			continue
		}
		pid, _, _ := strings.Cut(line, " ")
		if pid != "" {
			ids[pid] = true
		}
	}
	return ids, nil
}

ComputePatchIDs pipes diff into git patch-id --stable and returns the set of patch-id hex strings. Exposed as a variable so tests can stub it without a real git subprocess. Not safe for concurrent modification.

Functions

func AbortRebase added in v1.1.0

func AbortRebase(r Runner, dir string) error

AbortRebase runs `git rebase --abort` inside the given directory. Intentionally non-cancellable: rebase recovery must succeed even after Ctrl-C.

func AddRemote added in v1.9.0

func AddRemote(ctx context.Context, r Runner, name, url string) error

AddRemote adds a new remote with the given name and URL.

func AddWorktree

func AddWorktree(ctx context.Context, r Runner, path, branch, source string) error

AddWorktree creates a new worktree at the given path with a new branch from source.

func AddWorktreeFromBranch added in v1.5.0

func AddWorktreeFromBranch(ctx context.Context, r Runner, path, branch string) error

AddWorktreeFromBranch creates a worktree from an existing branch (no -b flag).

func AheadBehind

func AheadBehind(ctx context.Context, r Runner, dir string) (ahead, behind int, _ error)

AheadBehind returns the ahead/behind counts of the current branch vs its upstream. Returns (0, 0, nil) if there's no upstream configured. Returns ctx.Err() on context cancellation so callers can distinguish a timed-out query from a branch with no upstream.

func BranchExists

func BranchExists(ctx context.Context, r Runner, branch string) bool

BranchExists checks whether a local branch exists.

func Checkout added in v1.9.2

func Checkout(ctx context.Context, r Runner, dir, branch string) error

Checkout switches the working tree in dir to the given branch.

func CommitCountSince added in v1.9.0

func CommitCountSince(ctx context.Context, r Runner, branch string, since time.Duration) (int, error)

CommitCountSince counts commits on branch within the last `since` duration, via `git rev-list --count --since=<unix-ts>`.

git's --since stops at the first commit older than the cutoff, so an older ancestor hides anything beyond it. That matches what we want here: recent activity on the tip, not total commits in history.

func CommonDir added in v1.10.0

func CommonDir(ctx context.Context, r Runner) (string, error)

CommonDir returns the absolute path to the git common directory, shared by the main worktree and every linked worktree. Exported for callers (e.g. `rimba doctor`) that need to locate <commonDir>/worktrees/*/index.lock.

func CurrentBranch added in v1.9.2

func CurrentBranch(ctx context.Context, r Runner, dir string) (string, error)

CurrentBranch returns the short branch name checked out in the given directory. Returns an error with a hint if HEAD is detached.

func DefaultBranch

func DefaultBranch(ctx context.Context, r Runner) (string, error)

DefaultBranch detects the default branch (main or master).

func DeleteBranch

func DeleteBranch(ctx context.Context, r Runner, branch string, force bool) error

DeleteBranch deletes a local branch (-D if force). Already-gone branches are idempotent — checked after a failed delete to avoid a TOCTOU race.

func DeleteRemoteBranch added in v1.9.4

func DeleteRemoteBranch(ctx context.Context, r Runner, remote, branch string) error

DeleteRemoteBranch deletes a branch on the given remote. An already-gone remote ref is treated as success (idempotent).

func DiffNameOnly added in v1.4.0

func DiffNameOnly(ctx context.Context, r Runner, base, branch string) ([]string, error)

DiffNameOnly returns files changed between base and branch using three-dot diff. The three-dot notation (base...branch) shows changes on branch since it diverged from base.

func Fetch added in v1.1.0

func Fetch(ctx context.Context, r Runner, remote string, args FetchArgs) error

Fetch runs `git fetch <remote>`, applying any options in args, to update remote-tracking branches.

func FirstParentChainSHAs added in v1.9.7

func FirstParentChainSHAs(ctx context.Context, r Runner, mergeRef string) (map[string]bool, error)

FirstParentChainSHAs returns the set of commit SHAs on mergeRef's mainline (first-parent) history.

func HasUpstream added in v1.7.0

func HasUpstream(ctx context.Context, r Runner, dir string) bool

HasUpstream checks whether the current branch in dir has a remote tracking branch.

func HooksDir added in v1.1.0

func HooksDir(ctx context.Context, r Runner) (string, error)

HooksDir returns the absolute path to the repository's hooks directory. Respects core.hooksPath if configured, otherwise falls back to <git-common-dir>/hooks for worktree compatibility.

func IsDirty

func IsDirty(ctx context.Context, r Runner, dir string) (bool, error)

IsDirty returns true if the working tree at the given directory has uncommitted changes.

func IsMergeBaseAncestor added in v1.1.0

func IsMergeBaseAncestor(ctx context.Context, r Runner, ancestor, descendant string) bool

IsMergeBaseAncestor checks if ancestor is an ancestor of descendant using `git merge-base --is-ancestor`.

func IsSHAOnChain added in v1.9.7

func IsSHAOnChain(sha string, chain map[string]bool) bool

IsSHAOnChain reports whether sha is in chain (e.g. from FirstParentChainSHAs).

func IsSquashMerged added in v1.5.0

func IsSquashMerged(ctx context.Context, r Runner, mergeRef, branch string) (bool, error)

IsSquashMerged reports whether branch's diff patch-id matches any commit in mergeRef since their common merge-base, indicating a squash merge.

func IsSquashMergedWithMainlinePatchIDs added in v1.10.0

func IsSquashMergedWithMainlinePatchIDs(ctx context.Context, r Runner, mergeBase, branch string, mainlinePIDs map[string]bool) (bool, error)

IsSquashMergedWithMainlinePatchIDs is IsSquashMerged with a precomputed mainline patch-ID set, letting callers cache it once per merge-base across many branches.

func LastCommitInfo added in v1.5.0

func LastCommitInfo(ctx context.Context, r Runner, branch string) (time.Time, string, error)

LastCommitInfo returns the time and subject of the last commit on the given branch.

func LastCommitTime added in v1.5.0

func LastCommitTime(ctx context.Context, r Runner, branch string) (time.Time, error)

LastCommitTime returns the time of the last commit on the given branch.

func ListIgnoredUntracked added in v1.10.0

func ListIgnoredUntracked(ctx context.Context, r Runner, dir string, pathspecs []string) ([]string, error)

ListIgnoredUntracked lists untracked files git ignores under dir, scoped to pathspecs. An empty pathspecs returns no paths, not every ignored file.

func ListRemotes added in v1.9.4

func ListRemotes(ctx context.Context, r Runner) ([]string, error)

ListRemotes returns the names of all configured remotes by running `git remote`. It returns an empty (non-nil) slice when there are no remotes configured.

func LocalBranches added in v1.5.0

func LocalBranches(ctx context.Context, r Runner) ([]string, error)

LocalBranches returns the list of local branch names.

func MainRepoRoot added in v1.5.0

func MainRepoRoot(ctx context.Context, r Runner) (string, error)

MainRepoRoot returns the absolute path to the main repository root. Unlike RepoRoot, this always returns the main repo root even when called from within a worktree. Uses --git-common-dir whose parent is the main root.

func MainlinePatchIDsSince added in v1.10.0

func MainlinePatchIDsSince(ctx context.Context, r Runner, mergeBase, mergeRef string) (map[string]bool, error)

MainlinePatchIDsSince returns the patch-ID set for mergeRef's history since mergeBase (exclusive), so callers can cache it by mergeBase across branches.

func Merge

func Merge(ctx context.Context, r Runner, dir, branch string, noFF bool) error

Merge runs `git merge [--no-ff] <branch>` inside the given directory.

func MergeAbort added in v1.9.3

func MergeAbort(r Runner, dir string) error

MergeAbort runs `git merge --abort` in dir. Intentionally non-cancellable: merge recovery must complete after Ctrl-C to restore a clean state.

func MergeBase added in v1.1.0

func MergeBase(ctx context.Context, r Runner, ref1, ref2 string) (string, error)

MergeBase returns the merge-base commit of two refs.

func MergeInProgress added in v1.9.3

func MergeInProgress(ctx context.Context, r Runner, dir string) (bool, error)

MergeInProgress reports whether a merge is in progress in dir (MERGE_HEAD exists). Returns (false, nil) when no merge is in progress, (true, nil) when one is, and (false, err) when the check itself fails (infrastructure error).

func MergedBranches added in v1.1.0

func MergedBranches(ctx context.Context, r Runner, branch string) ([]string, error)

MergedBranches returns branches that have been merged into the given branch. Uses the stuck `--merged=<branch>` form: unlike `--`, it doesn't break refs with a leading dash.

func MoveWorktree

func MoveWorktree(ctx context.Context, r Runner, oldPath, newPath string, force bool) error

MoveWorktree moves the worktree from oldPath to newPath (force passes --force twice). Cancellable via ctx; rollback callers should pass context.Background() to avoid stranding it.

func Prune

func Prune(ctx context.Context, r Runner, dryRun bool) (string, error)

Prune runs `git worktree prune` to clean up stale worktree references.

func Push added in v1.7.0

func Push(ctx context.Context, r Runner, dir string) error

Push runs `git push` inside the given directory.

func PushForceWithLease added in v1.7.0

func PushForceWithLease(ctx context.Context, r Runner, dir string) error

PushForceWithLease runs `git push --force-with-lease` inside the given directory.

func PushSetUpstream added in v1.9.7

func PushSetUpstream(ctx context.Context, r Runner, dir, remote, branch string) error

PushSetUpstream publishes branch to remote and sets it as the upstream.

func Rebase added in v1.1.0

func Rebase(ctx context.Context, r Runner, dir, branch string) error

Rebase runs `git rebase <branch>` inside the given directory.

func RemoteExists added in v1.9.0

func RemoteExists(ctx context.Context, r Runner, name string) bool

RemoteExists reports whether a remote with the given name is configured.

func RemotePrune added in v1.9.3

func RemotePrune(ctx context.Context, r Runner, remote string, dryRun bool) ([]string, error)

RemotePrune runs `git remote prune <remote>`, deleting stale remote-tracking refs, and returns the names of the refs that were (or would be) pruned.

func RemoveWorktree

func RemoveWorktree(ctx context.Context, r Runner, path string, force bool) error

RemoveWorktree removes the worktree at the given path.

func RenameBranch

func RenameBranch(ctx context.Context, r Runner, oldBranch, newBranch string) error

RenameBranch renames a local branch from oldBranch to newBranch.

func RepairWorktree added in v1.10.0

func RepairWorktree(ctx context.Context, r Runner, path string) error

RepairWorktree recreates a missing .git linkfile from the still-present admin back-pointer, so a subsequent RemoveWorktree can fully remove it.

func RepoName

func RepoName(ctx context.Context, r Runner) (string, error)

RepoName returns the name of the repository (basename of the root directory).

func RepoRoot

func RepoRoot(ctx context.Context, r Runner) (string, error)

RepoRoot returns the absolute path to the repository root.

func StashApply added in v1.9.2

func StashApply(r Runner, dir, sha string) error

StashApply applies the stash identified by sha in the given directory. git stash apply accepts commit SHAs directly. On conflict the error wraps the stderr output so conflict markers surface to the caller. Intentionally non-cancellable: working-tree restores must complete after cancellation to avoid data loss.

func StashDrop added in v1.9.2

func StashDrop(r Runner, dir, sha string) error

StashDrop drops the stash entry whose commit SHA matches sha. git stash drop requires stash@{N} form; this function resolves the SHA to the ref first. Intentionally non-cancellable: stash cleanup must complete to avoid orphaned stash entries.

func StashPushAndRef added in v1.9.2

func StashPushAndRef(ctx context.Context, r Runner, dir, message string) (string, error)

StashPushAndRef stashes all changes (including untracked files) with the given message and returns the stash object SHA so it can be applied or dropped by reference later.

func UpstreamRemote added in v1.9.7

func UpstreamRemote(ctx context.Context, r Runner, dir string) (string, bool)

UpstreamRemote returns the remote name of the current branch's upstream tracking branch in dir, and whether an upstream exists at all.

func WithItemTimeout added in v1.9.5

func WithItemTimeout(ctx context.Context) (context.Context, context.CancelFunc)

WithItemTimeout returns a child context bounded by itemQueryTimeout. Caller must defer cancel().

Types

type ExecRunner

type ExecRunner struct {
	// Dir is the working directory for git commands. If empty, uses the current directory.
	Dir string
	// Timeout, when positive, applies a per-invocation deadline to every subprocess.
	// Zero means no timeout (relies solely on the caller's context).
	Timeout time.Duration
}

ExecRunner is the production implementation of Runner.

func (*ExecRunner) Run

func (r *ExecRunner) Run(ctx context.Context, args ...string) (string, error)

func (*ExecRunner) RunInDir

func (r *ExecRunner) RunInDir(ctx context.Context, dir string, args ...string) (string, error)

RunInDir is the single execution primitive: all other methods delegate here.

type FetchArgs added in v1.9.5

type FetchArgs struct {
	Prune bool // append --prune: drop remote-tracking refs whose upstream branch was deleted
}

FetchArgs configures Fetch. The zero value performs a plain `git fetch <remote>`.

type MergeTreeResult added in v1.4.0

type MergeTreeResult struct {
	HasConflicts  bool
	ConflictFiles []string
}

MergeTreeResult holds output of git merge-tree --write-tree.

func MergeTree added in v1.4.0

func MergeTree(ctx context.Context, r Runner, branch1, branch2 string) (MergeTreeResult, error)

MergeTree runs git merge-tree --write-tree to simulate a merge without touching the working tree. Requires git 2.38+. Exit code 0 = clean merge, exit code 1 = conflicts, other = error.

type PorcelainDeletionStatus added in v1.10.1

type PorcelainDeletionStatus struct {
	Deleted int
	Other   int
}

PorcelainDeletionStatus holds the classification of unstaged deletions from git status --porcelain=v2.

func ClassifyPorcelainDeletions added in v1.10.1

func ClassifyPorcelainDeletions(ctx context.Context, r Runner, dir string) (PorcelainDeletionStatus, error)

ClassifyPorcelainDeletions runs git status --porcelain=v2 in dir and classifies unstaged deletions vs other changes; v2 avoids v1's leading-space corruption from RunInDir's TrimSpace.

func (PorcelainDeletionStatus) AllDeletions added in v1.10.1

func (s PorcelainDeletionStatus) AllDeletions() bool

AllDeletions returns true if all porcelain entries are unstaged deletions (and at least one exists).

type RemoteFailure added in v1.9.4

type RemoteFailure struct {
	Remote string
	Err    error
}

RemoteFailure records a prune error for a single remote.

func PruneRemotes added in v1.9.4

func PruneRemotes(ctx context.Context, r Runner, remotes []string, dryRun bool) ([]string, []RemoteFailure)

PruneRemotes calls RemotePrune for each remote in order. Pruned refs from all successful remotes are collected and returned. Any remote that fails is recorded in the failures slice; iteration continues regardless of errors. Both return values are initialized as non-nil empty slices.

type Runner

type Runner interface {
	Run(ctx context.Context, args ...string) (string, error)
	RunInDir(ctx context.Context, dir string, args ...string) (string, error)
}

Runner abstracts git command execution for testability.

type WorktreeEntry

type WorktreeEntry struct {
	Path     string
	HEAD     string
	Branch   string
	Bare     bool
	Prunable bool
}

WorktreeEntry represents a parsed worktree from `git worktree list --porcelain`.

func FilterEntries added in v1.5.0

func FilterEntries(entries []WorktreeEntry, mainBranch string) []WorktreeEntry

FilterEntries returns entries with bare worktrees, empty branches, and the main branch removed. This is the common pre-filter for status, log, and clean.

func FindEntry added in v1.9.0

func FindEntry(entries []WorktreeEntry, branch string) *WorktreeEntry

FindEntry returns the first entry matching branch, or nil if none. Counterpart to FilterEntries.

func ListWorktrees

func ListWorktrees(ctx context.Context, r Runner) ([]WorktreeEntry, error)

ListWorktrees returns all worktrees by parsing `git worktree list --porcelain`.

Jump to

Keyboard shortcuts

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