git

package
v0.152.1 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 14 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const BackupRefPrefix = "refs/gk/backup"

BackupRefPrefix is the namespace under which gk stores history-rewriting safety nets. Each ref is `refs/gk/backup/<branch>/<unix-ts>` and points at the pre-rewrite tip of <branch>. Recovery: `git reset --hard <ref>` or `git branch <name> <ref>`.

Variables

View Source
var ErrDetachedHEAD = fmt.Errorf("detached HEAD")

ErrDetachedHEAD is returned by CurrentBranch when HEAD is detached.

View Source
var ErrNoDefaultBranch = fmt.Errorf("could not determine default branch")

ErrNoDefaultBranch is returned when no default branch can be determined.

View Source
var ExecHook func(args []string, dur time.Duration, err error)

ExecHook, when non-nil, is invoked after every ExecRunner.Run with the git args, wall-clock duration, and final error. Intended for debug logging from higher layers (cli/root.go wires it to Dbg) so the git package does not import cli. Captured args start at the first non-boilerplate token — the internal `-c core.quotepath=false` guard is elided so the log reads like the git command the user actually asked for.

Functions

func IsExitCode added in v0.143.1

func IsExitCode(err error, code int) bool

IsExitCode reports whether err is a *git.ExitError with the given code. Used by GetBranchConfig/UnsetBranchConfig to distinguish "missing key" (a normal state) from real failures. The runner wraps non-zero exits in our custom ExitError; raw os/exec errors come through unwrapped only on spawn failure (binary missing, etc.), which we want to surface either way.

func IsSubmoduleWorktreeDirtinessOnly

func IsSubmoduleWorktreeDirtinessOnly(xy, sub string) bool

IsSubmoduleWorktreeDirtinessOnly reports a submodule record that has no committable superproject gitlink change. Git reports nested tracked or untracked dirtiness as ".M S.M." / ".M S..U" even when the gitlink SHA is unchanged, so callers should render it separately from files that `git add` can stage in the superproject.

func RefExists

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

RefExists reports whether a ref resolves locally — used to test for cached remote-tracking refs (e.g. "refs/remotes/origin/main") without touching the network. Wraps `git rev-parse --verify --quiet <ref>`.

func TotalConflictLines

func TotalConflictLines(regions []ConflictRegion) int

TotalConflictLines is a convenience for renderers — sums the line counts on both sides across every region.

Types

type Client

type Client struct {
	R Runner
}

Client wraps a Runner and provides high-level, type-safe git operations.

func NewClient

func NewClient(r Runner) *Client

NewClient creates a Client backed by the given Runner.

func (*Client) AllBranchConfig

func (c *Client) AllBranchConfig(ctx context.Context, key string) (map[string]string, error)

AllBranchConfig reads `branch.<name>.<key>` for every branch in one `git config --get-regexp` call and returns a name→value map. List renderers (switch picker, worktree table) use this instead of N GetBranchConfig calls so the subprocess count stays flat on repos with hundreds of branches. Returns an empty map when no branch has the key (git exits 1 on no match — same contract as GetBranchConfig).

func (*Client) CheckRefFormat

func (c *Client) CheckRefFormat(ctx context.Context, ref string) error

CheckRefFormat validates a ref name via `git check-ref-format --branch <ref>`. Returns nil if valid; non-nil error otherwise.

func (*Client) CreateBackup

func (c *Client) CreateBackup(ctx context.Context, branch, sha string) (string, error)

CreateBackup writes a backup ref pointing to sha for branch and returns the ref name. The timestamp is encoded into the ref so multiple backups of the same branch don't collide.

func (*Client) CurrentBranch

func (c *Client) CurrentBranch(ctx context.Context) (string, error)

CurrentBranch returns the current branch name via `git symbolic-ref --short HEAD`. Returns ("", ErrDetachedHEAD) when HEAD is detached.

func (*Client) DefaultBranch

