worktree

package
v0.16.2 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: MIT Imports: 26 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

Overview

Package worktree is the machine-scoped worktree store (itd-2609091014076309, spc-2609301811532881): a session's or an agent's worktree lives at ~/.abcd.noindex/worktrees/<root-sha>/<name>/, keyed on the repository's root commit in the full form the history and transcript stores use, and never beside the user's own projects (adr-2609091248200336, whose location adr-2610031751065746 spells under the renamed home).

It is the only code that makes a directory in the store. The lane for a repository is LaneFor's answer, its levels are made by Lane.Ensure, a worktree already there is found by Adopt, and a new one is made by Add; the build loop's lane step calls these rather than a copy of them, so there is one way a worktree enters the store.

The package never prints. It returns values and a typed *Refusal, whose text is home-redacted, and a front door formats them.

Index

Constants

View Source
const (
	// WhereStore is a direct child of the repository's lane.
	WhereStore = "store"
	// WhereOutside is anywhere else git lists a worktree: listed, never touched.
	WhereOutside = "outside"
	// WhereSibling is one of abcd's own sibling stores kept in the lane (the
	// embargo store, iss-2610230014564359): never judged, archived or removed.
	WhereSibling = "sibling"
)

Where a row's worktree sits.

View Source
const (
	OutcomeReclaimed    = "reclaimed"
	OutcomeWouldReclaim = "would reclaim"
	OutcomeKept         = "kept"
)

A prune row's outcome.

View Source
const (
	QuietDaysKey     = "worktrees.quiet_days"
	DefaultQuietDays = 14
)

The quiet window's configuration: the layered key, its bundled default, and the most days it takes. The ceiling keeps the window's arithmetic far from overflow, where a huge window would wrap round and read every worktree as quiet.

View Source
const CacheTrimAge = 48 * time.Hour

CacheTrimAge is how long an entry goes unused before the trim deletes it.

View Source
const OutcomeQuiet = "quiet"

OutcomeQuiet is a quiet candidate's outcome: listed with its dossier and left in place.

Variables

View Source
var NotesRel = abcdhome.Rel("notes")

NotesRel is the notes archive, relative to the caller's home.

View Source
var StoreRel = abcdhome.Rel("worktrees")

StoreRel is the worktree store, relative to the caller's home.

Functions

func Adopt

func Adopt(repoRoot string, l Lane, name, branch string) (bool, error)

Adopt reports whether git already lists a worktree at name's path in the lane on branch (a short branch name): one the store made earlier, whose maker was stopped before it recorded it. One at that path on any other branch is refused, and so is a listed worktree with no real directory where git says it is; neither is touched.

func Merged

func Merged(dir, def, ref, tip string, prs []byte) (merged bool, by string)

Merged is the merged judgement for a caller outside the store: whether the commit tip of the branch ref (refs/heads/<b> or refs/remotes/<r>/<b>) is merged into the default branch def, read from dir, and how. prs is the forge's listing of pull requests from that branch as JSON in gh's field names (headRefName, headRefOid, baseRefName, isCrossRepository, state), or nil when the forge was not asked; a listing that does not parse counts as none. It is the one judgement the worktree store's reclaim and the shell guard's delete proof share (iss-2610241239492159), erring towards unmerged the same way for both.

func QuietDays

func QuietDays(r layered.Roots) (int, error)

QuietDays reads the quiet window, worktrees.quiet_days, through the layered configuration resolver: the repository's .abcd/config.json, then ~/.abcd.noindex/config.json, then DefaultQuietDays. It claims the worktrees namespace, so a misspelt key, a value below 1 or one that is not a whole number is refused naming its file, never replaced by the default.

func ValidName

func ValidName(name string) bool

ValidName reports whether name is one plain path segment that cannot escape the lane it is joined onto and cannot be read as an option: letters, digits, '.', '_' and '-', not led by '-' or '.', and holding no "..". A name a sibling store holds in the lane is not a worktree's (reserved).

Types

type AddOptions

type AddOptions struct {
	// Name is the worktree's name in the lane, one plain path segment.
	Name string
	// Branch is the short branch name; "" means Name.
	Branch string
	// Existing checks out Branch, which must already exist, and makes no
	// branch. Otherwise Branch is made, from Base, and must not exist yet.
	Existing bool
	// Base is the commit a new branch is cut from; unused with Existing.
	Base string
	// Git runs `git worktree add`. It is required.
	Git GitRunner
}

AddOptions is one worktree for Add to make.

type Added

type Added struct {
	Lane   Lane
	Path   string
	Branch string
}

Added is the worktree Add made.

func Add

