services

package
v1.37.0 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultCICacheTTL = 30 * time.Second

DefaultCICacheTTL is the default time-to-live for CI cache entries.

View Source
const GitWatchDebounce = 600 * time.Millisecond

GitWatchDebounce is the debounce window for watcher events.

Variables

This section is empty.

Functions

func BuildCommandEnv

func BuildCommandEnv(branch, wtPath, repoKey, mainWorktreePath string) map[string]string

BuildCommandEnv builds environment variables for worktree commands.

func CompressStatusTree

func CompressStatusTree(node *StatusTreeNode)

CompressStatusTree squashes single-child directory chains (e.g., a/b/c becomes one node).

func EditorCommand

func EditorCommand(cfg *config.AppConfig) string

EditorCommand determines the editor command to use.

func EnvMapToList

func EnvMapToList(env map[string]string) []string

EnvMapToList converts environment variables to KEY=VALUE pairs.

func ExpandWithEnv

func ExpandWithEnv(input string, env map[string]string) string

ExpandWithEnv expands environment variables using the provided map first.

func LoadAccessHistory

func LoadAccessHistory(repoKey, worktreeDir string) (map[string]int64, error)

LoadAccessHistory loads access history from file.

func LoadCache

func LoadCache(repoKey, worktreeDir string) ([]*models.WorktreeInfo, error)

LoadCache loads worktree data from the cache file.

func LoadCommandHistory

func LoadCommandHistory(repoKey, worktreeDir string) ([]string, error)

LoadCommandHistory loads command history from file.

func LoadWorktreeNotes added in v1.35.0

func LoadWorktreeNotes(repoKey, worktreeDir, worktreeNotesPath string) (map[string]models.WorktreeNote, error)

LoadWorktreeNotes loads worktree notes from file.

func MigrateRepoNotesToSharedFile added in v1.37.0

func MigrateRepoNotesToSharedFile(repoKey, worktreeDir, worktreeNotesPath string) (int, error)

MigrateRepoNotesToSharedFile moves per-repo worktree notes into the shared notes file when worktreeNotesPath is configured. Old absolute-path keys are converted to repo-relative keys. Entries already present in the shared file with a newer UpdatedAt are preserved. The per-repo file is removed on success. Returns the number of migrated notes.

func PagerCommand

func PagerCommand(cfg *config.AppConfig) string

PagerCommand determines the pager command to use.

func PagerEnv

func PagerEnv(pager string) string

PagerEnv returns environment variables needed for the pager.

func RunWorktreeNoteScript added in v1.36.0

func RunWorktreeNoteScript(ctx context.Context, script string, input WorktreeNoteScriptInput) (string, error)

RunWorktreeNoteScript executes worktree_note_script and returns the generated note text.

func SaveAccessHistory

func SaveAccessHistory(repoKey, worktreeDir string, history map[string]int64) error

SaveAccessHistory saves access history to file.

func SaveCache

func SaveCache(repoKey, worktreeDir string, worktrees []*models.WorktreeInfo) error

SaveCache saves worktree data to the cache file.

func SaveCommandHistory

func SaveCommandHistory(repoKey, worktreeDir string, commands []string) error

SaveCommandHistory saves command history to file.

func SavePaletteHistory

func SavePaletteHistory(repoKey, worktreeDir string, commands []CommandPaletteUsage) error

SavePaletteHistory saves palette usage history to file.

func SaveWorktreeNote added in v1.36.0

func SaveWorktreeNote(repoKey, worktreeDir, worktreeNotesPath, worktreePath, noteText string) error

SaveWorktreeNote stores a single note for a worktree path.

func SaveWorktreeNotes added in v1.35.0

func SaveWorktreeNotes(repoKey, worktreeDir, worktreeNotesPath string, notes map[string]models.WorktreeNote) error

SaveWorktreeNotes saves worktree notes to file.

func SortStatusTree

func SortStatusTree(node *StatusTreeNode)

SortStatusTree sorts tree nodes: directories first, then alphabetically.

func WorktreeNoteKey added in v1.37.0

func WorktreeNoteKey(repoKey, worktreeDir, worktreeNotesPath, worktreePath string) string

WorktreeNoteKey returns the storage key for a worktree note.

Default mode stores notes in per-repo files and uses full worktree paths as keys. Shared-file mode (worktreeNotesPath set) uses repo-relative keys for cross-system sync.

Types

type CICheckCache

type CICheckCache interface {
	// Get retrieves cached CI checks for a branch.
	// Returns the checks, fetch time, and whether the entry exists.
	Get(branch string) ([]*models.CICheck, time.Time, bool)

	// Set stores CI checks for a branch with the current timestamp.
	Set(branch string, checks []*models.CICheck)

	// Clear removes all cached entries.
	Clear()

	// IsFresh returns true if the cache entry exists and is within the TTL.
	IsFresh(branch string, ttl time.Duration) bool
}

