git

package
v0.15.4 Latest Latest
Warning

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

Go to latest
Published: May 18, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddWorktree

func AddWorktree(repo Repo, newName, newPath, fromRef string) error

AddWorktree creates a new linked worktree at newPath with a new branch newName, starting at fromRef (branch name, tag, or commit hash). fromRef may be empty, in which case git uses the current HEAD of the repo.

func AddWorktreeFromRemote

func AddWorktreeFromRemote(repo Repo, worktreePath, branch, remoteBranch string) error

AddWorktreeFromRemote adds a worktree for branch. It first tries to check out an existing local branch, then falls back to creating a tracking branch from remoteBranch (for freshly cloned bare repositories).

func AmendHead added in v0.14.5

func AmendHead(root string) (string, error)

AmendHead amends the HEAD commit with the currently staged changes.

func ApplyPatchToIndex

func ApplyPatchToIndex(worktreeRoot, patch string, reverse bool, unidiffZero bool) error

ApplyPatchToIndex applies patch to the index in worktreeRoot.

func ApplyPatchToWorktree

func ApplyPatchToWorktree(worktreeRoot, patch string, reverse bool, unidiffZero bool) error

ApplyPatchToWorktree applies patch to the worktree in worktreeRoot.

func BinaryFileSizes

func BinaryFileSizes(worktreeRoot string, file StageFileStatus) (prevSize, newSize int64, prevOK, newOK bool)

BinaryFileSizes returns previous and new file sizes for binary diff summaries. prevSize is read from HEAD (or rename source when available). newSize is read from the worktree path, falling back to the index blob.

func BranchRemote

func BranchRemote(repo Repo, branch string) string

BranchRemote returns the remote configured for branch (e.g. "origin"), falling back to "origin" if none is set.

func CloneBare

func CloneBare(repoURL, targetDir, cwd string) (string, error)

CloneBare clones repoURL using the .bare trick:

my-repo/
  .bare/   ← actual bare git repo
  .git      ← text file: "gitdir: ./.bare"
  main/    ← linked worktrees live here

targetDir, if non-empty, sets the outer directory name. Otherwise the name is inferred from the URL (with any ".git" suffix stripped). Returns the path to the outer directory (e.g. my-repo/).

func ColorizeDiff added in v0.13.0

func ColorizeDiff(worktreeRoot, path, rawDiff string, cached, sideBySide bool, renderWidth, contextLines int) (string, error)

ColorizeDiff colorizes a raw unified diff using delta if available, falling back to git diff --color=always.

func ColorizeUntrackedDiff added in v0.13.0

func ColorizeUntrackedDiff(worktreeRoot, path, rawDiff string, sideBySide bool, renderWidth, contextLines int) (string, error)

ColorizeUntrackedDiff colorizes a raw untracked diff using delta if available, falling back to git diff --no-index --color=always.

func CommitFileDiffForRef added in v0.13.0

func CommitFileDiffForRef(repoRoot, ref, path string) (string, error)

func CommitFileDiffWithDeltaForRef added in v0.13.0

func CommitFileDiffWithDeltaForRef(repoRoot, ref, path string, renderWidth int) (string, error)

func CommitFixup added in v0.14.5

func CommitFixup(root, hash string) (string, error)

CommitFixup creates a fixup commit targeting the given hash.

func CreateAnnotatedTag added in v0.15.1

func CreateAnnotatedTag(root, tag, message string) error

CreateAnnotatedTag creates an annotated tag at HEAD.

func CreateBranch

func CreateBranch(repo Repo, name string) error

CreateBranch creates and checks out a new branch.

func CurrentBranch

func CurrentBranch(dir string) (string, error)

CurrentBranch returns the short name of the current branch in dir.

func DefaultMainRemoteRef

func DefaultMainRemoteRef(repoRoot string) string

DefaultMainRemoteRef returns the best remote mainline ref for repoRoot. It prefers origin/<default-branch>, then falls back to origin/main/master if present.

func DeleteLocalBranch

func DeleteLocalBranch(repo Repo, name string, force bool) error

DeleteLocalBranch deletes a local branch. Use force=true to delete unmerged branches.

func DeleteRemoteBranch

func DeleteRemoteBranch(repo Repo, remoteName, branchName string) error

DeleteRemoteBranch deletes a branch on the remote.

func DeltaAvailable

func DeltaAvailable() bool

func DiffPath

func DiffPath(worktreeRoot, path string, cached bool, contextLines int) (string, error)

