cache

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Jan 24, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package cache manages persistent storage for worktree IDs and PR information.

The cache is stored in .wt-cache.json in the worktree directory and provides:

  • Stable worktree IDs: Each worktree gets a unique numeric ID that persists across sessions, enabling commands like "wt exec -i 5" to work reliably.

  • PR info caching: Stores fetched PR metadata (state, author, comments, etc.) to avoid repeated API calls. Cache entries expire after 24 hours.

  • Worktree metadata: Stores path, branch, repo path, and origin URL for each worktree to enable repair and recovery operations.

Cache Structure

The cache uses folder names as keys (e.g., "repo-feature-branch") since they're unique within a worktree directory and human-readable:

{
  "worktrees": {
    "repo-feature-branch": {
      "id": 1,
      "path": "/path/to/repo-feature-branch",
      "repo_path": "/path/to/repo",
      "branch": "feature-branch",
      "origin_url": "git@github.com:user/repo.git",
      "pr": { ... }
    }
  },
  "next_id": 2
}

Concurrency

Use LoadWithLock for operations that modify the cache to prevent corruption from concurrent access. The lock uses a .wt-cache.lock file.

Entry Lifecycle

Entries are never deleted, only marked as removed via RemovedAt timestamp. This preserves ID history and enables the doctor command to detect issues. Use Cache.SyncWorktrees to update the cache with current disk state.

The "wt doctor" command diagnoses and repairs cache issues including: stale entries, path mismatches, missing metadata, and duplicate IDs.

Index

Constants

View Source
const CacheMaxAge = 24 * time.Hour

CacheMaxAge is the maximum age of cached PR info before it's considered stale

Variables

This section is empty.

Functions

func CachePath added in v0.4.0

func CachePath(dir string) string

CachePath returns the path to the cache file for a directory

func LockPath added in v0.4.0

func LockPath(dir string) string

LockPath returns the path to the lock file for a directory

func MakeWorktreeKey added in v0.4.0

func MakeWorktreeKey(path string) string

MakeWorktreeKey creates a cache key from worktree path (folder name). The folder name is unique within a worktree_dir and human-readable.

func MarkRemovedByKey added in v0.4.0

func MarkRemovedByKey(c *Cache, key string)

MarkRemovedByKey is a package-level function for marking an entry as removed. Used by doctor command for fixing cache issues.

func Save added in v0.4.0

func Save(scanDir string, cache *Cache) error

Save saves the unified cache to disk atomically

Types

type Cache added in v0.4.0

type Cache struct {
	PRs       PRCache                     `json:"prs,omitempty"`
	Worktrees map[string]*WorktreeIDEntry `json:"worktrees,omitempty"` // key: folder name (e.g., "repo-feature-branch")
	NextID    int                         `json:"next_id,omitempty"`
}

Cache is the unified cache structure stored in .wt-cache.json

func Load added in v0.4.0

func Load(scanDir string) (*Cache, error)

Load loads the unified cache from disk

func LoadWithLock added in v0.4.0

func LoadWithLock(dir string) (*Cache, func(), error)

LoadWithLock acquires a lock and loads the cache. Returns cache, unlock function, and error. Caller must defer unlock() if err == nil.

func (*Cache) GetBranchByID added in v0.4.0

func (c *Cache) GetBranchByID(id int) (branch string, path string, found bool, removed bool)

GetBranchByID looks up a worktree by its ID and returns the branch name Returns branch, path, found, and whether it was marked as removed

func (*Cache) GetBranchByPRNumber added in v0.4.0

func (c *Cache) GetBranchByPRNumber(originURL string, prNumber int) string

GetBranchByPRNumber looks up PR info by PR number for a given origin URL Returns the branch name if found and cache is not stale, empty string otherwise

func (*Cache) GetByID added in v0.4.0

func (c *Cache) GetByID(id int) (path string, found bool, removed bool)

GetByID looks up a worktree by its ID Returns path, found, and whether it was marked as removed

func (*Cache) GetOrAssignID added in v0.4.0

func (c *Cache) GetOrAssignID(info WorktreeInfo) int

GetOrAssignID returns the existing ID for a worktree or assigns a new one. Uses folder name as key, stores rich metadata for repair/recovery.

func (*Cache) GetPRByOriginAndBranch added in v0.4.0

func (c *Cache) GetPRByOriginAndBranch(originURL, branch string) *PRInfo

