git

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Jul 12, 2026 License: AGPL-3.0 Imports: 13 Imported by: 0

Documentation

Overview

Package git encapsulates the per-session git worktree: creation, diff stats, push, and cleanup.

Each agent session runs inside its own worktree under {configDir}/worktrees/, on a branch named "{BranchPrefix}{SessionTitle}". The worktree is torn down on pause (branch preserved) and destroyed entirely on kill. Callers interact via the GitWorktree type; a CommandRunner abstraction makes the exec layer injectable for tests.

Error handling convention: errors are wrapped with fmt.Errorf("...: %w", err) so callers can match the cause. ErrBranchGone is a sentinel returned when the underlying branch has disappeared between operations — callers typically recover by rediscovering the branch or dropping the session.

Index

Constants

View Source
const MaxBranchSearchResults = 50

MaxBranchSearchResults is the maximum number of branches returned by SearchBranches.

Variables

View Source
var ErrBranchGone = errors.New("branch not found locally or on remote")

ErrBranchGone is returned by Setup when the branch a paused instance was pointing at has disappeared both locally and on origin — typically because an operator ran `git branch -D <name>` from outside the app. Callers use errors.Is to classify the failure and surface a recovery hint (kill-to-clean-up) instead of a generic setup error.

Functions

func CleanupWorktrees

func CleanupWorktrees(configDir string, runner CommandRunner) error

CleanupWorktrees removes all worktrees and their associated branches. configDir is the workspace config directory; if empty, falls back to GetConfigDir(). Pass nil for runner to use the default subprocess runner.

func CurrentBranch

func CurrentBranch(repoPath string, runner CommandRunner) (string, error)

CurrentBranch returns the current branch name for the given repo directory. Pass nil for runner to use the default subprocess runner.

func FetchBranches

func FetchBranches(repoPath string, runner CommandRunner)