DiffPath returns a unified diff for path. When cached is true, it reads index vs HEAD. Output is plain (no ANSI colors).

func DiffPathWithDelta

func DiffPathWithDelta(worktreeRoot, path string, cached bool, sideBySide bool, renderWidth int, contextLines int) (string, error)

DiffPathWithDelta returns a unified diff rendered by git diff with delta as pager. If delta is unavailable, it falls back to git's own color output.

func DiffUntrackedPath

func DiffUntrackedPath(worktreeRoot, path string, color bool, sideBySide bool, renderWidth int, contextLines int) (string, error)

DiffUntrackedPath returns a /dev/null -> file patch for an untracked path. Plain output is returned when color is false; otherwise output is rendered by git diff with delta as pager where possible.

func DiscardUntrackedPath

func DiscardUntrackedPath(worktreeRoot, relPath string) error

DiscardUntrackedPath removes an untracked path from the working tree.

func ExtractPRURL

func ExtractPRURL(output string) string

ExtractPRURL scans git push output for a GitHub PR creation URL. Git prefixes remote messages with "remote: ", so we strip that first.

func Fetch

func Fetch(repoRoot, remote string) error

Fetch runs `git fetch <remote>` in repoRoot.

func FixFetchConfig

func FixFetchConfig(repoRoot string) error

FixFetchConfig corrects the origin fetch refspec and runs git fetch.

func HasUnstagedChanges added in v0.14.5

func HasUnstagedChanges(root string) (bool, error)

HasUnstagedChanges reports whether there are tracked working-tree changes not yet in the index.

func IsCommitPushed added in v0.14.5

func IsCommitPushed(root, hash string) (bool, error)

IsCommitPushed reports whether hash appears in any remote tracking branch.

func IsHEAD added in v0.14.5

func IsHEAD(root, hash string) (bool, error)

IsHEAD reports whether hash resolves to the current HEAD commit.

func IsLocalBranch added in v0.15.4

func IsLocalBranch(repoRoot, ref string) bool

func IsNonFastForwardPushError

func IsNonFastForwardPushError(err error) bool

IsNonFastForwardPushError returns true when err matches a rejected push that can be resolved with a force push.

func IsRebasedOnMain

func IsRebasedOnMain(repo Repo, branch string) (bool, error)

IsRebasedOnMain reports whether branch is rebased on top of repo.MainBranch, i.e. whether the main branch tip is an ancestor of branch. Returns true when branch IS main (nothing to rebase) or when no main branch is detected.

func LastTag added in v0.15.1

func LastTag(root string) string

LastTag returns the most recent tag reachable from HEAD, or "v0.0.0" if none.

func ListRemotes

func ListRemotes(repo Repo) ([]string, error)

ListRemotes returns the names of all configured remotes.

func MoveWorktree

func MoveWorktree(repo Repo, from, to string) error

MoveWorktree moves a worktree from one path to another.

func NonInteractiveEnv

func NonInteractiveEnv() []string

func ParseVersion added in v0.15.1

func ParseVersion(tag string) (major, minor, patch int, err error)

ParseVersion parses "vMAJOR.MINOR.PATCH" into its integer components.

func PruneAllRemotes

func PruneAllRemotes(repo Repo) error

PruneAllRemotes prunes all configured remotes.

func PruneRemote

func PruneRemote(repo Repo, remote string) error

PruneRemote removes remote-tracking references for deleted remote branches.

func Pull

func Pull(worktreePath string) (string, error)

Pull fetches and integrates changes from the remote into the worktree and returns the combined output.

func Push

func Push(worktreePath, remote, branch string) error

Push uploads local branch commits to the remote using an explicit "git push <remote> <branch>" invocation.

func PushBranch

func PushBranch(worktreePath, remote, branch string) (prURL, output string, err error)

PushBranch pushes branch to remote and returns any PR creation URL found in the git output (e.g. the GitHub "Create a pull request" link), or "" if none. It also returns the combined output for display.

func PushBranchForce

func PushBranchForce(worktreePath, remote, branch string) (string, error)

PushBranchForce force-pushes branch using --force and returns the combined output.

func PushBranchForceWithLease

func PushBranchForceWithLease(worktreePath, remote, branch string) error

PushBranchForceWithLease force-pushes branch using --force-with-lease.

func PushOrigin added in v0.15.1

func PushOrigin(root string) error

PushOrigin pushes the current branch to origin.