GetPRByOriginAndBranch returns the cached PR for a given origin URL and branch. Searches through all entries to find a match. Returns nil if not found. This is used for backwards compatibility in cases where folder name isn't available.

func (*Cache) GetPRForBranch added in v0.4.0

func (c *Cache) GetPRForBranch(folderName string) *PRInfo

GetPRForBranch returns the cached PR for a worktree by folder name. Returns nil if not found or not fetched.

func (*Cache) MarkRemoved added in v0.4.0

func (c *Cache) MarkRemoved(folderName string)

MarkRemoved sets the RemovedAt timestamp for a worktree entry by folder name. Call this immediately after successfully removing a worktree.

func (*Cache) Reset added in v0.4.0

func (c *Cache) Reset()

Reset clears all cached data and resets NextID to 1. Active worktrees will get new IDs on next sync.

func (*Cache) SetPRByOriginAndBranch added in v0.4.0

func (c *Cache) SetPRByOriginAndBranch(originURL, branch string, pr *PRInfo)

SetPRByOriginAndBranch stores PR info by origin URL and branch. Searches through all entries to find a match. This is used for backwards compatibility in cases where folder name isn't available.

func (*Cache) SetPRForBranch added in v0.4.0

func (c *Cache) SetPRForBranch(folderName string, pr *PRInfo)

SetPRForBranch stores PR info for a worktree by folder name. Updates the entry if it exists; does nothing if the entry doesn't exist.

func (*Cache) SyncWorktrees added in v0.4.0

func (c *Cache) SyncWorktrees(worktrees []WorktreeInfo) map[string]int

SyncWorktrees updates the cache with current worktrees Returns a map of path -> ID for display Note: entries are never deleted, only marked as removed for history

type FileLock

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

FileLock provides exclusive file-based locking using flock.

func NewFileLock

func NewFileLock(path string) *FileLock

NewFileLock creates a new file lock for the given path. The lock file will be created if it doesn't exist.

func (*FileLock) Lock

func (l *FileLock) Lock() error

Lock acquires an exclusive lock on the file. Blocks until the lock is acquired.

func (*FileLock) Unlock

func (l *FileLock) Unlock() error

Unlock releases the lock and closes the file.

type PRCache added in v0.4.0

type PRCache map[string]map[string]*PRInfo

PRCache maps origin URL -> branch -> PR info (legacy format)

type PRInfo added in v0.4.0

type PRInfo struct {
	Number       int       `json:"number"`
	State        string    `json:"state"`    // Normalized: OPEN, MERGED, CLOSED
	IsDraft      bool      `json:"is_draft"` // true if PR is a draft
	URL          string    `json:"url"`
	Author       string    `json:"author"`        // username/login
	CommentCount int       `json:"comment_count"` // number of comments
	HasReviews   bool      `json:"has_reviews"`   // any reviews submitted
	IsApproved   bool      `json:"is_approved"`   // approved status
	CachedAt     time.Time `json:"cached_at"`
	Fetched      bool      `json:"fetched"` // true = API was queried (distinguishes "not fetched" from "no PR")
}

PRInfo represents pull request information

func (*PRInfo) IsStale added in v0.4.0

func (m *PRInfo) IsStale() bool

IsStale returns true if the cache entry is older than CacheMaxAge

type WorktreeIDEntry added in v0.4.0

type WorktreeIDEntry struct {
	ID        int        `json:"id"`
	Path      string     `json:"path"`
	RepoPath  string     `json:"repo_path,omitempty"`  // main repo path for repair
	Branch    string     `json:"branch,omitempty"`     // branch name for repair
	OriginURL string     `json:"origin_url,omitempty"` // origin URL (may be empty for local-only repos)
	RemovedAt *time.Time `json:"removed_at,omitempty"` // nil if still exists
	PR        *PRInfo    `json:"pr,omitempty"`         // embedded PR info
}

WorktreeIDEntry stores the ID for a worktree with rich metadata for repair

type WorktreeInfo added in v0.4.0

type WorktreeInfo struct {
	Path      string // worktree path (required)
	RepoPath  string // main repo path
	Branch    string // branch name
	OriginURL string // origin URL (may be empty for local-only repos)
}

WorktreeInfo contains the info needed to sync the cache. Path is required; other fields are stored as metadata for repair/recovery.

Jump to

Keyboard shortcuts

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