Help us shape the future of Go! Take the 2026 Go Developer Survey

worktree

package
v0.30.1 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package worktree provides actions for managing stackit-managed worktrees.

Index

Constants

View Source
const (
	RemovalRespectChanges = worktreeutil.RemovalRespectChanges
	RemovalDiscardChanges = worktreeutil.RemovalDiscardChanges
)
View Source
const WorktreeIncludeFile = ".worktreeinclude"

WorktreeIncludeFile is the repository-root file that selects ignored files which may be copied into a newly-created worktree. Its patterns use .gitignore syntax, but a match alone is insufficient: callers must pass only files already known to be ignored by Git.

Variables

This section is empty.

Functions

func DetachAction

func DetachAction(ctx context.Context, deps Deps, opts DetachOptions) error

DetachAction removes a worktree while preserving all branches.

func OwnershipWarnings added in v0.25.0

func OwnershipWarnings(ctx context.Context, eng OwnershipWarningsEngine) []string

OwnershipWarnings reports branches whose physical checkout location does not match the worktree that owns their stack. Exported so commands that mutate across the whole repository — sync in particular — can surface divergence at the time it matters, not only when someone happens to run `worktree list`.

func RemoveAction

func RemoveAction(ctx context.Context, deps Deps, opts RemoveOptions) error

RemoveAction removes a worktree for a stack

func ResolveApprovedHooks

func ResolveApprovedHooks(deps Deps) ([]string, error)

ResolveApprovedHooks reads the post-worktree-create hook list from the project config in deps.Config and returns the approved subset, prompting for any unapproved entries. Must be called from the main thread (may prompt interactively).

func RunPostCreateHooks

func RunPostCreateHooks(ctx context.Context, deps Deps, worktreePath WorktreePath) error

RunPostCreateHooks runs any configured post-worktree-create hooks. It reads the project config from deps.Config, resolves approvals, and executes approved hooks in the worktree directory.

func RunResolvedHooks

func RunResolvedHooks(ctx context.Context, hookCmds []string, worktreePath WorktreePath, out output.Output)

RunResolvedHooks executes a pre-resolved list of hooks in the given directory. Failures are warned, not blocking — matches the existing worktree behavior.

The caller's context is honored so Ctrl-C interrupts a hook instead of waiting out its timeout. An empty worktreePath is refused rather than passed through: os/exec treats an empty Dir as the current directory, which for these hooks is the user's main checkout — the one place they must never run.

Types

type AttachOptions

type AttachOptions struct {
	Branch string // Any branch in the stack (we find the stack root)
	Name   string // Optional worktree name (defaults to stack root name)
}

AttachOptions contains options for the attach action.

type BranchWorktrees added in v0.30.1

type BranchWorktrees struct{ Deps Deps }

BranchWorktrees backs create --worktree: it satisfies create.Worktrees with CreateAnchoredWorktreeForBranch and RunPostCreateHooks over Deps.

func (BranchWorktrees) CreateAnchored added in v0.30.1

func (w BranchWorktrees) CreateAnchored(ctx context.Context, branchName, name, scope string) (WorktreePath, error)

CreateAnchored creates a managed worktree anchored on branchName and returns its path.

func (BranchWorktrees) RunPostCreateHooks added in v0.30.1

func (w BranchWorktrees) RunPostCreateHooks(ctx context.Context, path WorktreePath) error

RunPostCreateHooks runs the configured post-worktree-create hooks in path.

type ChildRestoreMode added in v0.28.0

type ChildRestoreMode int

ChildRestoreMode controls whether rollback also reparents children back to the worktree's anchor branch. Remove never reparents children (they stay on the anchor), so it always skips this step; detach reparents them away from the anchor before deleting it, so it must restore them on failure.

const (
	SkipChildRestore ChildRestoreMode = iota
	RestoreChildren
)

type CreateOptions

type CreateOptions struct {
	Name  string // User-provided name for the worktree
	Scope string // Optional scope to set on the anchor branch
	// Config is the main repository's resolved configuration. Worktrees are
	// always created from the main repository, so when the command runs inside
	// a managed worktree the caller resolves the main repository's config.
	// Nil falls back to Deps.Config.
	Config RepoConfig
}