func PushTag added in v0.15.1

func PushTag(root, tag string) error

PushTag pushes a specific tag to origin.

func Rebase

func Rebase(dir string, onto string) (string, error)

Rebase rebases the current branch onto the given ref.

func RebaseAutosquash added in v0.14.5

func RebaseAutosquash(root, hash string) (string, error)

RebaseAutosquash performs a non-interactive autosquash rebase from hash^ onward.

func RemoteDefaultBranch

func RemoteDefaultBranch(repoRoot string) string

RemoteDefaultBranch returns the repository's default branch using origin/HEAD when available, then falls back to local branch checks.

func RemoveWorktree

func RemoveWorktree(repo Repo, name string, force bool) error

RemoveWorktree removes a worktree by name or path.

func RenameBranch

func RenameBranch(repo Repo, oldName, newName string) error

RenameBranch renames a local branch from oldName to newName.

func ResolveCommitish added in v0.12.10

func ResolveCommitish(repoRoot, ref string) (string, error)

func RestorePaths

func RestorePaths(worktreeRoot string, paths []string) error

RestorePaths restores the given paths in both index and worktree from HEAD.

func RewordCommit added in v0.14.6

func RewordCommit(root, hash, message string) (string, error)

RewordCommit rewrites the message of an arbitrary non-HEAD commit via interactive rebase. --autostash handles both staged and unstaged working-tree changes automatically.

func RewordHead added in v0.14.6

func RewordHead(root, message string) (string, error)

RewordHead amends the HEAD commit message only, leaving any staged content untouched.

func StageIntentPath

func StageIntentPath(worktreeRoot, path string) error

StageIntentPath records an intent-to-add entry without adding content.

func StagePath

func StagePath(worktreeRoot, path string) error

StagePath stages a full path (used for untracked files).

func StagedFiles added in v0.14.5

func StagedFiles(root string) ([]string, error)

StagedFiles returns the paths of files with staged index changes.

func Stash

func Stash(dir string) (string, error)

Stash saves the dirty state of the working directory onto the stash stack.

func StashPop

func StashPop(dir string) (string, error)

StashPop applies the most recent stash and removes it from the stash stack.

func StashPushAuto added in v0.14.5

func StashPushAuto(root string) (string, error)

StashPushAuto stashes all tracked working-tree changes plus untracked files.

func TrackRemote

func TrackRemote(repoRoot, remote, branch string) error

TrackRemote configures an existing branch to track <remote>/<branch>.

func UnstagePath

func UnstagePath(worktreeRoot, path string) error

UnstagePath removes path changes from the index while preserving worktree edits.

func UpdateRemotes

func UpdateRemotes(repo Repo) (string, error)

UpdateRemotes fetches updates from all remotes and returns their combined output.

func UpstreamBranch

func UpstreamBranch(repoRoot, branch string) string

UpstreamBranch returns the upstream tracking ref (e.g. "origin/feature") for a local branch. It first checks the configured tracking branch, then falls back to "origin/<branch>" if that ref exists. Returns "" if neither applies.

func WorktreeRoot

func WorktreeRoot(dir string) (string, error)

WorktreeRoot resolves dir to the root of the current non-bare worktree.

Types

type Branch

type Branch struct {
	Name       string
	GitName    string // as passed to git commands (e.g. "origin/main" for remote)
	RemoteName string // non-empty for remote branches
	IsRemote   bool
}

Branch represents a local or remote git branch.

func ListBranches

func ListBranches(repo Repo) ([]Branch, error)

ListBranches returns all local and remote branches, excluding HEAD pointers.

type BranchHistoryClass added in v0.12.5

type BranchHistoryClass string
const (
	BranchHistoryShared     BranchHistoryClass = "shared"
	BranchHistoryLocalOnly  BranchHistoryClass = "local_only"
	BranchHistoryRemoteOnly BranchHistoryClass = "remote_only"
)

type BranchHistoryCommit added in v0.12.5

type BranchHistoryCommit struct {
	Commit
	Class BranchHistoryClass
}

func BranchHistorySinceMain added in v0.12.5

func BranchHistorySinceMain(repo Repo, branch, upstreamRef string) ([]BranchHistoryCommit, error)

BranchHistorySinceMain returns branch history since the repo's remote mainline ref (for example origin/main or origin/master) when available.

type Change

type Change struct {
	Kind ChangeKind
	Path string
}

Change represents a single file change reported by git status.

func UncommittedChanges

