worktree

package
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrWorktreeDirty means removal would discard local file changes.
	ErrWorktreeDirty = errors.New("refusing to remove worktree with local changes")
	// ErrWorktreeActive means a supported coding agent is running in the worktree.
	ErrWorktreeActive = errors.New("refusing to remove worktree with a running agent")
	// ErrWorktreeLocalCommits means a review worktree's HEAD has commits the
	// PR head never had: work that exists only in this checkout. It is also
	// returned when that cannot be ruled out, so review cleanup fails closed.
	ErrWorktreeLocalCommits = errors.New("refusing to remove worktree that may hold local commits")
	// ErrNotPRReview means a worktree named after a PR is not checked out as
	// that PR's review (see Classify), so review cleanup must leave it alone.
	ErrNotPRReview = errors.New("refusing to remove worktree that is not a PR review checkout")
)
View Source
var GitMu sync.Mutex

GitMu serializes git worktree operations to prevent concurrent index.lock conflicts.

Functions

func AgeDays

func AgeDays(path string) (int, error)

AgeDays returns the age of a worktree in days based on its last commit.

func AgeHours

func AgeHours(path string) (int, error)

AgeHours returns the age of a worktree in hours based on its last commit.

func CleanupFailedAdd added in v0.7.0

func CleanupFailedAdd(originPath, worktreePath, branch string)

CleanupFailedAdd cleans up after a failed "git worktree add" that may have created the branch and/or a partial worktree directory but failed to complete. It removes the partial worktree directory, prunes git's worktree metadata, and deletes the orphaned branch.

originPath is the main repo directory, worktreePath is the target worktree directory, and branch is the git branch that was being created.

func CreateFromMain added in v0.11.0

func CreateFromMain(originPath, worktreePath, worktreeName, branch string) error

