worktree

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package worktree manages Git worktrees and Jujutsu workspaces for XenForo development environments.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidBranch indicates a branch name that cannot be used.
	ErrInvalidBranch = errors.New("invalid branch name")

	// ErrBranchExists indicates the branch is already present.
	ErrBranchExists = errors.New("branch already exists")

	// ErrWorktreeExists indicates the target directory is already in use.
	ErrWorktreeExists = errors.New("worktree already exists")

	// ErrNotXenForo indicates the source is not a XenForo installation.
	ErrNotXenForo = errors.New("not a XenForo directory")
)
View Source
var (
	// ErrDirtyWorktree indicates uncommitted changes would be lost.
	ErrDirtyWorktree = errors.New("worktree has uncommitted changes")

	// ErrUnmergedCommits indicates commits exist only in this worktree.
	ErrUnmergedCommits = errors.New("worktree has commits not present on any remote")
)
View Source
var ErrNotADirectory = errors.New("not a directory")

ErrNotADirectory indicates a copy source exists but is not a directory.

View Source
var ErrNotARepository = errors.New("not a git or Jujutsu repository")

ErrNotARepository indicates a path is not inside a supported repository.

View Source
var ErrRegistryCorrupt = errors.New("worktree registry is corrupt")

ErrRegistryCorrupt indicates the registry file exists but cannot be parsed.

Mutating calls tolerate this and rebuild from an empty registry, so a damaged file never blocks cleanup. Read failures are not tolerated: they mean the existing entries are unknown rather than absent.

Functions

func BranchToDirName

func BranchToDirName(branch string) string

BranchToDirName converts a branch name into a single, safe path segment.

Only the last segment is used, so dev/xfs/slack-unfurl becomes slack-unfurl. The prefix in a conventional branch name describes where the work belongs rather than what it is, and repeating it in directory names, URLs and Docker instance names makes all three harder to read.

The result is always a single segment: it can never contain a separator or resolve to a parent directory, whatever the branch name contains.

This is deliberately lossy. dev/xfs/slack-unfurl and dev/xf/slack-unfurl both yield slack-unfurl, so callers must check whether the directory is already taken. Preflight rejects a collision rather than renaming around it, which keeps the branch-to-path mapping computable without consulting any state.

func CheckRemovable

func CheckRemovable(ctx context.Context, worktreePath string) error

CheckRemovable reports whether a worktree can be removed without losing work.

It is separate from Remove so callers can run the check before destroying anything the removal depends on. Tearing down containers and volumes first and only then discovering that the worktree is dirty would refuse the removal after the data it was protecting had already been deleted.

func CopyTree

func CopyTree(ctx context.Context, src, dst string, progress ProgressFunc) error

CopyTree recursively copies src to dst, preserving file modes.

A missing source is not an error: a XenForo installation may legitimately have no data/ or internal_data/ yet.

This is implemented natively rather than by shelling out to rsync. macOS no longer ships GNU rsync — /usr/bin/rsync is openrsync, which lacks the progress options — and Windows has no rsync at all, so an external tool would behave differently depending on the machine.

func CurrentBranch

func CurrentBranch(ctx context.Context, repoDir string) (string, error)

CurrentBranch returns the branch checked out in repoDir.

For a Jujutsu repository this returns the workspace name.

func InstanceName

func InstanceName(sourcePath, branch string) string

InstanceName derives the Docker Compose project name for a worktree.

It combines a readable prefix taken from the branch's final segment with a short digest of the canonical source checkout and the full branch name. The branch-to-directory mapping is lossy - dev/24x/feature and dev/xfs/feature both reduce to "feature" - so without the digest those worktrees would also share a Compose project, and stopping or destroying one would affect the other. Mixing in the source path keeps checkouts that happen to use the same branch names apart as well.

The digest is computed from the symlink-resolved source so that the name is stable whether the checkout is reached through a symlinked path or not.

func RegistryPath

func RegistryPath() (string, error)

RegistryPath returns where the registry is stored, so callers can name the file when telling the user how to deal with a damaged one.

func Remove

func Remove(ctx context.Context, sourcePath, worktreePath string, force bool) error

Remove deletes a worktree and its branch.

Unless force is set, it refuses when the worktree holds uncommitted changes or commits that exist nowhere else, listing what would be lost. Removing containers and volumes is the caller's responsibility.

func ResolveExistingPath

func ResolveExistingPath(sourcePath, branch string) (string, error)

ResolveExistingPath is ResolvePath for branch names that came from the user.

BranchToDirName yields an empty name for inputs such as "." or "..", which would resolve to the directory holding every worktree for the checkout. A command acting on that path would operate on all of them at once, so those inputs are rejected rather than resolved.