func (c *Client) DefaultBranch(ctx context.Context, remote string) (string, error)

DefaultBranch detects the base branch with the following fallback chain:

  1. git symbolic-ref --short refs/remotes/<remote>/HEAD (e.g. "origin/main" -> "main")
  2. git show-ref --verify --quiet refs/remotes/<remote>/develop
  3. git show-ref --verify --quiet refs/remotes/<remote>/main
  4. git show-ref --verify --quiet refs/remotes/<remote>/master

Returns ErrNoDefaultBranch if none exist.

func (*Client) Fetch

func (c *Client) Fetch(ctx context.Context, remote, ref string, prune bool) error

Fetch runs `git fetch <remote>` or `git fetch <remote> <ref>` if ref != "". prune=true adds --prune. If remote is empty, "origin" is used.

func (*Client) GetBranchConfig

func (c *Client) GetBranchConfig(ctx context.Context, branch, key string) (string, error)

GetBranchConfig reads `git config branch.<branch>.<key>`. Returns ("", nil) when the key is unset (git exits non-zero, but absence is not a programmer error here — callers treat empty as "not configured"). Other failures (broken config, runner error) propagate as a non-nil error.

The two-level distinction (unset vs error) is intentional: parent metadata is opt-in, so "no value" is the normal path on most branches and must not noise up logs. We detect "unset" via exit code 1 (git's documented signal for missing keys); anything else surfaces.

func (*Client) GitCommonDir

func (c *Client) GitCommonDir(ctx context.Context) (string, error)

GitCommonDir returns the common git directory via `git rev-parse --git-common-dir`. For worktrees this differs from GitDir.

func (*Client) GitDir

func (c *Client) GitDir(ctx context.Context) (string, error)

GitDir returns the `.git` directory path via `git rev-parse --git-dir`.

func (*Client) IsDirty

func (c *Client) IsDirty(ctx context.Context) (bool, error)

IsDirty returns true if any tracked changes exist (untracked files ignored). Uses `git status --porcelain=v1 -uno`.

func (*Client) LatestBackupRef

func (c *Client) LatestBackupRef(ctx context.Context, branch string) string

LatestBackupRef returns the most recent gk backup ref for branch, or "" when none exists. Caller can show this so the user knows where to jump back to via `git reset --hard <ref>` if they want to bail.

func (*Client) PruneBackups

func (c *Client) PruneBackups(ctx context.Context, branch string, maxAge time.Duration, keepRecent int) int

PruneBackups deletes backup refs for branch older than maxAge, while preserving the keepRecent newest ones regardless of age. Returns the number of refs deleted. Errors during enumeration or deletion are swallowed — pruning is best-effort and must never block a pull.

func (*Client) Raw

func (c *Client) Raw() Runner

Raw returns the underlying Runner for advanced callers.

func (*Client) RebaseConflictStatus

func (c *Client) RebaseConflictStatus(ctx context.Context) (*RebaseConflictInfo, error)

RebaseConflictStatus inspects the working tree and .git/ to describe a paused rebase. Returns (nil, nil) when no rebase is in progress. All git-side errors are tolerated — best-effort population so the caller can still print whatever fields it could collect.

func (*Client) RebaseOnto

func (c *Client) RebaseOnto(ctx context.Context, upstream string) (RebaseResult, error)

RebaseOnto runs `git rebase <upstream>` and returns a classified RebaseResult. Conflict cases return a nil error — callers should inspect the Conflict flag.

func (*Client) SetBranchConfig

func (c *Client) SetBranchConfig(ctx context.Context, branch, key, value string) error

SetBranchConfig writes `git config branch.<branch>.<key> <value>` to the local repo config. Overwrites any existing value. Empty value is allowed but discouraged — prefer UnsetBranchConfig for clearing.

func (*Client) Status

func (c *Client) Status(ctx context.Context) (*Status, error)

Status runs `git status --porcelain=v2 -z --branch` and returns parsed output.

func (*Client) UnsetBranchConfig

func (c *Client) UnsetBranchConfig(ctx context.Context, branch, key string) error

UnsetBranchConfig removes `branch.<branch>.<key>` via `git config --unset`. Returns nil when the key was already absent (idempotent), so callers can invoke this without first checking. Other errors propagate.

type ConflictLine

type ConflictLine struct {
	LineNum int
	Text    string
}

ConflictLine is one line from inside (or adjacent to) a conflict region. LineNum is 1-indexed.

type ConflictRegion

type ConflictRegion struct {
	StartMarkerLine int    // line carrying `<<<<<<<`
	MidMarkerLine   int    // line carrying `=======`
	EndMarkerLine   int    // line carrying `>>>>>>>`
	OursLabel       string // text after `<<<<<<<` (typically "HEAD")
	TheirsLabel     string // text after `>>>>>>>` (typically the commit subject or branch)

	Ours   []ConflictLine // content between Start and Mid markers (exclusive)
	Theirs []ConflictLine // content between Mid and End markers (exclusive)

	// ContextBefore/After carry one line of unchanged code surrounding
	// the region. They are nil at the very top/bottom of the file. The
	// renderer uses them to anchor the conflict in its surroundings so
	// the user can recognise where the change lives.
	ContextBefore *ConflictLine
	ContextAfter  *ConflictLine
}

ConflictRegion describes one git conflict block — a contiguous slice of a file delimited by `<<<<<<<`, `=======`, and `>>>>>>>` markers. Line numbers are 1-indexed and refer to the file as it sits on disk while the conflict is unresolved (so callers can quote them back to the user, e.g. "lines 188–200").

func ParseConflictMarkers

func ParseConflictMarkers(path string) ([]ConflictRegion, error)

ParseConflictMarkers reads path and returns one ConflictRegion per `<<<<<<<` … `=======` … `>>>>>>>` block found. Malformed regions (missing mid or end marker) are silently skipped — pre-existing markers in test fixtures or generated code shouldn't crash the renderer. Files larger than ~16MiB are truncated at the scanner's buffer; callers concerned with very large files should fall back to the simple "files with conflicts" listing.

type DirtyFlags

type DirtyFlags struct {
	Modified bool // tracked file changed in working tree (Y position)
	Staged   bool // index has changes (X position)
	Conflict bool // unmerged path (U in either position) — overrides
}

DirtyFlags summarizes uncommitted state of a worktree as classified from `git status --porcelain` output. Each flag is set when at least one path matches; the parser does not count occurrences.

func ParsePorcelainV1

func ParsePorcelainV1(raw []byte) DirtyFlags

ParsePorcelainV1 classifies `git status --porcelain[=v1] -z` output into DirtyFlags. Input is the raw stdout (entries are NUL-terminated when -z is used; the parser also handles newline-terminated output for callers that didn't pass -z). Untracked (`??`) and ignored (`!!`) entries are intentionally skipped — they're considered noise for the "branch has uncommitted work" signal.

Format reminder (porcelain v1):

XY <path>           (X=index, Y=working tree)
`R  old -> new`     (rename — X='R', Y=' ')
`?? path`           (untracked — skipped)
`UU path`           (unmerged — flagged as conflict)

func (DirtyFlags) Clean

func (d DirtyFlags) Clean() bool

Clean reports whether all flags are unset.

type ExecRunner

type ExecRunner struct {
	// Dir is the working directory for git commands.
	// Empty string means the current working directory.
	Dir string

	// ExtraEnv are additional environment variables appended after the forced
	// guard variables. These can override the guards if needed.
	ExtraEnv []string
}

ExecRunner implements Runner by invoking the system git binary.

func (*ExecRunner) Run

func (r *ExecRunner) Run(ctx context.Context, args ...string) (stdout, stderr []byte, err error)

Run executes `git <args...>` and returns captured stdout and stderr. Non-zero exit codes produce an *ExitError; stdout/stderr are still returned.

type ExitError

type ExitError struct {
	Code   int
	Args   []string
	Stderr string
}

ExitError wraps a non-zero git exit with its code.

func (*ExitError) Error

func (e *ExitError) Error() string

type FakeCall

type FakeCall struct {
	Args []string
}

FakeCall records a single invocation made to FakeRunner.

type FakeResponse

type FakeResponse struct {
	Stdout   string
	Stderr   string
	ExitCode int
	Err      error
}

FakeResponse defines the canned response returned by FakeRunner for a given call.

type FakeRunner

type FakeRunner struct {
	Responses   map[string]FakeResponse
	DefaultResp FakeResponse
	Calls       []FakeCall
	// contains filtered or unexported fields
}

FakeRunner implements Runner for use in tests. Responses are keyed by strings.Join(args, " "). When no key matches, DefaultResp is returned (zero value means exit 0 + empty output). All calls are appended to Calls for later assertion.

Run is safe to invoke from multiple goroutines: production runners (e.g. ExecRunner) are inherently safe because each call spawns a separate process, and tests started exercising parallel runner access in v0.39.1 (cross-worktree status hint). The mutex protects only the Calls append and Responses lookup; canned responses are expected to be set up before the first Run call.

func (*FakeRunner) Run

func (f *FakeRunner) Run(_ context.Context, args ...string) (stdout, stderr []byte, err error)

Run looks up args in Responses, falls back to DefaultResp, records the call, and returns an *ExitError when ExitCode != 0.

type RebaseConflictInfo

type RebaseConflictInfo struct {
	StoppedSHA  string   // SHA of the commit that stopped the rebase
	StoppedSubj string   // first-line subject of that commit
	Done        int      // picks completed (1-indexed; matches msgnum)
	Total       int      // total picks in the rebase plan
	Unmerged    []string // files still carrying conflict markers (XY=U*)
	Staged      []string // files already staged (auto-merged or resolved)
}

RebaseConflictInfo describes the state of a paused rebase. It is populated from .git/rebase-merge metadata plus a couple of cheap porcelain calls. Callers use it to render a richer error than git's terse "could not apply" — for example, the list of files that still have conflict markers, the commit currently being applied, and how far through the rebase we are.

func (*RebaseConflictInfo) Remaining

func (r *RebaseConflictInfo) Remaining() int

Remaining returns the number of picks left after the current one, or 0 when total is unknown.

type RebaseResult

type RebaseResult struct {
	Success   bool
	Conflict  bool // conflict occurred
	NothingTo bool // already up-to-date / nothing to do
	Stdout    string
	Stderr    string
}

RebaseResult holds the classified outcome of a rebase operation.

type Runner

type Runner interface {
	// Run executes `git <args...>` and returns captured stdout/stderr.
	// Non-zero exit codes produce a non-nil error; stdout/stderr are still returned.
	Run(ctx context.Context, args ...string) (stdout, stderr []byte, err error)
}

Runner executes git commands in a controlled environment. Implementations must ensure deterministic, locale-independent output.

type Status

type Status struct {
	Branch        string
	Upstream      string
	Ahead, Behind int
	Entries       []StatusEntry
}

Status holds parsed output of `git status --porcelain=v2 -z --branch`.

type StatusEntry

type StatusEntry struct {
	XY   string
	Sub  string // porcelain v2 submodule field, e.g. N... or S..U
	Path string
	Orig string // original path for renames
	Kind StatusKind
}

StatusEntry represents a single entry in `git status --porcelain=v2`.

type StatusKind

type StatusKind int

StatusKind classifies a status entry.

const (
	KindOrdinary StatusKind = iota
	KindRenamed
	KindUnmerged
	KindUntracked
	KindIgnored
	KindSubmodule
)

Jump to

Keyboard shortcuts

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