func UncommittedChanges(worktreePath string) ([]Change, error)

UncommittedChanges returns modified, added, deleted, and untracked files in the worktree at the given path.

type ChangeKind

type ChangeKind string

ChangeKind classifies a file change in the working tree.

const (
	ChangeModified  ChangeKind = "M"
	ChangeAdded     ChangeKind = "A"
	ChangeDeleted   ChangeKind = "D"
	ChangeRenamed   ChangeKind = "R"
	ChangeUntracked ChangeKind = "?"
)

type Commit

type Commit struct {
	FullHash string
	Hash     string
	Subject  string
	Date     time.Time
}

Commit is a single git commit with abbreviated hash and subject line.

func CommitsBehindMain

func CommitsBehindMain(repo Repo, branch string) ([]Commit, error)

CommitsBehindMain returns commits on main that are not reachable from branch, ordered newest first.

func CommitsBetween

func CommitsBetween(repo Repo, fromRef, toRef string) ([]Commit, error)

CommitsBetween returns commits reachable from toRef but not fromRef, ordered newest first.

func CommitsSinceMain

func CommitsSinceMain(repo Repo, branch string) ([]Commit, error)

CommitsSinceMain returns commits on branch that are not reachable from the repo's local main branch, ordered newest first.

func HeadCommit

func HeadCommit(repoRoot, branch string) (Commit, error)

HeadCommit returns the latest commit on the given branch.

type CommitDetails added in v0.12.11

type CommitDetails struct {
	FullHash    string
	Hash        string
	AuthorName  string
	AuthorShort string
	Subject     string
	Body        string
	Date        time.Time
	Decorations []RefDecoration
}

func CommitDetailsForRef added in v0.12.11

func CommitDetailsForRef(repoRoot, ref string) (CommitDetails, error)

type CommitFile added in v0.13.0

type CommitFile struct {
	Status     string
	Path       string
	RenameFrom string
}

func CommitFilesForRef added in v0.13.0

func CommitFilesForRef(repoRoot, ref string) ([]CommitFile, error)

type CommitInfo

type CommitInfo struct {
	Hash    string
	Message string
	Date    time.Time
}

type DirInfo

type DirInfo struct {
	Repo           Repo
	WorktreeRoot   string // non-empty when inside a linked worktree
	IsRepoRoot     bool
	IsWorktreeRoot bool
}

DirInfo describes what kind of git context a directory is in.

func IdentifyDir

func IdentifyDir(dir string) (*DirInfo, error)

IdentifyDir returns context about the directory: which repo it belongs to, whether it's a worktree root, etc.

type FetchConfigProblem

type FetchConfigProblem struct {
	Description string
	Commands    []string
}

FetchConfigProblem describes a misconfigured origin fetch setup and the commands needed to fix it.

func CheckFetchConfig

func CheckFetchConfig(repoRoot string) *FetchConfigProblem