FetchBranches fetches and prunes remote-tracking branches (best-effort, won't fail if offline). Pass nil for runner to use the default subprocess runner.

func IsGitRepo

func IsGitRepo(path string, runner CommandRunner) bool

IsGitRepo checks if the given path is within a git repository. Pass nil for runner to use the default subprocess runner.

func RemoveTitleSidecar added in v0.6.0

func RemoveTitleSidecar(worktreePath string)

RemoveTitleSidecar deletes the title sidecar if present. Exported for callers outside this package that remove a worktree without going through GitWorktree.Cleanup — e.g. session.RemoveOrphanWorktree, which force-removes an orphaned worktree directly via `git worktree remove`. Best-effort, mirroring removeTitleSidecar.

func SearchBranches

func SearchBranches(repoPath, filter string, runner CommandRunner) ([]string, error)

SearchBranches searches for branches whose name contains filter (case-insensitive), ordered by most recently updated first. Returns at most MaxBranchSearchResults. If filter is empty, returns all branches up to the limit. Pass nil for runner to use the default subprocess runner.

func WorktreeTitleSidecarPath added in v0.4.0

func WorktreeTitleSidecarPath(worktreePath string) string

WorktreeTitleSidecarPath returns the path of the sidecar file that records a worktree's original instance title. It lives next to the worktree directory (a sibling file), NOT inside it — keeping it out of the work tree avoids polluting git status/diffs. Orphan discovery reads it to reconstruct the exact display title — and therefore the exact tmux session name — which the lossy branch-name sanitization (lowercasing, dash-collapsing) otherwise destroys.

Types

type CommandRunner

type CommandRunner = internalexec.Executor

CommandRunner is an alias for internal/exec.Executor. Kept as a type alias so git-package callers keep the familiar name while the concrete interface lives in a leaf package shared with cmd/.

func DefaultRunner

func DefaultRunner() CommandRunner

DefaultRunner returns the production subprocess runner.

type DiffStats

type DiffStats struct {
	// Content is the full diff content
	Content string
	// Added is the number of added lines
	Added int
	// Removed is the number of removed lines
	Removed int
	// Error holds any error that occurred during diff computation
	// This allows propagating setup errors (like missing base commit) without breaking the flow
	Error error
}

DiffStats holds statistics about the changes in a diff

func DiffUncommitted

func DiffUncommitted(repoPath string, runner CommandRunner) *DiffStats

DiffUncommitted returns the diff of uncommitted changes in the given repo directory. Used for workspace terminals that operate on the root repo without a worktree. Only shows tracked file changes to avoid mutating the user's git index. Pass nil for runner to use the default subprocess runner.

func DiffUncommittedShortStat

func DiffUncommittedShortStat(repoPath string, runner CommandRunner) *DiffStats

DiffUncommittedShortStat returns only line counts for uncommitted changes. Pass nil for runner to use the default subprocess runner.

func (*DiffStats) IsEmpty

func (d *DiffStats) IsEmpty() bool

IsEmpty reports whether the diff contains no added lines, no removed lines, and no body content — the state presented when a session has not yet diverged from its base commit.

type GitWorktree

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

GitWorktree manages git worktree operations for a session

func NewGitWorktree

func NewGitWorktree(repoPath string, sessionName string, configDir string) (tree *GitWorktree, branchname string, err error)

NewGitWorktree creates a new GitWorktree instance. configDir is the workspace config directory; if empty, falls back to GetConfigDir().

func NewGitWorktreeFromBranch

func NewGitWorktreeFromBranch(repoPath string, branchName string, sessionName string, configDir string) (*GitWorktree, error)

NewGitWorktreeFromBranch creates a new GitWorktree that uses an existing branch. The branch will not be deleted on cleanup. configDir is the workspace config directory; if empty, falls back to GetConfigDir().

func NewGitWorktreeFromBranchWithRunner

func NewGitWorktreeFromBranchWithRunner(repoPath string, branchName string, sessionName string, configDir string, runner CommandRunner) (*GitWorktree, error)

NewGitWorktreeFromBranchWithRunner is NewGitWorktreeFromBranch with an injected CommandRunner for tests. Passing nil falls back to the default subprocess runner.

func NewGitWorktreeFromStorage

func NewGitWorktreeFromStorage(repoPath string, worktreePath string, sessionName string, branchName string, baseCommitSHA string, isExistingBranch bool, configDir string) *GitWorktree

NewGitWorktreeFromStorage rehydrates a GitWorktree from its persisted [session.GitWorktreeData] fields. Unlike NewGitWorktree, this constructor does no git work — it simply reattaches the in-memory wrapper to an on-disk worktree that already exists (or that needs to be rebuilt by a caller via Setup on resume).

func NewGitWorktreeFromStorageWithRunner

func NewGitWorktreeFromStorageWithRunner(repoPath string, worktreePath string, sessionName string, branchName string, baseCommitSHA string, isExistingBranch bool, configDir string, runner CommandRunner) *GitWorktree

NewGitWorktreeFromStorageWithRunner is NewGitWorktreeFromStorage with an injected CommandRunner for tests. Passing nil falls back to the default subprocess runner.

func NewGitWorktreeWithRunner

func NewGitWorktreeWithRunner(repoPath string, sessionName string, configDir string, runner CommandRunner) (tree *GitWorktree, branchname string, err error)

NewGitWorktreeWithRunner is NewGitWorktree with an injected CommandRunner (used by tests). Passing nil falls back to the default runner. configDir must be a concrete workspace config directory (callers thread this through via config.WorkspaceContext); passing empty string falls back to the global directory and logs a warning.

func (*GitWorktree) ApplyStash added in v0.6.0

func (g *GitWorktree) ApplyStash(sha string) error

ApplyStash applies the stash commit sha onto the worktree, targeting the exact commit rather than stack position (stash@{0}) — refs/stash is shared across every worktree of this repo. A no-op for an empty sha.

Because StashChanges' commit is two-parent (see its doc comment), `git stash apply` treats every previously-untracked file as a clean "add" against the index, so it comes back staged (`git status` would show it as `A`) rather than untracked (`??`) — unlike real `git stash apply -u`, which restores untracked content straight to disk without touching the index. To match the user-visible result of a real stash, ApplyStash finds every path that is newly added in the index relative to HEAD (`git diff --cached --diff-filter=A`) and unstages it (`git reset --`); the file's content on disk is untouched, only its index entry is removed, so it reads back as untracked. Best-effort: a failure here is logged, not returned, since the restore itself already succeeded and the file is still present (just staged) either way.

On a clean apply, the matching stash-list entry is dropped (also best-effort, logged not returned, for the same reason). On conflict, the stash entry is left in place — mirroring `git stash pop`'s own safety behavior — and the error is returned so the caller does not clear its reference to it; neither the unstage nor the drop step runs in that case.

func (*GitWorktree) Cleanup

func (g *GitWorktree) Cleanup() (err error)

Cleanup removes the worktree and associated branch

func (*GitWorktree) CommitChanges

func (g *GitWorktree) CommitChanges(commitMessage string) error

CommitChanges commits changes locally without pushing to remote

func (*GitWorktree) Diff

func (g *GitWorktree) Diff() *DiffStats

Diff returns the git diff between the worktree and the base branch along with statistics

func (*GitWorktree) DiffShortStat

func (g *GitWorktree) DiffShortStat() *DiffStats

DiffShortStat returns only the line counts (Added/Removed) without full diff content. Uses git diff --shortstat which is significantly cheaper for large diffs.

func (*GitWorktree) DropStash added in v0.6.0

func (g *GitWorktree) DropStash(sha string) error

DropStash removes the stash-list entry matching sha, if present. No-op if sha is empty or no longer found (already dropped, or never stored). Resolves each entry's own commit hash via `git rev-parse` rather than assuming stack position, for the same reason ApplyStash does — refs/stash is shared across every worktree of this repo, so "top of stack" could belong to a different worktree by now. Runs against repoPath rather than worktreePath since refs/stash is a repo-level concept and the worktree directory may not exist at call time (e.g. after Kill has already removed it).

Narrow TOCTOU: the loop resolves stash@{N} -> sha, then reuses that same stash@{N} name in the "stash drop" call below rather than the resolved sha, so a concurrent push from another worktree that lands between the two could shift what stash@{N} refers to. Left as-is deliberately — git serializes stash ref updates, so the window is a single process's gap between two subprocess calls, and worst case is a failed/no-op drop (caught by the caller's own list scan on any retry), not data loss.