func ResolvePath

func ResolvePath(sourcePath, branch string) string

ResolvePath returns the worktree path for a branch of the given checkout.

The result depends only on its arguments, so any tool can predict it without consulting the registry or git.

func SourceCheckout

func SourceCheckout(ctx context.Context, dir string) (string, error)

SourceCheckout returns the main checkout for the repository containing dir.

When dir is inside a linked worktree or workspace this returns the *original* checkout, not the linked one. That keeps new checkouts siblings of the source rather than nesting them, so running the command from within one behaves the same as running it from the source.

func WorktreesDir

func WorktreesDir(sourcePath string) string

WorktreesDir returns the directory holding the worktrees for a checkout.

Worktrees are siblings of the source checkout, so ~/Sites/main yields ~/Sites/main.worktrees. This keeps them on the same filesystem as the source, which matters for Docker bind mounts, and makes them discoverable without knowing an xf-specific convention.

Types

type Entry

type Entry struct {
	// SourcePath is the checkout the worktree was created from.
	SourcePath string `json:"source_path"`

	// SourceBranch is the branch the source was on at creation time.
	SourceBranch string `json:"source_branch"`

	// WorktreePath is the resolved location of the worktree.
	WorktreePath string `json:"worktree_path"`

	// Branch is the branch checked out in the worktree.
	Branch string `json:"branch"`

	// Instance is the Docker instance name for the worktree.
	Instance string `json:"instance"`

	// Cloned records whether the environment was cloned from the source.
	Cloned bool `json:"cloned"`

	// CreatedAt is when the worktree was created.
	CreatedAt time.Time `json:"created_at"`
}

Entry records a worktree created by xf.

type Options

type Options struct {
	// SourcePath is the checkout to branch from.
	SourcePath string

	// Branch is the branch (Git) or workspace (Jujutsu) to create in the new
	// checkout. It also names the new directory.
	Branch string

	// Base is the revision to base the new checkout on, interpreted with the
	// selected backend's revision syntax. Defaults to the source's current HEAD.
	Base string

	// Instance overrides the derived Docker instance name.
	Instance string
}

Options describes a worktree to create.

type ProgressFunc

type ProgressFunc func(copied, total int)

ProgressFunc reports copy progress as files are written.

type Registry

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

Registry is the on-disk record of worktrees xf has created.

It exists so that worktrees can be listed across projects, which git alone cannot do. It is deliberately *not* the source of truth: git and Docker are. Worktrees can be removed behind xf's back, so callers must reconcile entries against reality rather than trusting the file.

A missing registry reads as empty, and the operations that rewrite it -- Add and Remove -- recover from a damaged one by replacing it, so creating and removing worktrees never fail on registry damage. Reading is the exception: All reports a corrupt file rather than silently presenting an empty list, because "no worktrees" and "the record is unreadable" call for different responses from the user. Listing and pruning therefore surface the error and say what to do about it.

func NewRegistry

func NewRegistry() (*Registry, error)

NewRegistry opens the registry in the user's configuration directory.

func (*Registry) Add

func (r *Registry) Add(entry Entry) error

Add records a worktree, replacing any existing entry for the same path.

func (*Registry) All

func (r *Registry) All() ([]Entry, error)

All returns every recorded entry.

A missing registry returns no entries and no error.

func (*Registry) ForSource

func (r *Registry) ForSource(sourcePath string) ([]Entry, error)

ForSource returns the entries belonging to a single checkout.

func (*Registry) Remove

func (r *Registry) Remove(worktreePath string) error

Remove drops the entry for a worktree path. Removing an absent entry is not an error, so cleanup is idempotent.

type Result

type Result struct {
	// Path is the worktree location.
	Path string

	// Branch is the branch checked out in the worktree.
	Branch string

	// SourcePath is the checkout it was created from.
	SourcePath string

	// SourceBranch is the branch the source was on at creation time.
	SourceBranch string

	// Instance is the Docker instance name for the worktree.
	Instance string

	// CreatedAt is when the worktree was created.
	CreatedAt time.Time
}

Result describes a created worktree.

func Create

func Create(ctx context.Context, opts Options) (*Result, error)

Create makes a worktree on a new branch.

It does not configure Docker or install anything; that is the caller's job. Pre-flight runs first, so a failure here leaves the source checkout untouched.

type WorktreeStatus

type WorktreeStatus struct {
	// Modified lists paths with uncommitted changes, including untracked files.
	Modified []string

	// UnmergedCommits lists commits not reachable from any remote branch.
	UnmergedCommits []string
}

WorktreeStatus describes the state of a worktree's working tree and branch.

Jump to

Keyboard shortcuts

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