func Add(repoRoot string, opts AddOptions) (Added, error)

Add makes a worktree in the lane of the repository at repoRoot: the name and branch are judged, the lane is derived and read (LaneFor), and nothing may stand at the path; only then are the lane's levels made (Ensure), git adds the worktree and its directory is narrowed to 0700. Every refusal comes before anything is written, so a refused Add writes nothing; a git that fails is a refusal whose cause is git's error (Refusal.Err).

Once git has made the worktree, Add records where its branch starts (start.go) and lays its local tier, so a reservation can keep its key there at once (iss-2610222022157889). Either failing is a refusal returned with the Added it made, since the worktree stands and git's own removal is the way back.

type AllListing

type AllListing struct {
	Store     string        `json:"store"`
	Lanes     []LaneListing `json:"lanes"`
	ForgeNote string        `json:"forge_note,omitempty"`
}

AllListing is ListAll's answer.

func ListAll

func ListAll(opts AllOptions) (AllListing, error)

ListAll walks every directory under ~/.abcd.noindex/worktrees/ without following symlinks. A directory named by a full root commit is a lane, labelled from opts.Labels; its worktrees are judged from their own checkout, found through each one's .git file. Anything else is not a lane.

type AllOptions

type AllOptions struct {
	// Labels are the registry's labels by root commit; a lane with none is
	// shown under its root commit.
	Labels map[string]Label
	// Here is the checkout the caller stands in, "" for none: a directory
	// abbreviating its root commit names its full-key lane.
	Here string
	// Forge is asked once per lane's checkout; nil asks none.
	Forge GH
}

AllOptions is how ListAll labels and judges the lanes.

type CacheTrim added in v0.16.2

type CacheTrim struct {
	// Path is the cache's directory, home-redacted and masked; "" when go named
	// none.
	Path string `json:"path,omitempty"`
	// Skipped says why nothing was looked at; "" when the cache was walked.
	Skipped string `json:"skipped,omitempty"`
	// UnusedDays is the age an entry had to pass.
	UnusedDays     int    `json:"unused_days"`
	EntriesRemoved int    `json:"entries_removed"`
	BytesFreed     uint64 `json:"bytes_freed"`
	// Failed counts the entries that could not be removed and the
	// subdirectories that could not be read.
	Failed int `json:"failed,omitempty"`
}

CacheTrim is what one trim did. Under a dry run the counts are what a real run would have removed.

func TrimGoCache added in v0.16.2

func TrimGoCache(dryRun bool, now time.Time) CacheTrim

TrimGoCache deletes the entries of the cache `go env GOCACHE` names that have gone unused for CacheTrimAge, as of now, or under a dry run only counts them. It reports rather than returns a failure: a trim never fails the prune that asked for it.

type DirtyState

type DirtyState struct {
	Modified  int      `json:"modified"`
	Untracked int      `json:"untracked"`
	Paths     []string `json:"paths"`
}

DirtyState is a candidate's uncommitted changes: counts, and the first paths.

type Dossier

type Dossier struct {
	Dirty DirtyState `json:"dirty"`
	// Commits counts the branch's commits not on the default branch, and
	// Subjects are the first of them, newest first.
	Commits  int      `json:"commits"`
	Subjects []string `json:"subjects"`
	// Diff is `git diff --shortstat` from the merge base to the tip.
	Diff string `json:"diff"`
	// Records are the record ids the subjects and changed paths cite.
	Records []string `json:"records"`
	// Ignored is what git ignores in the worktree outside the local tier: a
	// removal deletes it, and only the tier is archived.
	Ignored IgnoredState `json:"ignored"`
	// LastActivity is when the worktree was last active, in UTC.
	LastActivity   string `json:"last_activity"`
	Recommendation string `json:"recommendation"`
}

Dossier is what prune shows of a quiet candidate, dirty state first, so the person can tell what naming it would and would not remove.

type GH

type GH func(dir string, args ...string) (string, error)

GH runs the forge client with args from dir and returns its output: the front door hands the repository's own bounded runner. A failure of any kind (no client, no login, no GitHub remote, no answer in time) is no forge.

type GitRunner

type GitRunner func(dir string, args ...string) (string, error)