CreateOptions contains options for the create action

type Deps added in v0.30.1

type Deps struct {
	// Engine is the full engine. Worktree lifecycle spans registrations, branch
	// creation and deletion, metadata, reparenting, and physical checkouts, and
	// CreateAction swaps in a freshly built main-repository engine of the same
	// type, so a narrow interface would restate most of engine.Engine.
	Engine engine.Engine
	Out    output.Output
	// Log is handed to the git runner of the main-repository engine CreateAction
	// builds when invoked from inside a managed worktree.
	Log      output.Logger
	RepoRoot string
	// Here is where the command runs: the main repository or a managed worktree.
	Here actions.Here
	// Config is the repository configuration already loaded at bootstrap. Nil
	// means none was loaded. Lifecycle actions read resolved values from it and
	// post-create hooks use it as their approval store.
	Config config.Configurer
	// Prompts asks the user to approve unseen post-worktree-create hooks.
	Prompts handler.Prompter
}

Deps are the collaborators the worktree lifecycle actions need. Adapters build them from their own runtime state; the actions never see bootstrap types.

type DetachOptions

type DetachOptions struct {
	Selector WorktreeSelector // Worktree name or anchor branch
	Policy   RemovalPolicy    // Whether detach may discard uncommitted changes
}

DetachOptions contains options for the detach action.

type Entry

type Entry struct {
	Name          engine.WorktreeName `json:"name"`          // User-provided name
	AnchorBranch  string              `json:"anchor_branch"` // Registered anchor branch name
	Path          WorktreePath        `json:"path"`
	StackSize     int                 `json:"stack_size"`               // Number of real branches in the stack
	CurrentBranch string              `json:"current_branch,omitempty"` // Branch currently checked out in this worktree
	RootBranches  []string            `json:"root_branches,omitempty"`  // Real stack roots visible to the user
	Lifecycle     WorktreeLifecycle   `json:"lifecycle"`
	StatusMessage string              `json:"status_message,omitempty"` // Human-readable summary of current state
	// contains filtered or unexported fields
}

Entry represents a single managed worktree

func (Entry) MarshalJSON added in v0.25.0

func (e Entry) MarshalJSON() ([]byte, error)

MarshalJSON preserves the established flat lifecycle fields while exposing the typed lifecycle object to newer clients. The compatibility projection can be removed only in a deliberately versioned output change.

type LifecycleCapability added in v0.25.0

type LifecycleCapability string

LifecycleCapability describes whether a lifecycle operation is structurally available. Uncommitted changes are deliberately not represented here: their handling is an explicit RemovalPolicy chosen by the caller.

const (
	LifecycleAllowed     LifecycleCapability = "allowed"
	LifecycleNeedsRepair LifecycleCapability = "needs_repair"
	LifecycleCurrent     LifecycleCapability = "current"
	LifecycleHasBranches LifecycleCapability = "has_branches"
)

type ListOptions

type ListOptions struct {
	Selector WorktreeSelector
}

ListOptions contains options for the list action

type ListResult

type ListResult struct {
	Worktrees     []Entry
	CurrentAnchor string // Anchor branch of the worktree we're currently in (if any)
	// OwnershipWarnings report branches whose physical checkout location does
	// not agree with Stackit's derived ownership model. They are warnings so
	// `worktree list` remains useful for diagnosing a damaged repository.
	OwnershipWarnings []string `json:"ownership_warnings,omitempty"`
}

ListResult contains the results of listing worktrees

func ListAction

func ListAction(ctx context.Context, deps Deps, opts ListOptions) (*ListResult, error)

ListAction lists all managed worktrees

type OpenOptions

type OpenOptions struct {
	Selector WorktreeSelector // Worktree name or anchor branch
}

OpenOptions contains options for the open action

type OwnershipWarningsEngine added in v0.30.1

