git

package
v0.22.0 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2026 License: MIT Imports: 11 Imported by: 0

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:

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

Constants

This section is empty.

Variables

View Source
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 CheckGit

func CheckGit() error

CheckGit verifies that git is available in PATH

func ClearBranchNote

func ClearBranchNote(ctx context.Context, repoPath, branch string) error

ClearBranchNote removes the note (description) from a branch

func CloneBareWithWorktreeSupport added in v0.13.0

func CloneBareWithWorktreeSupport(ctx context.Context, url, destPath string) error

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

func CloneRegular(ctx context.Context, url, destPath string) error

CloneRegular performs a standard (non-bare) git clone. Cleans up the destination directory on failure.

func CreateWorktree added in v0.13.0

func CreateWorktree(ctx context.Context, gitDir, wtPath, branch string) error

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

func CreateWorktreeNewBranch(ctx context.Context, gitDir, wtPath, branch, baseRef string) error

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

func CreateWorktreeOrphan(ctx context.Context, gitDir, wtPath, branch string) error

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

func DeleteLocalBranch(ctx context.Context, repoPath, branch string, force bool) error

DeleteLocalBranch deletes a local branch

func FetchBranch

func FetchBranch(ctx context.Context, repoPath, branch string) error

FetchBranch fetches a specific branch from origin

func FetchBranchFromRemote added in v0.16.0

func FetchBranchFromRemote(ctx context.Context, repoPath, remote, branch string) error

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

func GetBranchNote(ctx context.Context, repoPath, branch string) (string, error)

GetBranchNote returns the note (description) for a branch Returns empty string if no note is set

func GetCommitMeta added in v0.21.0

func GetCommitMeta(ctx context.Context, repoPath string, shas []string) map[string]CommitMeta

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

func GetCurrentBranch(ctx context.Context, path string) (string, error)

GetCurrentBranch returns the current branch name Returns "(detached)" for detached HEAD state

func GetCurrentRepoMainPathFrom added in v0.8.0

func GetCurrentRepoMainPathFrom(ctx context.Context, path string) string

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

func GetDefaultBranch(ctx context.Context, repoPath string) string

GetDefaultBranch returns the default branch name for the remote (e.g., "main" or "master")

func GetGitDir added in v0.13.0

func GetGitDir(repoPath string, repoType RepoType) string

GetGitDir returns the git directory for a repo

func GetMainRepoPath

func GetMainRepoPath(worktreePath string) (string, error)

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

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

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

func GetOriginURL(ctx context.Context, repoPath string) (string, error)

GetOriginURL gets the origin URL for a repository

func GetRepoDisplayName added in v0.4.0

func GetRepoDisplayName(repoPath string) string

GetRepoDisplayName returns the folder name of the repository.

func GetUpstreamBranch

func GetUpstreamBranch(ctx context.Context, repoPath, branch string) string

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

func GetWorktreeBranches(ctx context.Context, repoPath string) map[string]bool

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 HasRemote added in v0.12.0

func HasRemote(ctx context.Context, repoPath, remoteName string) bool

HasRemote checks if a remote with the given name exists

func ListLocalBranches added in v0.8.0

func ListLocalBranches(ctx context.Context, repoPath string) ([]string, error)

ListLocalBranches returns all local branch names for a repository.

func ListRemoteBranches added in v0.8.0

func ListRemoteBranches(ctx context.Context, repoPath string) ([]string, error)

ListRemoteBranches returns all remote branch names (with remote prefix, e.g. "origin/main") for a repository.

func ListRemotes added in v0.16.0

func ListRemotes(ctx context.Context, repoPath string) ([]string, error)

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

func LocalBranchExists(ctx context.Context, repoPath, branch string) bool

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

func PruneWorktrees(ctx context.Context, repoPath string) error

PruneWorktrees prunes stale worktree references

func PushBranch added in v0.14.0

func PushBranch(ctx context.Context, repoPath, branch string) error

PushBranch pushes a branch to origin.

func RefExists added in v0.15.0

func RefExists(ctx context.Context, repoPath, ref string) bool

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

func RemoteBranchExists(ctx context.Context, repoPath, branch string) bool

RemoteBranchExists checks if a remote tracking branch exists.

func RemoveWorktree

func RemoveWorktree(ctx context.Context, worktree Worktree, force bool) error

RemoveWorktree removes a git worktree

func RunGitCommand added in v0.13.0

func RunGitCommand(ctx context.Context, dir string, args ...string) error

RunGitCommand executes a git command with context support and verbose logging. This is the exported version of runGit for use by commands.

func SetBranchNote

func SetBranchNote(ctx context.Context, repoPath, branch, note string) error

SetBranchNote sets a note (description) on a branch

func SetUpstreamBranch added in v0.14.0

func SetUpstreamBranch(ctx context.Context, repoPath, localBranch, upstream string) error

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

func Stash(ctx context.Context, path string) (int, error)

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.

func StashPop added in v0.10.0

func StashPop(ctx context.Context, path string) error

StashPop applies and removes the most recent stash entry. Returns nil if successful.

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

type CreateWorktreeResult struct {
	Path          string
	AlreadyExists bool
}

CreateWorktreeResult contains the result of creating a worktree

type LoadWarning added in v0.17.0

type LoadWarning struct {
	RepoName string
	Err      error
}

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

type RepoRef struct {
	Name string
	Path string
}

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

const (
	RepoTypeRegular RepoType = iota
	RepoTypeBare
)

func DetectRepoType added in v0.13.0

func DetectRepoType(path string) (RepoType, error)

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

Jump to

Keyboard shortcuts

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