CICheckCache provides cache management for CI check data.

func NewCICheckCache

func NewCICheckCache() CICheckCache

NewCICheckCache creates a new thread-safe CI check cache.

type CIDataService

type CIDataService interface {
	// Sort returns a copy of checks sorted with GitHub Actions first.
	Sort(checks []*models.CICheck) []*models.CICheck

	// StatusIcon returns the appropriate icon for CI status.
	// Draft PRs show "D" instead of CI status.
	StatusIcon(status string, isDraft, useIcons bool, iconProvider CIIconProvider) string

	// ExtractRunID extracts the run ID from a GitHub Actions URL.
	// Example: https://github.com/owner/repo/actions/runs/12345678/job/98765432 -> 12345678
	ExtractRunID(link string) string

	// ExtractJobID extracts the job ID from a GitHub Actions URL.
	// Example: https://github.com/owner/repo/actions/runs/12345678/job/98765432 -> 98765432
	ExtractJobID(link string) string

	// ExtractRepo extracts the owner/repo from a GitHub URL.
	// Example: https://github.com/owner/repo/actions/runs/12345678 -> owner/repo
	ExtractRepo(link string) string
}

CIDataService provides stateless CI check operations.

func NewCIDataService

func NewCIDataService() CIDataService

NewCIDataService creates a new CIDataService.

type CIFetchResult

type CIFetchResult struct {
	Branch string
	Checks []*models.CICheck
	Err    error
}

CIFetchResult contains the result of a CI status fetch operation.

type CIFetchService

type CIFetchService interface {
	// CreateFetchForPR creates a fetch function for PR-based CI status.
	// The returned function can be called to perform the fetch and return a result.
	CreateFetchForPR(ctx context.Context, git GitCIProvider, prNumber int, branch string) func() CIFetchResult

	// CreateFetchForCommit creates a fetch function for commit-based CI status.
	// The returned function can be called to perform the fetch and return a result.
	CreateFetchForCommit(ctx context.Context, git GitCIProvider, worktreePath, branch string) func() CIFetchResult
}

CIFetchService creates commands for fetching CI status. This service abstracts the creation of fetch operations.

func NewCIFetchService

func NewCIFetchService() CIFetchService

NewCIFetchService creates a new CIFetchService.

type CIIconProvider

type CIIconProvider interface {
	GetCIIcon(conclusion string) string
}

CIIconProvider provides CI status icons.

type CommandExecutor

type CommandExecutor interface {
	Run(cmd string, cwd string, env map[string]string) tea.Cmd
	RunWithPager(cmd string, cwd string, env map[string]string) tea.Cmd
	RunInteractive(cmd *exec.Cmd, callback tea.ExecCallback) tea.Cmd
}

CommandExecutor runs shell commands for the application.

type CommandPaletteUsage

type CommandPaletteUsage struct {
	ID        string `json:"id"`
	Timestamp int64  `json:"timestamp"`
	Count     int    `json:"count"`
}

CommandPaletteUsage tracks usage frequency and recency for command palette items.

func LoadPaletteHistory

func LoadPaletteHistory(repoKey, worktreeDir string) ([]CommandPaletteUsage, error)

LoadPaletteHistory loads palette usage history from file.

type CreateFromChangesOptions

type CreateFromChangesOptions struct {
	SourcePath    string
	NewBranch     string
	TargetPath    string
	CurrentBranch string
	Env           map[string]string
}

CreateFromChangesOptions contains parameters for creating a worktree from existing changes.

type CreateOptions

type CreateOptions struct {
	Branch     string
	TargetPath string
	BaseRef    string
	Env        map[string]string
}

CreateOptions contains parameters for worktree creation.

type FilterService

type FilterService struct {
	FilterQuery         string
	StatusFilterQuery   string
	LogFilterQuery      string
	WorktreeSearchQuery string
	StatusSearchQuery   string
	LogSearchQuery      string
}

FilterService stores filter and search queries by target.

func NewFilterService

func NewFilterService(initialFilter string) *FilterService

NewFilterService creates a new FilterService with an optional initial filter.

func (*FilterService) FilterQueryForTarget

func (f *FilterService) FilterQueryForTarget(target state.FilterTarget) string

FilterQueryForTarget returns the filter query for the given target.

func (*FilterService) HasActiveFilterForPane

func (f *FilterService) HasActiveFilterForPane(paneIndex int) bool

HasActiveFilterForPane reports whether a pane has a non-empty filter applied.

func (*FilterService) SearchQueryForTarget

func (f *FilterService) SearchQueryForTarget(target state.SearchTarget) string

SearchQueryForTarget returns the search query for the given target.

func (*FilterService) SetFilterQuery

func (f *FilterService) SetFilterQuery(target state.FilterTarget, query string)