GitRunner runs one git command in dir and returns its output, or its failure. Add takes it from the caller, because how a checkout runs (the person's filters and hooks, its time bound) is the caller's to decide.

type Held

type Held struct {
	// Names maps a worktree's name in the lane to the run holding it.
	Names map[string]string
	// Runs are the run ids whose state could not be read.
	Runs []string
}

Held is what the build loop holds in the lane: the worktrees a run whose state is not complete names, by their name in the lane, and the runs whose state could not be read, each of which holds every worktree named after it.

func (Held) By

func (h Held) By(name string) string

By is the run holding the worktree called name, or "".

type HeldReader

type HeldReader func(repoRoot string) (Held, error)

HeldReader reads what the build loop holds for the repository at repoRoot. The loop imports this package, so it is handed in, the shape the status block's lane reader takes.

type IgnoredState

type IgnoredState struct {
	Count  int      `json:"count"`
	Paths  []string `json:"paths"`
	Unread bool     `json:"unread"`
}

IgnoredState is a candidate's ignored paths outside the local tier: the count, and the first of them (a wholly ignored directory is one path). Unread says git refused the listing, so the count says nothing.

type Label

type Label struct {
	Name string
	Path string
}

Label is a repository's entry in abcd's registry, keyed on its root commit: the name a lane is shown under. Path is the registry's label for where the checkout was, which ListAll never reads: which checkout a lane belongs to is each worktree's own .git file's answer.

type Lane

type Lane struct {
	// Home is the caller's home, the base the store is proved real from.
	Home string
	// RootSHA is the repository's root commit, the lane's key.
	RootSHA string
	// Rel is the lane, relative to Home, slash-separated: StoreRel/<RootSHA>.
	Rel string
	// Dir is the lane's absolute path, Home/Rel.
	Dir string
}

Lane is one repository's directory in the store.

func LaneFor

func LaneFor(repoRoot string) (Lane, error)

LaneFor derives the lane of the repository at repoRoot from its root commit and the caller's home. It makes nothing. A repository with no root commit is refused; git failing to answer is an error, since that is no evidence the repository has none.

func (Lane) Ensure

func (l Lane) Ensure() error

Ensure makes the lane's levels under the home one at a time, from the top down, and holds each to two tests before the next is made: it is a real directory (a symlink or a file anywhere in the chain refuses), and it is the caller's alone (fsutil.CallersAlone: owned by this uid, no group or other write bit), so no other account can replace a checkout in it. A level made here is made 0700; one that already exists keeps its mode and is judged as it stands, and nothing is made inside a level that fails. A Lane that is not the store's shape for its own root commit makes nothing.

func (Lane) Path

func (l Lane) Path(name string) string

Path is the worktree called name in the lane. It builds the path only; a caller that has not validated name with ValidName must not use it.

type LaneListing

type LaneListing struct {
	// Key is the directory's name, a root commit for a lane.
	Key string `json:"key"`
	// Label is the repository's registry name, or Key where it has none.
	Label     string `json:"label"`
	Path      string `json:"path"`
	Reason    string `json:"reason,omitempty"`
	Worktrees []Row  `json:"worktrees"`
}

LaneListing is one directory directly under the store.

type ListOptions

type ListOptions struct {
	// Forge is the forge client, asked once for the run's pull requests; nil
	// asks none, and merged is judged from git alone.
	Forge GH
}

ListOptions is how List judges the rows.

type Listing

type Listing struct {
	// Lane is the repository's lane, home-redacted.
	Lane      string `json:"lane"`
	Worktrees []Row  `json:"worktrees"`
	// ForgeNote says, once, that no forge answered and why; empty when one did
	// or there was nothing to ask about.
	ForgeNote string `json:"forge_note,omitempty"`
}

Listing is List's answer.

func List

func List(repoRoot string, opts ListOptions) (Listing, error)

List renders the repository at repoRoot's worktrees and its lane. A store level that is a symlink, another account's or writable by others is refused before anything under it is read, and an absent lane holds no rows of its own; nothing is made.

type PruneOptions

type PruneOptions struct {
	// DryRun archives and removes nothing, and reports the rows a real run
	// would.
	DryRun bool
	// Forge is asked once for the merged judgement; nil asks none.
	Forge GH
	// Held reads what the build loop holds. It is required: a run that cannot
	// tell what the loop holds removes nothing.
	Held HeldReader
	// Cwd is prune's own working directory; the worktree holding it is kept.
	Cwd string
	// Now stamps the archive entry; nil is the clock.
	Now func() time.Time
	// PreRemove is the caller's own check on a worktree prune is about to
	// remove, given its absolute path: asked last, after every refusal, the
	// merged judgement and the archive's flush, immediately before `git
	// worktree remove`. A keep keeps the worktree with reason and takes back
	// the archive entry just written for it. A dry run asks it at the same
	// point, so it reports the row a real run would. nil checks nothing more.
	PreRemove func(abs string) (keep bool, reason string)
	// QuietDays is the quiet window in days (QuietDays reads it): an
	// unmerged worktree with no activity inside it and no open pull request
	// is a quiet candidate. 0 judges no worktree quiet.
	QuietDays int
	// Yes names the quiet candidates to reclaim. Each must be in the lane, or
	// the run is refused before anything is removed; a named worktree that is
	// not a quiet candidate this run is kept, saying why.
	Yes []string
	// TrimCache trims the Go build cache (TrimGoCache) after Prune has removed
	// at least one worktree, or, under a dry run, would have. nil trims
	// nothing, and PruneOne never does: a caller walking the lane one name at
	// a time would walk the whole cache once a name.
	TrimCache func(dryRun bool, now time.Time) CacheTrim
}

PruneOptions is one prune run.

type PruneRow

type PruneRow struct {
	Name    string `json:"name"`
	Branch  string `json:"branch"`
	Path    string `json:"path"`
	Where   string `json:"where"`
	Outcome string `json:"outcome"`
	// Reason says why a kept worktree was kept.
	Reason string `json:"reason,omitempty"`
	// Notes is how much of the local tier a reclaimed worktree had archived,
	// "none" for an absent or empty tier.
	Notes string `json:"notes,omitempty"`
	// Archive names the notes entry written, home-redacted.
	Archive string `json:"archive,omitempty"`
	// Dossier is what a quiet candidate holds, so a person can choose to
	// name it.
	Dossier *Dossier `json:"dossier,omitempty"`
}

PruneRow is one worktree's outcome.

type Pruned

type Pruned struct {
	Lane      string     `json:"lane"`
	DryRun    bool       `json:"dry_run"`
	Rows      []PruneRow `json:"rows"`
	ForgeNote string     `json:"forge_note,omitempty"`
	// CacheTrim is what the Go build cache's trim did; nil when none was asked
	// for or no worktree was removed.
	CacheTrim *CacheTrim `json:"cache_trim,omitempty"`
}

Pruned is Prune's answer.

func Prune

func Prune(repoRoot string, opts PruneOptions) (Pruned, error)

Prune reclaims the merged, clean worktrees of the repository at repoRoot's lane. A store refusal (a symlinked level, one another account owns or others can write) is returned before anything is judged, and so is a failure to read what the build loop holds; otherwise every worktree is a row. After it removes a worktree it trims the Go build cache, if opts asks; what the trim finds is reported and never fails the run.

func PruneOne

func PruneOne(repoRoot, name string, opts PruneOptions) (Pruned, error)

PruneOne is Prune for the one worktree called name in the repository's lane: the same proof, refusals, judgement, archive and removal, its answer the one row. A name the lane does not hold, a worktree outside the store among them, is refused before anything is archived or removed. Only that worktree is judged, so a caller walking the lane one name at a time does not judge every worktree once a call.

func (Pruned) Reclaimed

func (p Pruned) Reclaimed() int

Reclaimed counts the rows reclaimed, or that a dry run would reclaim.

type Refusal

type Refusal struct {
	Reason string
	Remedy string
	Err    error
}

Refusal is the store declining an operation for a reason the caller can act on. Reason and Remedy are home-redacted. The remedy names the act that clears the reason and not how to retry, which is the caller's to say. Err, when set, is the failure underneath (git's), which Unwrap hands on.