type OwnershipWarningsEngine interface {
	ListWorktrees(ctx context.Context) (git.WorktreeList, error)
	OwningWorktree(ctx context.Context, branch engine.Branch) (*engine.WorktreeInfo, error)
	GetBranch(name string) engine.Branch
}

OwnershipWarningsEngine is the engine surface ownership warnings read.

type PruneOptions

type PruneOptions struct {
	DryRun bool // If true, only show what would be pruned
}

PruneOptions contains options for the prune action.

type PruneResult

type PruneResult struct {
	Pruned  []string       // Names of pruned worktrees
	Skipped []SkippedEntry // Worktrees that were skipped and why
}

PruneResult contains the results of pruning worktrees.

func PruneAction

func PruneAction(ctx context.Context, deps Deps, opts PruneOptions) (*PruneResult, error)

PruneAction removes all empty worktrees.

type RegistrationState added in v0.18.0

type RegistrationState string
const (
	RegistrationStateOK      RegistrationState = "ok"
	RegistrationStateLegacy  RegistrationState = "legacy"
	RegistrationStateInvalid RegistrationState = "invalid"
)

type RemovalPolicy added in v0.25.0

type RemovalPolicy = worktreeutil.RemovalPolicy

RemovalPolicy makes destructive worktree operations explicit at the action boundary while sharing the low-level path-removal policy.

func RemovalPolicyForForce added in v0.25.0

func RemovalPolicyForForce(force bool) RemovalPolicy

RemovalPolicyForForce converts the CLI's --force flag at the boundary where it is parsed; lifecycle code only receives an explicit policy.

type RemoveOptions

type RemoveOptions struct {
	Selector WorktreeSelector // Worktree name or anchor branch
	Policy   RemovalPolicy    // Whether removal may discard uncommitted changes
}

RemoveOptions contains options for the remove action

type RepairEntry added in v0.18.0

type RepairEntry struct {
	Name         string `json:"name"`
	Action       string `json:"action"`
	AnchorBranch string `json:"anchor_branch,omitempty"`
}

type RepairOptions added in v0.18.0

type RepairOptions struct {
	Selector WorktreeSelector
	// Config is the main repository's resolved configuration, used to name
	// anchors for legacy registrations. Nil falls back to Deps.Config.
	Config RepoConfig
}

type RepairResult added in v0.18.0

type RepairResult struct {
	Repaired []RepairEntry  `json:"repaired"`
	Skipped  []SkippedEntry `json:"skipped,omitempty"`
}

func RepairAction added in v0.18.0

func RepairAction(ctx context.Context, deps Deps, opts RepairOptions) (*RepairResult, error)

type RepoConfig added in v0.29.0

type RepoConfig interface {
	Trunk() string
	UndoStackDepth() int
	LinearStacks() bool
	WorktreeBasePath() string
	BranchNamePattern() string
}

RepoConfig is the resolved repository configuration worktree lifecycle actions read. The loaded repository config satisfies it; actions never load config from disk themselves.

type SkippedEntry

type SkippedEntry struct {
	Name   string
	Reason string
}

SkippedEntry represents a worktree that was skipped during pruning.

type WarmStartResult added in v0.25.0

type WarmStartResult struct {
	Enabled         bool
	Copied          []string
	SkippedExisting []string
	// SkippedUnsafe lists files that could not be placed because something on
	// their path is not a plain directory — most often a tracked file on trunk
	// occupying a name the include file also selects as a directory.
	SkippedUnsafe []WarmStartSkip
}

WarmStartResult describes files copied into a new worktree. Paths are relative to the source worktree and sorted for deterministic output.

func CopyIncludedIgnoredFiles added in v0.25.0

func CopyIncludedIgnoredFiles(sourceRoot, destinationRoot string, ignoredPaths []string) (WarmStartResult, error)

CopyIncludedIgnoredFiles copies selected ignored regular files from sourceRoot to destinationRoot. ignoredPaths must be repository-relative paths that Git has already classified as ignored; this function deliberately does not infer ignore state from .worktreeinclude itself.

Existing destination files are never overwritten. Symlinks and non-regular files are skipped so a project-controlled include file cannot cause Stackit to follow a path outside either worktree.