SetFilterQuery sets the filter query for the given target.

func (*FilterService) SetSearchQuery

func (f *FilterService) SetSearchQuery(target state.SearchTarget, query string)

SetSearchQuery sets the search query for the given target.

type GitCIProvider

type GitCIProvider interface {
	// FetchCIStatus fetches CI status for a PR.
	FetchCIStatus(ctx context.Context, prNumber int, branch string) ([]*models.CICheck, error)

	// FetchCIStatusByCommit fetches CI status for a commit SHA.
	FetchCIStatusByCommit(ctx context.Context, sha, path string) ([]*models.CICheck, error)

	// GetHeadSHA returns the HEAD commit SHA for a worktree path.
	GetHeadSHA(ctx context.Context, path string) string

	// IsGitHub returns true if the repository is hosted on GitHub.
	IsGitHub(ctx context.Context) bool
}

GitCIProvider defines the interface for git service CI operations. This interface enables dependency injection for testing CI-related functionality.

type GitCommonDirResolver

type GitCommonDirResolver interface {
	RunGit(ctx context.Context, args []string, cwd string, okReturncodes []int, strip, silent bool) string
}

GitCommonDirResolver resolves the git common directory for a repository.

type GitService

type GitService interface {
	RunGit(ctx context.Context, args []string, cwd string, okReturncodes []int, strip, silent bool) string
	RunCommandChecked(ctx context.Context, args []string, cwd, errorPrefix string) bool
	GetMainBranch(ctx context.Context) string
	GetMergedBranches(ctx context.Context, baseBranch string) []string
	RenameWorktree(ctx context.Context, oldPath, newPath, oldBranch, newBranch string) bool
	ExecuteCommands(ctx context.Context, cmdList []string, cwd string, env map[string]string) error
	RunGitWithCombinedOutput(ctx context.Context, args []string, cwd string, env map[string]string) ([]byte, error)
}

GitService defines the subset of git operations needed by WorktreeService.

type GitWatchService

type GitWatchService struct {
	Started     bool
	Waiting     bool
	CommonDir   string
	Roots       []string
	Events      chan struct{}
	Done        chan struct{}
	Paths       map[string]struct{}
	Mu          sync.Mutex
	Watcher     *fsnotify.Watcher
	LastRefresh time.Time
	// contains filtered or unexported fields
}

GitWatchService manages git watcher state.

func NewGitWatchService

func NewGitWatchService(git GitCommonDirResolver, logf func(string, ...any)) *GitWatchService

NewGitWatchService creates a new GitWatchService.

func (*GitWatchService) IsUnderRoot

func (w *GitWatchService) IsUnderRoot(path string) bool

IsUnderRoot reports whether the path is under any watch root.

func (*GitWatchService) MaybeWatchNewDir

func (w *GitWatchService) MaybeWatchNewDir(path string)

MaybeWatchNewDir registers newly created directories under watch roots.

func (*GitWatchService) NextEvent

func (w *GitWatchService) NextEvent() <-chan struct{}

NextEvent returns the event channel if waiting is not already active.

func (*GitWatchService) ResetWaiting

func (w *GitWatchService) ResetWaiting()

ResetWaiting clears the waiting flag after an event is processed.

func (*GitWatchService) ShouldRefresh

func (w *GitWatchService) ShouldRefresh(now time.Time) bool

ShouldRefresh checks debounce timing for watcher events.

func (*GitWatchService) Signal

func (w *GitWatchService) Signal()

Signal notifies listeners of watcher activity.

func (*GitWatchService) Start

func (w *GitWatchService) Start(ctx context.Context, cfg *config.AppConfig) (bool, error)

Start initialises the watcher and starts the background goroutine.

func (*GitWatchService) Stop

func (w *GitWatchService) Stop()

Stop stops the watcher and closes channels.

type HistoryService

type HistoryService interface {
	LoadCommands(repoKey string) []string
	SaveCommands(repoKey string, cmds []string)
	AddCommand(repoKey string, cmd string)
	LoadAccessHistory(repoKey string) map[string]int64
	SaveAccessHistory(repoKey string, history map[string]int64)
	RecordAccess(repoKey string, path string)
	LoadPaletteHistory(repoKey string) []CommandPaletteUsage
	SavePaletteHistory(repoKey string, commands []CommandPaletteUsage)
	AddPaletteUsage(repoKey string, id string)
}

HistoryService persists command and palette history.

type Pager

type Pager interface {
	Show(content string, env []string, cwd string) tea.Cmd
	ShowFileDiff(sf models.StatusFile, wt *models.WorktreeInfo) tea.Cmd
	ShowCommitDiff(sha string, wt *models.WorktreeInfo) tea.Cmd
}

Pager defines how diffs and content are displayed.

type PruneCandidate

