Documentation
¶
Index ¶
- Constants
- Variables
- func AbortRebase(r Runner, dir string) error
- func AddRemote(ctx context.Context, r Runner, name, url string) error
- func AddWorktree(ctx context.Context, r Runner, path, branch, source string) error
- func AddWorktreeFromBranch(ctx context.Context, r Runner, path, branch string) error
- func AheadBehind(ctx context.Context, r Runner, dir string) (ahead, behind int, _ error)
- func BranchExists(ctx context.Context, r Runner, branch string) bool
- func Checkout(ctx context.Context, r Runner, dir, branch string) error
- func CommitCountSince(ctx context.Context, r Runner, branch string, since time.Duration) (int, error)
- func CommonDir(ctx context.Context, r Runner) (string, error)
- func CurrentBranch(ctx context.Context, r Runner, dir string) (string, error)
- func DefaultBranch(ctx context.Context, r Runner) (string, error)
- func DeleteBranch(ctx context.Context, r Runner, branch string, force bool) error
- func DeleteRemoteBranch(ctx context.Context, r Runner, remote, branch string) error
- func DiffNameOnly(ctx context.Context, r Runner, base, branch string) ([]string, error)
- func Fetch(ctx context.Context, r Runner, remote string, args FetchArgs) error
- func FirstParentChainSHAs(ctx context.Context, r Runner, mergeRef string) (map[string]bool, error)
- func HasUpstream(ctx context.Context, r Runner, dir string) bool
- func HooksDir(ctx context.Context, r Runner) (string, error)
- func IsDirty(ctx context.Context, r Runner, dir string) (bool, error)
- func IsMergeBaseAncestor(ctx context.Context, r Runner, ancestor, descendant string) bool
- func IsSHAOnChain(sha string, chain map[string]bool) bool
- func IsSquashMerged(ctx context.Context, r Runner, mergeRef, branch string) (bool, error)
- func IsSquashMergedWithMainlinePatchIDs(ctx context.Context, r Runner, mergeBase, branch string, ...) (bool, error)
- func LastCommitInfo(ctx context.Context, r Runner, branch string) (time.Time, string, error)
- func LastCommitTime(ctx context.Context, r Runner, branch string) (time.Time, error)
- func ListIgnoredUntracked(ctx context.Context, r Runner, dir string, pathspecs []string) ([]string, error)
- func ListRemotes(ctx context.Context, r Runner) ([]string, error)
- func LocalBranches(ctx context.Context, r Runner) ([]string, error)
- func MainRepoRoot(ctx context.Context, r Runner) (string, error)
- func MainlinePatchIDsSince(ctx context.Context, r Runner, mergeBase, mergeRef string) (map[string]bool, error)
- func Merge(ctx context.Context, r Runner, dir, branch string, noFF bool) error
- func MergeAbort(r Runner, dir string) error
- func MergeBase(ctx context.Context, r Runner, ref1, ref2 string) (string, error)
- func MergeInProgress(ctx context.Context, r Runner, dir string) (bool, error)
- func MergedBranches(ctx context.Context, r Runner, branch string) ([]string, error)
- func MoveWorktree(ctx context.Context, r Runner, oldPath, newPath string, force bool) error
- func Prune(ctx context.Context, r Runner, dryRun bool) (string, error)
- func Push(ctx context.Context, r Runner, dir string) error
- func PushForceWithLease(ctx context.Context, r Runner, dir string) error
- func PushSetUpstream(ctx context.Context, r Runner, dir, remote, branch string) error
- func Rebase(ctx context.Context, r Runner, dir, branch string) error
- func RemoteExists(ctx context.Context, r Runner, name string) bool
- func RemotePrune(ctx context.Context, r Runner, remote string, dryRun bool) ([]string, error)
- func RemoveWorktree(ctx context.Context, r Runner, path string, force bool) error
- func RenameBranch(ctx context.Context, r Runner, oldBranch, newBranch string) error
- func RepairWorktree(ctx context.Context, r Runner, path string) error
- func RepoName(ctx context.Context, r Runner) (string, error)
- func RepoRoot(ctx context.Context, r Runner) (string, error)
- func StashApply(r Runner, dir, sha string) error
- func StashDrop(r Runner, dir, sha string) error
- func StashPushAndRef(ctx context.Context, r Runner, dir, message string) (string, error)
- func UpstreamRemote(ctx context.Context, r Runner, dir string) (string, bool)
- func WithItemTimeout(ctx context.Context) (context.Context, context.CancelFunc)
- type ExecRunner
- type FetchArgs
- type MergeTreeResult
- type PorcelainDeletionStatus
- type RemoteFailure
- type Runner
- type WorktreeEntry
Constants ¶
const ( CmdMergeBase = "merge-base" CmdDiff = "diff" CmdLog = "log" )
const DefaultRemote = "origin"
DefaultRemote is the conventional name for the primary upstream remote.
Variables ¶
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
AbortRebase runs `git rebase --abort` inside the given directory. Intentionally non-cancellable: rebase recovery must succeed even after Ctrl-C.
func AddWorktree ¶
AddWorktree creates a new worktree at the given path with a new branch from source.
func AddWorktreeFromBranch ¶ added in v1.5.0
AddWorktreeFromBranch creates a worktree from an existing branch (no -b flag).
func AheadBehind ¶
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 ¶
BranchExists checks whether a local branch exists.
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
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
CurrentBranch returns the short branch name checked out in the given directory. Returns an error with a hint if HEAD is detached.
func DefaultBranch ¶
DefaultBranch detects the default branch (main or master).
func DeleteBranch ¶
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
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
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
Fetch runs `git fetch <remote>`, applying any options in args, to update remote-tracking branches.
func FirstParentChainSHAs ¶ added in v1.9.7
FirstParentChainSHAs returns the set of commit SHAs on mergeRef's mainline (first-parent) history.
func HasUpstream ¶ added in v1.7.0
HasUpstream checks whether the current branch in dir has a remote tracking branch.
func HooksDir ¶ added in v1.1.0
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 ¶
IsDirty returns true if the working tree at the given directory has uncommitted changes.
func IsMergeBaseAncestor ¶ added in v1.1.0
IsMergeBaseAncestor checks if ancestor is an ancestor of descendant using `git merge-base --is-ancestor`.
func IsSHAOnChain ¶ added in v1.9.7
IsSHAOnChain reports whether sha is in chain (e.g. from FirstParentChainSHAs).
func IsSquashMerged ¶ added in v1.5.0
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
LastCommitInfo returns the time and subject of the last commit on the given branch.
func LastCommitTime ¶ added in v1.5.0
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
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
LocalBranches returns the list of local branch names.
func MainRepoRoot ¶ added in v1.5.0
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 MergeAbort ¶ added in v1.9.3
MergeAbort runs `git merge --abort` in dir. Intentionally non-cancellable: merge recovery must complete after Ctrl-C to restore a clean state.
func MergeInProgress ¶ added in v1.9.3
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
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 ¶
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 PushForceWithLease ¶ added in v1.7.0
PushForceWithLease runs `git push --force-with-lease` inside the given directory.
func PushSetUpstream ¶ added in v1.9.7
PushSetUpstream publishes branch to remote and sets it as the upstream.
func RemoteExists ¶ added in v1.9.0
RemoteExists reports whether a remote with the given name is configured.
func RemotePrune ¶ added in v1.9.3
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 ¶
RemoveWorktree removes the worktree at the given path.
func RenameBranch ¶
RenameBranch renames a local branch from oldBranch to newBranch.
func RepairWorktree ¶ added in v1.10.0
RepairWorktree recreates a missing .git linkfile from the still-present admin back-pointer, so a subsequent RemoveWorktree can fully remove it.
func StashApply ¶ added in v1.9.2
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
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
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
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
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.
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
MergeTreeResult holds output of git merge-tree --write-tree.
type PorcelainDeletionStatus ¶ added in v1.10.1
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
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 ¶
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`.