CreateFromMain fetches origin/main and creates a new worktree checked out to a new branch cut from it. Used for feature work (branch didn't exist before), as opposed to PR review worktrees which check out an existing remote branch/ref instead.

Adds the worktree with --no-checkout and checks it out as a separate step, so a failed checkout is reported on its own and the partial worktree is cleaned up. Serializes on RepoLock and GitMu to prevent concurrent index.lock conflicts across worktree operations on the same origin repo, in this process or another.

func CreateFromPR added in v0.11.0

func CreateFromPR(originPath, worktreePath, worktreeName string, prNumber int) error

CreateFromPR fetches the PR's remote branch (pull/N/head) into a local pr-N branch and creates a worktree checked out to it. Used for PR review worktrees, which check out an existing remote ref, as opposed to CreateFromMain which cuts a brand new branch for feature work.

If worktreePath already exists by the time the lock is acquired (e.g. a concurrent caller created it first), this is a no-op — callers that need a fast pre-lock existence check too (to skip the wait entirely in the common case) can still do their own os.Stat before calling.

Adds the worktree with --no-checkout and checks it out as a separate step, so a failed checkout is reported on its own and the partial worktree is cleaned up. Serializes on RepoLock and GitMu to prevent concurrent index.lock conflicts across worktree operations on the same origin repo, in this process or another.

func FastForward added in v0.12.0

func FastForward(ctx context.Context, worktreePath string, prNumber int) error

FastForward fast-forwards the worktree onto refs/remotes/origin/pr-N. A non-ff merge returns *ErrNonFastForward. Callers that want the worktree to match GitHub anyway should ResetToRemotePR when the tree is clean.

func FetchPRHead added in v0.12.0

func FetchPRHead(ctx context.Context, originPath string, prNumber int) error

FetchPRHead fetches GitHub's pull/N/head into refs/remotes/origin/pr-N.

func FetchRefspec added in v0.12.0

func FetchRefspec(ctx context.Context, originPath, refspec string) error

FetchRefspec runs `git fetch origin <refspec>` in originPath.

func HEAD(worktreePath string) (string, error)

HEAD returns the full SHA of HEAD in the given working tree.

func IsMissingPRRef added in v0.12.0

func IsMissingPRRef(err error) bool

IsMissingPRRef reports whether git fetch failed because pull/N/head is gone (PR deleted, or GitHub no longer advertises the ref). Callers should skip, not retry as a git flake.

func IsNonFastForward added in v0.12.0

func IsNonFastForward(err error) bool

IsNonFastForward reports whether err is a rejected fast-forward.

func LastActivity

func LastActivity(path string) (time.Time, error)

LastActivity returns the date of the last commit in the worktree.

func PRBranch added in v0.13.0

func PRBranch(prNumber int) string

PRBranch is the local branch a PR review worktree checks out: pr-<number>, fetched from GitHub's pull/<number>/head. Classify relies on it to tell a review apart from a work stream whose name also ends in -pr-<number>.

func PRName added in v0.12.0

func PRName(repoShort string, prNumber int) string

PRName is the directory name of a PR review worktree: <repo>-pr-<number>. Every caller goes through here so the layout has one definition to change.

func PRPath added in v0.12.0

func PRPath(basePath, repoShort string, prNumber int) string

PRPath is where a PR review worktree for repoShort lives under basePath.

func ParseBranchFromName

func ParseBranchFromName(name string) string

ParseBranchFromName extracts the branch suffix from a worktree directory name. e.g., "mono-feature-branch" -> "feature-branch"

func ParseRepoFromName

func ParseRepoFromName(name string) string

ParseRepoFromName extracts the repo short name from a worktree directory name. e.g., "mono-pr-1234" -> "mono"

func RemotePRRef added in v0.12.0

func RemotePRRef(prNumber int) string

RemotePRRef is the remote-tracking ref used to store pull/N/head. Fetching into the local pr-N branch is refused when that branch is checked out in a worktree; this ref is never checked out.

func RemovalBlocked added in v0.12.0

func RemovalBlocked(err error) bool

RemovalBlocked reports whether err is an expected safety refusal rather than a Git or filesystem failure.

func Remove added in v0.12.0

func Remove(originPath, worktreePath string) error

Remove removes a linked worktree only when it is inactive and contains no local changes. Zen-generated review context is reproducible and does not make a worktree dirty. A missing worktree is already removed and succeeds.

func RemoveReview added in v0.13.0

func RemoveReview(ctx context.Context, originPath, worktreePath string, prNumber int, prHead string) error

RemoveReview removes the review worktree of a merged PR. On top of the checks Remove makes, it refuses unless the worktree is still checked out as review prNumber (ErrNotPRReview) and HEAD is prHead, GitHub's last head for the PR, or one of its ancestors (ErrWorktreeLocalCommits). Review worktrees are never pushed to the author's branch, so any commit beyond prHead was made here and exists nowhere else. When prHead is not in the local object store, pull/<prNumber>/head is fetched first; if the comparison still cannot be made, removal is refused.

func RemoveStaleLock added in v0.7.0

func RemoveStaleLock(lockFile, name string) bool

RemoveStaleLock removes lockFile if it is a regular file last modified more than staleLockAge ago, and reports whether it did. Missing files, younger locks, and anything that is not a regular file are left alone: removing a lock that a running git still holds makes its rename fail with "unable to write new index file".

func ResetToRemotePR added in v0.12.0

func ResetToRemotePR(ctx context.Context, worktreePath string, prNumber int) error

ResetToRemotePR points the worktree at refs/remotes/origin/pr-N with reset --hard. Used after a non-fast-forward fetch (force-push) when the tree has no tracked local changes and the user confirmed. Untracked files (CLAUDE.local.md, .zen/) are left in place. The previous tip remains in the reflog as pr-N@{1}.

func RevParse added in v0.12.0

func RevParse(worktreePath, rev string) (string, error)

RevParse resolves a revision in worktreePath.

func SHAEqual added in v0.12.0

func SHAEqual(a, b string) bool

SHAEqual reports whether two git object names refer to the same commit. Empty strings never match. Short prefixes of at least 7 hex chars match a longer SHA.

func TrackedDirty added in v0.12.0

func TrackedDirty(worktreePath string) (bool, error)

TrackedDirty reports whether worktreePath has staged or unstaged changes to tracked files. Untracked files (CLAUDE.local.md, AGENTS.md, .zen/) are ignored so injected context does not block a fast-forward.

func UniqueCommitCount added in v0.12.0

func UniqueCommitCount(worktreePath string, prNumber int) (int, error)

UniqueCommitCount is how many commits are on HEAD that are not in refs/remotes/origin/pr-N. Used to warn before reset --hard: a linear GitHub update with no local commits is 0; a local review commit or a rewritten remote is typically ≥1.

Types

type ErrNonFastForward added in v0.12.0

type ErrNonFastForward struct {
	Detail string
}

ErrNonFastForward is returned when a worktree cannot be fast-forwarded (diverged history, typically a force-push). Callers should ResetToRemotePR when the worktree is clean and idle, not skip forever.

func (*ErrNonFastForward) Error added in v0.12.0

func (e *ErrNonFastForward) Error() string

type RepoLock added in v0.13.0

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

RepoLock is a cross-process lock on one origin repository. GitMu only serializes worktree operations inside a single zen process, so `zen watch` creating review worktrees could race `zen work new` or `zen review` in another process on the same repository's index, refs, and config. The lock is an flock on a stable sibling file, .<repo>.zen.lock, which other tools that change the origin checkout can take too.

func AcquireRepoLock added in v0.13.0

func AcquireRepoLock(originPath string) (*RepoLock, error)

AcquireRepoLock blocks until no other process holds originPath's lock.

func (*RepoLock) Release added in v0.13.0

func (lock *RepoLock) Release() error

Release unlocks and closes the lock. It is safe to call more than once.

type Stats

type Stats struct {
	Total     int            `json:"total"`
	PRReviews int            `json:"pr_reviews"`
	Features  int            `json:"features"`
	ByRepo    map[string]int `json:"by_repo"`
}

Stats holds worktree statistics.

func GetStats

func GetStats(cfg *config.Config) (*Stats, error)

GetStats computes statistics across all worktrees.

type Type

type Type string

Type classifies a worktree.

const (
	TypePRReview Type = "pr-review"
	TypeFeature  Type = "feature"
)

func Classify

func Classify(name, branch string, detached bool) (Type, int)

Classify reports whether a worktree is a PR review and, if so, for which PR.

The directory name alone is not proof: a work stream can end in -pr-<N> too (zen work new mono fix-pr-123 creates mono-fix-pr-123 on branch <branch_prefix>/fix-pr-123). A review must also be checked out on the PRBranch zen creates for that same PR, or on a detached HEAD. branch is the checked-out branch name, empty when detached. Anything else is feature work, which the daemon's merged-review cleanup never touches.

type Worktree

type Worktree struct {
	Path     string `json:"path"`
	Name     string `json:"name"`
	Branch   string `json:"branch"`
	Type     Type   `json:"type"`
	PRNumber int    `json:"pr_number,omitempty"`
	Repo     string `json:"repo"`
}

Worktree represents a discovered git worktree.

func ListAll

func ListAll(cfg *config.Config) ([]Worktree, error)

ListAll lists worktrees across all configured repositories.

func ListForRepo

func ListForRepo(cfg *config.Config, repo string) ([]Worktree, error)

ListForRepo lists all worktrees for a given repository using `git worktree list`.

Jump to

Keyboard shortcuts

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