type PruneCandidate struct {
	Worktree *models.WorktreeInfo
	Source   string // "pr", "git", or "both"
}

PruneCandidate represents a worktree that is a candidate for pruning.

type StatusFile

type StatusFile = models.StatusFile

StatusFile represents a file entry from git status.

type StatusService

type StatusService struct {
	Tree          *StatusTreeNode
	TreeFlat      []*StatusTreeNode
	CollapsedDirs map[string]bool
	Index         int
}

StatusService manages status tree state.

func NewStatusService

func NewStatusService() *StatusService

NewStatusService creates a new StatusService.

func (*StatusService) ClampIndex

func (s *StatusService) ClampIndex()

ClampIndex ensures Index is within the valid range for the flat list.

func (*StatusService) RebuildFlat

func (s *StatusService) RebuildFlat()

RebuildFlat rebuilds the flattened tree representation.

func (*StatusService) RestoreSelection

func (s *StatusService) RestoreSelection(path string)

RestoreSelection sets Index based on the provided path if it exists.

func (*StatusService) SelectedPath

func (s *StatusService) SelectedPath() string

SelectedPath returns the path of the currently selected node.

func (*StatusService) ToggleCollapse

func (s *StatusService) ToggleCollapse(path string)

ToggleCollapse toggles a directory collapse state and rebuilds the flat list.

type StatusTreeNode

type StatusTreeNode struct {
	Path        string            // Full path (e.g., "internal/app" or "internal/app/app.go")
	File        *StatusFile       // nil for directories
	Children    []*StatusTreeNode // nil for files
	Compression int               // Number of compressed path segments (e.g., "a/b" = 1)
	Depth       int               // Cached depth for rendering
}

StatusTreeNode represents a node in the status file tree (directory or file).

func BuildStatusTree

func BuildStatusTree(files []StatusFile) *StatusTreeNode

BuildStatusTree builds a tree structure from a flat list of files. Files are grouped by directory, with directories sorted before files.

func FlattenStatusTree

func FlattenStatusTree(node *StatusTreeNode, collapsed map[string]bool, depth int) []*StatusTreeNode

FlattenStatusTree returns visible nodes respecting collapsed state.

func (*StatusTreeNode) CollectFiles

func (n *StatusTreeNode) CollectFiles() []*StatusFile

CollectFiles recursively collects all StatusFile pointers from this node and its children.

func (*StatusTreeNode) IsDir

func (n *StatusTreeNode) IsDir() bool

IsDir returns true if this node is a directory.

func (*StatusTreeNode) Name

func (n *StatusTreeNode) Name() string

Name returns the display name for this node.

type WorktreeNoteScriptInput added in v1.36.0

type WorktreeNoteScriptInput struct {
	Content string
	Type    string
	Number  int
	Title   string
	URL     string
}

WorktreeNoteScriptInput contains the context passed to worktree_note_script.

type WorktreeService

type WorktreeService interface {
	// Create creates a new worktree.
	Create(ctx context.Context, opts CreateOptions) error

	// CreateFromChanges moves changes from an existing worktree to a new one.
	CreateFromChanges(ctx context.Context, opts CreateFromChangesOptions) error

	// Delete removes a worktree and optionally its branch.
	Delete(ctx context.Context, path, branch string, deleteBranch bool) error

	// Rename moves a worktree and conditionally renames its branch.
	Rename(ctx context.Context, oldPath, newPath, oldBranch, newBranch string) error

	// Push pushes a worktree's branch to its upstream.
	Push(ctx context.Context, wt *models.WorktreeInfo, args []string, env map[string]string) (string, error)

	// Sync synchronizes a worktree's branch with its upstream (pull + push).
	Sync(ctx context.Context, wt *models.WorktreeInfo, pullArgs, pushArgs []string, env map[string]string) (string, error)

	// UpdateFromBase updates a branch from its PR base branch.
	UpdateFromBase(ctx context.Context, wt *models.WorktreeInfo, mergeMethod string, env map[string]string) (string, error)

	// Absorb merges or rebases a worktree into the main branch.
	Absorb(ctx context.Context, wt *models.WorktreeInfo, mainWorktree *models.WorktreeInfo, mergeMethod string) error

	// GetPruneCandidates identifies worktrees that have been merged and are candidates for pruning.
	GetPruneCandidates(ctx context.Context, worktrees []*models.WorktreeInfo) ([]PruneCandidate, error)

	// ExecuteCommands runs a list of shell commands in the specified directory.
	ExecuteCommands(ctx context.Context, commands []string, cwd string, env map[string]string) error
}

WorktreeService handles high-level worktree lifecycle and synchronization operations.

func NewWorktreeService

func NewWorktreeService(git GitService) WorktreeService

NewWorktreeService creates a new WorktreeService.

Jump to

Keyboard shortcuts

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