CheckFetchConfig checks whether origin is configured to populate refs/remotes/origin/* and that those refs exist. Returns nil if everything looks fine, or a FetchConfigProblem describing what to fix.

type Issue

type Issue struct {
	Description    string
	FixDescription string
	// contains filtered or unexported fields
}

Issue represents a problem found by the doctor check.

func CheckRepo

func CheckRepo(repo Repo) ([]Issue, error)

CheckRepo runs all health checks on repo and returns any issues found.

func (Issue) CanFix

func (i Issue) CanFix() bool

CanFix reports whether an automatic fix is available for this issue.

func (Issue) Fix

func (i Issue) Fix() error

Fix applies the automatic fix.

type LogEntry added in v0.12.10

type LogEntry struct {
	FullHash    string
	Hash        string
	AuthorName  string
	AuthorShort string
	Subject     string
	Date        time.Time
	Graph       string
	Decorations []RefDecoration
}

func LogEntries added in v0.12.10

func LogEntries(repoRoot, startRef string, limit int) ([]LogEntry, error)

func LogEntriesFiltered added in v0.15.4

func LogEntriesFiltered(repoRoot, startRef string, limit int, filter LogFilter) ([]LogEntry, error)

type LogFilter added in v0.15.4

type LogFilter struct {
	Path      string
	StartLine int // 0 = file-only (no -L)
	EndLine   int
}

LogFilter restricts a log query to a file path or a line range within a file.

func (LogFilter) IsActive added in v0.15.4

func (f LogFilter) IsActive() bool

type PushDivergence

type PushDivergence struct {
	Branch     string
	Remote     string
	Upstream   string
	Local      CommitInfo
	RemoteHead CommitInfo
}

func DetectPushDivergence

func DetectPushDivergence(worktreePath, branch string) (*PushDivergence, error)

DetectPushDivergence fetches origin when an upstream branch exists and reports divergence between local branch and its upstream.

func DetectPushDivergenceAfterFetch

func DetectPushDivergenceAfterFetch(worktreePath, branch string) (*PushDivergence, error)

type RefDecoration added in v0.12.10

type RefDecoration struct {
	Name string
	Kind RefDecorationKind
}

type RefDecorationKind added in v0.12.10

type RefDecorationKind string
const (
	RefDecorationLocalBranch  RefDecorationKind = "local_branch"
	RefDecorationRemoteBranch RefDecorationKind = "remote_branch"
	RefDecorationTag          RefDecorationKind = "tag"
)

type Repo

type Repo struct {
	Root        string
	WorktreeDir string // directory where linked worktrees live; if empty, defaults to Root
	IsBare      bool
	MainBranch  string // "main" or "master"
}

Repo represents a git repository.

func FindRepo

func FindRepo(dir string) (*Repo, error)

FindRepo walks up from dir to find a git repository.

func (Repo) LinkedWorktreeDir

func (r Repo) LinkedWorktreeDir() string

LinkedWorktreeDir returns the directory where linked worktrees are created. For normal bare repos this is the same as Root; for .bare repos it is the parent directory that contains both .bare/ and the worktrees.

type RunError

type RunError struct {
	Args   []string
	Dir    string
	Stdout string
	Stderr string
	Code   int
}

RunError is returned when a git command exits with a non-zero status.

func (*RunError) Error

func (e *RunError) Error() string

type StageFileStatus

type StageFileStatus struct {
	Path         string
	RenameFrom   string
	IndexStatus  byte
	WorktreeCode byte
}

StageFileStatus represents one file entry from git status porcelain output.

func ListStageFiles

func ListStageFiles(worktreeRoot string) ([]StageFileStatus, error)

ListStageFiles returns status entries suitable for an interactive staging UI.

func (StageFileStatus) HasStagedChanges

func (s StageFileStatus) HasStagedChanges() bool

func (StageFileStatus) HasUnstagedChanges

func (s StageFileStatus) HasUnstagedChanges() bool

func (StageFileStatus) IsRenamed

func (s StageFileStatus) IsRenamed() bool

func (StageFileStatus) IsUntracked

func (s StageFileStatus) IsUntracked() bool

func (StageFileStatus) XY

func (s StageFileStatus) XY() string

XY returns the two-character porcelain status code.

type SyncStatus

type SyncStatus struct {
	Name   SyncStatusName
	Ahead  int // commits the local branch has that upstream doesn't
	Behind int // commits upstream has that the local branch doesn't
}

SyncStatus holds the sync relationship between a local branch and a reference.

func BranchSyncStatusAgainstRef

func BranchSyncStatusAgainstRef(repoRoot, localRef, remoteRef string) (SyncStatus, error)

BranchSyncStatusAgainstRef compares a local branch/ref against an explicit remote reference (for example: branch vs origin/main).

func WorktreeSyncStatus

func WorktreeSyncStatus(repo Repo, branch string) (SyncStatus, error)

WorktreeSyncStatus returns the sync status of a worktree branch compared to its upstream remote tracking branch. Returns StatusUnknown if no upstream is configured.

func (SyncStatus) Pretty

func (s SyncStatus) Pretty() string

Pretty returns a human-readable summary of the sync status.

type SyncStatusName

type SyncStatusName string

SyncStatusName describes the relationship between a branch and its upstream.

const (
	StatusSame     SyncStatusName = "same"
	StatusAhead    SyncStatusName = "ahead"
	StatusBehind   SyncStatusName = "behind"
	StatusDiverged SyncStatusName = "diverged"
	StatusUnknown  SyncStatusName = "unknown"
)

type Worktree

type Worktree struct {
	Path       string
	Name       string // path relative to the repo root
	Branch     string // short branch name, empty if detached
	Head       string // commit hash
	IsDetached bool
	IsBare     bool
}

Worktree represents a git worktree.

func ListWorktrees

func ListWorktrees(repo Repo) ([]Worktree, error)

ListWorktrees returns all linked worktrees for the repo (excludes the bare root).

Jump to

Keyboard shortcuts

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