func (*Refusal) Error

func (r *Refusal) Error() string

func (*Refusal) Unwrap

func (r *Refusal) Unwrap() error

Unwrap is the failure underneath the refusal, if any.

type Row

type Row struct {
	Name   string `json:"name"`
	Branch string `json:"branch"`
	Path   string `json:"path"`
	Where  string `json:"where"`
	// State is clean or dirty, Merged merged or unmerged, and JudgedBy how a
	// merged branch was judged (forge, ancestry, content); all three are empty
	// when Reason says why the row is not judged.
	State    string `json:"state,omitempty"`
	Merged   string `json:"merged,omitempty"`
	JudgedBy string `json:"judged_by,omitempty"`
	// Locked and Prunable are git's attributes, with git's reasons.
	Locked         bool   `json:"locked,omitempty"`
	LockReason     string `json:"lock_reason,omitempty"`
	Prunable       bool   `json:"prunable,omitempty"`
	PrunableReason string `json:"prunable_reason,omitempty"`
	Reason         string `json:"reason,omitempty"`
	// Abs is the worktree's absolute path, as git or the lane names it, for a
	// caller that acts on the row. It is never output: Path is the form that
	// may be shown, so a home path never reaches a terminal or the JSON.
	Abs string `json:"-"`
}

Row is one worktree, or one directory in the store, as list renders it.

Jump to

Keyboard shortcuts

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