func (*GitWorktree) GetBaseCommitSHA

func (g *GitWorktree) GetBaseCommitSHA() string

GetBaseCommitSHA returns the base commit SHA for the worktree

func (*GitWorktree) GetBranchName

func (g *GitWorktree) GetBranchName() string

GetBranchName returns the name of the branch associated with this worktree

func (*GitWorktree) GetRepoName

func (g *GitWorktree) GetRepoName() string

GetRepoName returns the name of the repository (last part of the repoPath).

func (*GitWorktree) GetRepoPath

func (g *GitWorktree) GetRepoPath() string

GetRepoPath returns the path to the repository

func (*GitWorktree) GetStashRef added in v0.6.0

func (g *GitWorktree) GetStashRef() string

GetStashRef returns the pending stash commit SHA, or "" if none.

func (*GitWorktree) GetWorktreePath

func (g *GitWorktree) GetWorktreePath() string

GetWorktreePath returns the path to the worktree

func (*GitWorktree) IsBranchCheckedOut

func (g *GitWorktree) IsBranchCheckedOut() (bool, error)

IsBranchCheckedOut checks if the instance branch is currently checked out

func (*GitWorktree) IsDirty

func (g *GitWorktree) IsDirty() (bool, error)

IsDirty checks if the worktree has uncommitted changes

func (*GitWorktree) IsExistingBranch

func (g *GitWorktree) IsExistingBranch() bool

IsExistingBranch returns whether this worktree uses a pre-existing branch

func (*GitWorktree) Merge added in v0.3.0

func (g *GitWorktree) Merge(sourceBranch string) error

Merge runs `git merge <sourceBranch>` in the worktree's directory, bringing another session's branch into this one. On conflict or any other non-zero exit, the git error/output is returned as-is and the merge is left exactly as git leaves it (MERGE_HEAD + conflict markers on a real conflict) — callers must not run `merge --abort` automatically, so a conflicted merge stays available for the user (or the agent) to resolve and commit.

func (*GitWorktree) OpenBranchURL

func (g *GitWorktree) OpenBranchURL() error

OpenBranchURL opens the branch URL in the default browser

func (*GitWorktree) Prune

func (g *GitWorktree) Prune() error

Prune removes all working tree administrative files and directories

func (*GitWorktree) PushChanges

func (g *GitWorktree) PushChanges(commitMessage string, open bool) error

PushChanges commits and pushes changes in the worktree to the remote branch

func (*GitWorktree) Remove

func (g *GitWorktree) Remove() error

Remove removes the worktree but keeps the branch

func (*GitWorktree) SetStashRef added in v0.6.0

func (g *GitWorktree) SetStashRef(sha string)

SetStashRef sets the pending stash commit SHA (or clears it, for "").

func (*GitWorktree) Setup

func (g *GitWorktree) Setup() (err error)

Setup creates a new worktree for the session

func (*GitWorktree) StashChanges added in v0.6.0

func (g *GitWorktree) StashChanges(message string) (string, error)

StashChanges snapshots the worktree's tracked and untracked changes into a stash commit without disturbing the shared stash stack's ordering, and without ever calling `git stash push`/`create` (both pass through the same option parser, which documents only `git stash create [<message>]` — no -u/--include-untracked; passing it anyway silently swallows the flag into the commit message and drops untracked files from the snapshot, verified empirically against the installed git). Instead this builds, by hand, the same two-parent "index on ..." / "On ..." commit pair `git stash push -u` itself would produce, via plumbing against a scratch GIT_INDEX_FILE so the real index and working tree are left untouched:

  • iCommit: tree = HEAD plus staged/unstaged modifications to already-tracked files (`add -u`), parent = HEAD. This is the "index" side of the stash.
  • the returned commit: tree = iCommit's tree plus untracked files (`add -A` on the same scratch index), parents = [HEAD, iCommit]. Untracked files exist only in this tree, not iCommit's, so `stash apply` (which diffs parent1..parent2 for the index and parent2..commit for the worktree) restores them via the second diff, same as it would for a real `stash push -u` entry.

Note this is deliberately a two-parent commit, not real git's three-parent (b, i, u) --include-untracked format — there is no separate untracked-only commit unpacked straight onto disk. Building that would mean reproducing stash's internal object plumbing exactly; instead ApplyStash restores content via this simpler shape and then re-derives the tracked/untracked classification itself (see its doc comment) so the user-visible result still matches real stash.

`git stash store` then anchors the resulting commit against gc (dangling commits are prunable after gc.pruneExpire) and makes it visible via `git stash list` for manual recovery, using the SHA — never stack position — that plumbing already handed back, so there is no race window reading back "top of stack" afterward. Returns "" (no error) if the worktree has nothing to stash, mirroring IsDirty's scope (tracked and untracked).

Jump to

Keyboard shortcuts

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