type WarmStartSkip added in v0.25.0

type WarmStartSkip struct {
	Path   string
	Reason string
}

WarmStartSkip records one file warm start declined to copy, and why.

type WorktreeChanges added in v0.25.0

type WorktreeChanges string

WorktreeChanges describes the inspected state of the worktree directory.

const (
	WorktreeChangesClean WorktreeChanges = "clean"
	WorktreeChangesDirty WorktreeChanges = "dirty"
)

type WorktreeCheckout added in v0.25.0

type WorktreeCheckout string

WorktreeCheckout describes whether a managed worktree is the current one.

const (
	WorktreeCheckoutElsewhere WorktreeCheckout = "elsewhere"
	WorktreeCheckoutCurrent   WorktreeCheckout = "current"
)

type WorktreeLifecycle added in v0.25.0

type WorktreeLifecycle struct {
	Registration RegistrationState   `json:"registration_state"`
	Presence     WorktreePresence    `json:"presence"`
	Checkout     WorktreeCheckout    `json:"checkout"`
	Changes      WorktreeChanges     `json:"changes"`
	Remove       LifecycleCapability `json:"remove"`
	Detach       LifecycleCapability `json:"detach"`
}

WorktreeLifecycle is the inspected lifecycle state of a managed worktree. Keeping these dimensions typed makes a worktree's mutability explicit without requiring callers to infer it from a combination of booleans.

func (WorktreeLifecycle) CanDetach added in v0.25.0

func (l WorktreeLifecycle) CanDetach() bool

func (WorktreeLifecycle) CanRemove added in v0.25.0

func (l WorktreeLifecycle) CanRemove() bool

func (WorktreeLifecycle) Exists added in v0.25.0

func (l WorktreeLifecycle) Exists() bool

func (WorktreeLifecycle) IsCurrent added in v0.25.0

func (l WorktreeLifecycle) IsCurrent() bool

func (WorktreeLifecycle) IsDirty added in v0.25.0

func (l WorktreeLifecycle) IsDirty() bool

func (WorktreeLifecycle) NeedsRepair added in v0.25.0

func (l WorktreeLifecycle) NeedsRepair() bool

type WorktreePath added in v0.25.0

type WorktreePath = engine.WorktreePath

WorktreePath is the engine-level identity of a managed checkout.

func OpenAction

func OpenAction(ctx context.Context, deps Deps, opts OpenOptions) (WorktreePath, error)

OpenAction returns the path to a worktree for a stack

type WorktreePresence added in v0.25.0

type WorktreePresence string

WorktreePresence describes whether the registered directory still exists.

const (
	WorktreePresent WorktreePresence = "present"
	WorktreeMissing WorktreePresence = "missing"
)

type WorktreeResult added in v0.25.0

type WorktreeResult struct {
	Name         string       // The name of the worktree
	AnchorBranch string       // The name of the anchor branch
	Path         WorktreePath // The path to the worktree
}

WorktreeResult describes a created or attached managed worktree.

func AttachAction

func AttachAction(ctx context.Context, deps Deps, opts AttachOptions) (*WorktreeResult, error)

AttachAction creates a worktree for an existing stack.

func CreateAction

func CreateAction(ctx context.Context, deps Deps, opts CreateOptions) (*WorktreeResult, error)

CreateAction creates a new worktree with an anchor branch

func CreateAnchoredWorktreeForBranch added in v0.18.0

func CreateAnchoredWorktreeForBranch(ctx context.Context, deps Deps, branchName string, name string, scope string) (*WorktreeResult, error)

CreateAnchoredWorktreeForBranch creates a hidden anchor for branchName, moves branchName under it without rebasing, and opens a worktree checked out on branchName.

type WorktreeSelector added in v0.25.0

type WorktreeSelector string

WorktreeSelector identifies a managed worktree by either its display name or hidden anchor branch. It keeps user-facing selectors distinct from branch names used for stack graph operations.

func (WorktreeSelector) String added in v0.25.0

func (s WorktreeSelector) String() string

Jump to

Keyboard shortcuts

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