Documentation
¶
Overview ¶
Package git provides git operations via shell commands.
All operations use os/exec.Command to call the git CLI directly rather than using Go git libraries. This approach is simpler, more reliable, and ensures compatibility with user configurations (SSH keys, credential helpers, aliases).
Worktree Operations ¶
Core worktree management:
- [AddWorktree]: Create worktrees for new or existing branches
- RemoveWorktree: Remove worktrees with optional force flag
- [MoveWorktree]: Relocate worktrees to new paths
- LoadWorktreesForRepos: Load worktrees from multiple repos in parallel
Repository Operations ¶
Repository and branch queries:
- GetOriginURL, [GetRepoName]: Extract repository information
- GetCurrentBranch, [BranchExists]: Branch operations
- [GetCommitCount]: Commits ahead of default branch
- GetDefaultBranch: Detect main/master branch
Link Validation and Repair ¶
Git worktrees have bidirectional links between the worktree's .git file and the main repo's .git/worktrees/ directory. These can break when repos are moved. Functions for diagnosis and repair:
- [IsWorktreeLinkValid]: Check if links are intact
- [CanRepairWorktree]: Check if repair is possible
- [RepairWorktree]: Fix broken links via "git worktree repair"
- [ListPrunableWorktrees]: Find stale git references
Index ¶
- Variables
- func CheckGit() error
- func ClearBranchNote(ctx context.Context, repoPath, branch string) error
- func CloneBareWithWorktreeSupport(ctx context.Context, url, destPath string) error
- func CloneRegular(ctx context.Context, url, destPath string) error
- func CreateWorktree(ctx context.Context, gitDir, wtPath, branch string) error
- func CreateWorktreeNewBranch(ctx context.Context, gitDir, wtPath, branch, baseRef string) error
- func CreateWorktreeOrphan(ctx context.Context, gitDir, wtPath, branch string) error
- func DeleteLocalBranch(ctx context.Context, repoPath, branch string, force bool) error
- func FetchBranch(ctx context.Context, repoPath, branch string) error
- func FetchBranchFromRemote(ctx context.Context, repoPath, remote, branch string) error
- func GetAllBranchConfig(ctx context.Context, repoPath string) (notes map[string]string, upstreams map[string]bool)
- func GetBranchNote(ctx context.Context, repoPath, branch string) (string, error)
- func GetCommitMeta(ctx context.Context, repoPath string, shas []string) map[string]CommitMeta
- func GetCurrentBranch(ctx context.Context, path string) (string, error)
- func GetCurrentRepoMainPathFrom(ctx context.Context, path string) string
- func GetDefaultBranch(ctx context.Context, repoPath string) string
- func GetGitDir(repoPath string, repoType RepoType) string
- func GetMainRepoPath(worktreePath string) (string, error)
- func GetMainRepoPathWithContext(ctx context.Context, worktreePath string) (string, error)
- func GetOriginURL(ctx context.Context, repoPath string) (string, error)
- func GetRepoDisplayName(repoPath string) string
- func GetUpstreamBranch(ctx context.Context, repoPath, branch string) string
- func GetWorktreeBranches(ctx context.Context, repoPath string) map[string]bool
- func HasRemote(ctx context.Context, repoPath, remoteName string) bool
- func ListLocalBranches(ctx context.Context, repoPath string) ([]string, error)
- func ListRemoteBranches(ctx context.Context, repoPath string) ([]string, error)
- func ListRemotes(ctx context.Context, repoPath string) ([]string, error)
- func LoadWorktreesForRepos(ctx context.Context, repos []RepoRef) ([]Worktree, []LoadWarning)
- func LocalBranchExists(ctx context.Context, repoPath, branch string) bool
- func ParseRemoteRef(ctx context.Context, repoPath, ref string) (remote, branch string, isRemote bool)
- func PruneWorktrees(ctx context.Context, repoPath string) error
- func PushBranch(ctx context.Context, repoPath, branch string) error
- func RefExists(ctx context.Context, repoPath, ref string) bool
- func RemoteBranchExists(ctx context.Context, repoPath, branch string) bool
- func RemoveWorktree(ctx context.Context, worktree Worktree, force bool) error
- func RunGitCommand(ctx context.Context, dir string, args ...string) error
- func SetBranchNote(ctx context.Context, repoPath, branch, note string) error
- func SetUpstreamBranch(ctx context.Context, repoPath, localBranch, upstream string) error
- func Stash(ctx context.Context, path string) (int, error)
- func StashPop(ctx context.Context, path string) error
- type CommitMeta
- type CreateWorktreeResult
- type LoadWarning
- type MigrateToBareResult
- type MigrateToRegularResult
- type MigrationOptions
- type MigrationPlan
- type RegularMigrationPlan
- type RepoRef
- type RepoType
- type Worktree
- type WorktreeInfo
- type WorktreeMigration
Constants ¶
This section is empty.
Variables ¶
var ErrGitNotFound = fmt.Errorf("git not found: please install git (https://git-scm.com)")
ErrGitNotFound indicates git is not installed or not in PATH
Functions ¶
func ClearBranchNote ¶
ClearBranchNote removes the note (description) from a branch
func CloneBareWithWorktreeSupport ¶ added in v0.13.0
CloneBareWithWorktreeSupport clones a repo as a bare repo inside the .git directory. This allows worktrees to be created as siblings while git commands work normally.
The directory structure will be:
destPath/ └── .git/ # bare git repo contents (HEAD, objects/, refs/, etc.)
func CloneRegular ¶ added in v0.22.0
CloneRegular performs a standard (non-bare) git clone. Cleans up the destination directory on failure.
func CreateWorktree ¶ added in v0.13.0
CreateWorktree creates a worktree for an existing branch. gitDir is the .git directory (for regular repos) or the bare repo path. wtPath is the target worktree path. branch is the existing branch to checkout.
func CreateWorktreeNewBranch ¶ added in v0.13.0
CreateWorktreeNewBranch creates a worktree with a new branch. gitDir is the .git directory (for regular repos) or the bare repo path. wtPath is the target worktree path. branch is the new branch name. baseRef is the starting point (e.g., "origin/main").
func CreateWorktreeOrphan ¶ added in v0.15.0
CreateWorktreeOrphan creates a worktree with a new orphan branch. Used for empty repos (no commits) where there's no valid ref to branch from.
func DeleteLocalBranch ¶
DeleteLocalBranch deletes a local branch
func FetchBranch ¶
FetchBranch fetches a specific branch from origin
func FetchBranchFromRemote ¶ added in v0.16.0
FetchBranchFromRemote fetches a specific branch from a named remote.
func GetAllBranchConfig ¶
func GetAllBranchConfig(ctx context.Context, repoPath string) (notes map[string]string, upstreams map[string]bool)
GetAllBranchConfig returns branch notes and upstreams for a repository in one call. Uses: `git config --get-regexp 'branch\.'` Returns: notes map (branch -> note), upstreams map (branch -> upstream ref)
func GetBranchNote ¶
GetBranchNote returns the note (description) for a branch Returns empty string if no note is set
func GetCommitMeta ¶ added in v0.21.0
GetCommitMeta returns commit metadata for the given SHAs in one batched git call. Uses `git show -s --format=%H|%ct|%cr` to get both unix timestamps and relative times. Returns a map of full SHA → CommitMeta. Returns nil for empty input, empty map on error (non-fatal).
func GetCurrentBranch ¶
GetCurrentBranch returns the current branch name Returns "(detached)" for detached HEAD state
func GetCurrentRepoMainPathFrom ¶ added in v0.8.0
GetCurrentRepoMainPathFrom returns the main repository path from the given path Works whether you're in the main repo or a worktree Returns empty string if not in a git repo
func GetDefaultBranch ¶
GetDefaultBranch returns the default branch name for the remote (e.g., "main" or "master")
func GetMainRepoPath ¶
GetMainRepoPath returns the main repository path from a worktree path. Uses git commands rather than reading .git files directly.
func GetMainRepoPathWithContext ¶ added in v0.13.0
GetMainRepoPathWithContext returns the main repository path from a worktree path. Uses git rev-parse --git-common-dir to find the shared git directory.
func GetOriginURL ¶
GetOriginURL gets the origin URL for a repository
func GetRepoDisplayName ¶ added in v0.4.0
GetRepoDisplayName returns the folder name of the repository.
func GetUpstreamBranch ¶
GetUpstreamBranch returns the remote branch name for a local branch. Returns empty string if no upstream is configured.
func GetWorktreeBranches ¶ added in v0.8.0
GetWorktreeBranches returns a set of branch names that are currently checked out in worktrees. Useful for filtering out branches that can't be checked out again.
func ListLocalBranches ¶ added in v0.8.0
ListLocalBranches returns all local branch names for a repository.
func ListRemoteBranches ¶ added in v0.8.0
ListRemoteBranches returns all remote branch names (with remote prefix, e.g. "origin/main") for a repository.
func ListRemotes ¶ added in v0.16.0
ListRemotes returns all remote names for a repository.
func LoadWorktreesForRepos ¶ added in v0.17.0
func LoadWorktreesForRepos(ctx context.Context, repos []RepoRef) ([]Worktree, []LoadWarning)
LoadWorktreesForRepos fetches worktrees from all repos in parallel. Per repo: ListWorktreesFromRepo + GetAllBranchConfig + GetOriginURL + GetCommitMeta. PR fields are NOT populated — callers do that from prcache after loading. Results maintain stable ordering (by repo index, then worktree order within repo). Errors per repo are collected as warnings (non-fatal).
func LocalBranchExists ¶ added in v0.16.0
LocalBranchExists checks if a local branch exists in the given repo.
func ParseRemoteRef ¶ added in v0.16.0
func ParseRemoteRef(ctx context.Context, repoPath, ref string) (remote, branch string, isRemote bool)
ParseRemoteRef checks if ref has a valid remote prefix (e.g., "origin/main"). Returns the remote name, branch name, and whether it's a remote ref.
func PruneWorktrees ¶
PruneWorktrees prunes stale worktree references
func PushBranch ¶ added in v0.14.0
PushBranch pushes a branch to origin.
func RefExists ¶ added in v0.15.0
RefExists checks if a git ref resolves to a valid object. Returns false for unborn HEAD (empty repos with no commits). Works for any ref: HEAD, origin/main, refs/heads/branch, etc.
func RemoteBranchExists ¶ added in v0.14.0
RemoteBranchExists checks if a remote tracking branch exists.
func RemoveWorktree ¶
RemoveWorktree removes a git worktree
func RunGitCommand ¶ added in v0.13.0
RunGitCommand executes a git command with context support and verbose logging. This is the exported version of runGit for use by commands.
func SetBranchNote ¶
SetBranchNote sets a note (description) on a branch
func SetUpstreamBranch ¶ added in v0.14.0
SetUpstreamBranch sets the upstream tracking branch for a local branch. upstream should be "origin/<branch>" or just "<branch>" (will prepend origin/).
func Stash ¶ added in v0.10.0
Stash creates a stash entry with a specific message. Includes untracked files (-u) to capture all uncommitted changes. Returns the number of stashed files. If the stash succeeded but the file count cannot be determined, returns 1 as a safe fallback. Returns 0 when there is nothing to stash. Returns error only if git stash fails.
Types ¶
type CommitMeta ¶ added in v0.21.0
type CommitMeta struct {
Age string // Human-readable relative time (e.g. "3 hours ago")
Date time.Time // Commit timestamp for sorting
}
CommitMeta holds commit metadata fetched in a single batched git call.
type CreateWorktreeResult ¶
CreateWorktreeResult contains the result of creating a worktree
type LoadWarning ¶ added in v0.17.0
LoadWarning represents a non-fatal error encountered while loading worktrees for a repo.
type MigrateToBareResult ¶ added in v0.13.0
type MigrateToBareResult struct {
MainWorktreePath string // Path to the new main worktree (e.g., repo/main)
GitDir string // Path to the .git directory
}
MigrateToBareResult contains the result of a successful migration
func MigrateToBare ¶ added in v0.13.0
func MigrateToBare(ctx context.Context, plan *MigrationPlan) (*MigrateToBareResult, error)
MigrateToBare converts a regular repo to bare-in-.git format. This preserves all working tree files including uncommitted changes.
type MigrateToRegularResult ¶ added in v0.22.0
type MigrateToRegularResult struct {
RepoPath string // Repo root (now has working tree)
GitDir string // .git directory
}
MigrateToRegularResult contains the result of a successful bare→regular migration
func MigrateToRegular ¶ added in v0.22.0
func MigrateToRegular(ctx context.Context, plan *RegularMigrationPlan) (*MigrateToRegularResult, error)
MigrateToRegular converts a bare-in-.git repo to a regular repo. This preserves all working tree files including uncommitted changes.
type MigrationOptions ¶ added in v0.14.0
type MigrationOptions struct {
WorktreeFormat string // Format string for worktree paths (e.g., "{branch}", "../{repo}-{branch}")
RepoName string // Repository name for path resolution
}
MigrationOptions configures how the migration computes worktree paths
func (MigrationOptions) Validate ¶ added in v0.22.0
func (o MigrationOptions) Validate() error
Validate checks that required fields are set.
type MigrationPlan ¶ added in v0.13.0
type MigrationPlan struct {
RepoPath string // Original repo path
GitDir string // Current .git directory path
CurrentBranch string // Branch to use for main worktree
MainBranchUpstream string // Upstream for the main branch (e.g., "main" for origin/main)
MainWorktreePath string // Computed path for the main worktree
WorktreesToFix []WorktreeMigration
}
MigrationPlan describes what will be done during migration
func ValidateMigration ¶ added in v0.13.0
func ValidateMigration(ctx context.Context, repoPath string, opts MigrationOptions) (*MigrationPlan, error)
ValidateMigration checks if a repo can be migrated and returns the migration plan. The opts parameter configures how worktree paths are computed.
type RegularMigrationPlan ¶ added in v0.22.0
type RegularMigrationPlan struct {
RepoPath string // Repository root (contains .git/)
GitDir string // .git directory (bare repo)
DefaultBranch string // Branch to move to repo root
DefaultBranchWT string // Current worktree path for default branch
DefaultUpstream string // Upstream tracking for default branch
WorktreesToFix []WorktreeMigration // Other worktrees to reformat
}
RegularMigrationPlan describes what will be done during bare→regular migration
func ValidateMigrationToRegular ¶ added in v0.22.0
func ValidateMigrationToRegular(ctx context.Context, repoPath string, opts MigrationOptions) (*RegularMigrationPlan, error)
ValidateMigrationToRegular checks if a bare repo can be converted to regular and returns the plan.
type RepoRef ¶ added in v0.17.0
RepoRef identifies a repo for the loader. Keeps the git package independent of the registry package.
type RepoType ¶ added in v0.13.0
type RepoType int
RepoType indicates whether a repo is bare or regular
func DetectRepoType ¶ added in v0.13.0
DetectRepoType determines if a path is a bare or regular git repository
type Worktree ¶
type Worktree struct {
Path string `json:"path"`
Branch string `json:"branch"`
CommitHash string `json:"commit"`
CommitAge string `json:"commit_age,omitempty"`
RepoName string `json:"repo"`
RepoPath string `json:"-"`
OriginURL string `json:"-"`
Note string `json:"note,omitempty"`
HasUpstream bool `json:"-"`
CommitDate time.Time `json:"commit_date"`
PRNumber int `json:"pr_number,omitempty"`
PRState string `json:"pr_state,omitempty"`
PRURL string `json:"pr_url,omitempty"`
PRDraft bool `json:"pr_draft,omitempty"`
}
Worktree represents a git worktree with its metadata. Used as the unified struct across all commands (list, prune, cd, exec). Fields tagged json:"-" are internal and excluded from user-facing JSON output.
type WorktreeInfo ¶
type WorktreeInfo struct {
Path string
Branch string
CommitHash string // Full hash from git, caller can truncate
}
WorktreeInfo contains basic worktree information from git worktree list.
func ListWorktreesFromRepo ¶
func ListWorktreesFromRepo(ctx context.Context, repoPath string) ([]WorktreeInfo, error)
ListWorktreesFromRepo returns all worktrees for a repository using git worktree list --porcelain -z. Uses NUL-separated output for robust parsing of paths with special characters. Skips bare worktrees (e.g., .bare directory in bare repo layouts).
type WorktreeMigration ¶ added in v0.13.0
type WorktreeMigration struct {
OldPath string // Current worktree path
NewPath string // New path after migration (may be same)
Branch string
Upstream string // Upstream branch (e.g., "feature" for origin/feature)
OldName string // Name in .git/worktrees/
NewName string // Name after migration (may be same)
NeedsMove bool // Whether the worktree folder needs to be moved
}
WorktreeMigration describes a worktree that needs to be updated