git

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: MIT Imports: 12 Imported by: 1 module, 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

Overview

Package git is a typed wrapper around the git command line. It shells out through pkg/exec; go-git is deliberately not used so behaviour matches the user's git exactly (hooks, config, worktrees, signing).

Index

Constants

View Source
const DefaultLockRetryBudget = 2 * time.Second

DefaultLockRetryBudget is how long git commands wait for a held index lock before giving up. IDEs and agents take the lock for milliseconds at a time while refreshing status, which is plenty to make a bare `git add` fail.

Variables

View Source
var ErrDetached = errors.New("HEAD is detached")

ErrDetached is returned when HEAD is not on a branch.

View Source
var ErrNotRepo = errors.New("not a git repository")

ErrNotRepo is returned by Discover outside a git repository.

Functions

This section is empty.

Types

type AddMode

type AddMode int

AddMode selects what `git add` stages.

const (
	// AddNone stages nothing.
	AddNone AddMode = iota
	// AddAll stages all changes including untracked files (git add -A).
	AddAll
	// AddUpdate stages changes to tracked files only (git add -u).
	AddUpdate
	// AddPatch stages hunks interactively (git add -p); needs a TTY.
	AddPatch
)

type Branch

type Branch struct {
	Name string
	// Head is the tip commit id.
	Head string
	// CommitTime is the committer date of the tip.
	CommitTime time.Time
	// Worktree is the path of the worktree the branch is checked out in, or
	// empty.
	Worktree string
	// Upstream is the tracking branch (e.g. origin/feat), or empty.
	Upstream string
}

Branch describes a local branch.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client runs git commands.

func New

func New(r exec.Runner, opts ...Option) *Client

New returns a Client that runs git through r.

func (*Client) Add

func (c *Client) Add(ctx context.Context, repo Repo, mode AddMode) error

Add stages changes according to mode.

func (*Client) AddedPaths added in v0.1.4

func (c *Client) AddedPaths(ctx context.Context, repo Repo, from, to string) ([]string, error)

AddedPaths lists the paths that exist in to's tree but not in from's.

func (*Client) BranchExists

func (c *Client) BranchExists(ctx context.Context, repo Repo, name string) (bool, error)

BranchExists reports whether a local branch exists.

func (*Client) Branches

func (c *Client) Branches(ctx context.Context, repo Repo) ([]Branch, error)

Branches lists local branches sorted by name.

func (*Client) CheckRefFormat

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

CheckRefFormat validates name as a branch name.

func (*Client) Commit

func (c *Client) Commit(ctx context.Context, repo Repo, o CommitOptions) (string, error)

Commit creates or amends a commit and returns the new HEAD id. When the editor must open (no message and not NoEdit, or Edit), the command runs in passthrough mode.

func (*Client) CommitInfo added in v0.1.4

func (c *Client) CommitInfo(ctx context.Context, repo Repo, rev string) (CommitInfo, error)

CommitInfo reads rev's author, message, tree and first parent.

func (*Client) CommitTree added in v0.1.4

func (c *Client) CommitTree(ctx context.Context, repo Repo, tree, parent string, info CommitInfo) (string, error)

CommitTree creates a commit of tree on parent with info's author, author date and message. The committer is the current user and signing follows the user's commit.gpgsign, as commit-tree honours both.

func (*Client) ConfigAdd

func (c *Client) ConfigAdd(ctx context.Context, repo Repo, scope Scope, key, value string) error

ConfigAdd appends a value to a multi-valued key.

func (*Client) ConfigGet

func (c *Client) ConfigGet(ctx context.Context, repo Repo, scope Scope, key string) (string, bool, error)

ConfigGet returns the value of key. The boolean reports whether it was set.

func (*Client) ConfigGetAll

func (c *Client) ConfigGetAll(ctx context.Context, repo Repo, scope Scope, key string) ([]string, error)

ConfigGetAll returns every value of a multi-valued key.

func (*Client) ConfigGetRegexp

func (c *Client) ConfigGetRegexp(ctx context.Context, repo Repo, scope Scope, re string) ([]ConfigEntry, error)

ConfigGetRegexp returns every entry whose key matches the regexp.

func (*Client) ConfigSet

func (c *Client) ConfigSet(ctx context.Context, repo Repo, scope Scope, key, value string) error

ConfigSet sets key to value, replacing existing values.

func (*Client) ConfigUnset

func (c *Client) ConfigUnset(ctx context.Context, repo Repo, scope Scope, key string) error

ConfigUnset removes every value of key. A missing key is not an error.

func (*Client) ConfigUnsetValue

func (c *Client) ConfigUnsetValue(ctx context.Context, repo Repo, scope Scope, key, value string) error

ConfigUnsetValue removes the values of key that match the given value (exact match). A missing key or value is not an error.

func (*Client) ConflictedFiles

func (c *Client) ConflictedFiles(ctx context.Context, repo Repo) ([]string, error)

ConflictedFiles lists paths with unresolved merge conflicts.

func (*Client) CountCommits

func (c *Client) CountCommits(ctx context.Context, repo Repo, from, to string) (int, error)

CountCommits returns the number of commits in from..to.

func (*Client) CreateBranch

func (c *Client) CreateBranch(ctx context.Context, repo Repo, name, start string) error

CreateBranch creates name at start without checking it out.

func (*Client) CurrentBranch

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

CurrentBranch returns the checked-out branch name.

func (*Client) DefaultBranch

func (c *Client) DefaultBranch(ctx context.Context, repo Repo) (string, bool, error)

DefaultBranch guesses the repository's trunk the way gh-stack does: the branch origin/HEAD points at, else a local main or master. The boolean is false when nothing matches.

func (*Client) DeleteBranch added in v0.1.4

func (c *Client) DeleteBranch(ctx context.Context, repo Repo, name string) error

DeleteBranch deletes a local branch whether or not it is merged. git refuses when the branch is checked out in any worktree; callers check.

func (*Client) DiffRange

func (c *Client) DiffRange(ctx context.Context, repo Repo, base, head string) (string, error)

DiffRange returns the diff between base and head (base...head semantics are not used: this is the exact tree difference, which is what a rebased branch shows against its parent).

func (*Client) Discover

func (c *Client) Discover(ctx context.Context, dir string) (Repo, error)

Discover resolves the repository containing dir.

func (*Client) Fetch added in v0.1.4

func (c *Client) Fetch(ctx context.Context, repo Repo, remote string) error

Fetch updates the remote-tracking refs of remote and prunes the ones whose branch is gone. Nothing local moves.

func (*Client) HasStagedChanges

func (c *Client) HasStagedChanges(ctx context.Context, repo Repo) (bool, error)

HasStagedChanges reports whether the index differs from HEAD.

func (*Client) HasUnstagedChanges

func (c *Client) HasUnstagedChanges(ctx context.Context, repo Repo) (bool, error)

HasUnstagedChanges reports whether the working tree has unstaged changes to tracked files.

func (*Client) HasUntrackedFiles

func (c *Client) HasUntrackedFiles(ctx context.Context, repo Repo) (bool, error)

HasUntrackedFiles reports whether untracked, non-ignored files exist.

func (*Client) IsAncestor

func (c *Client) IsAncestor(ctx context.Context, repo Repo, ancestor, descendant string) (bool, error)

IsAncestor reports whether ancestor is reachable from descendant.

func (*Client) ListCmds

func (c *Client) ListCmds(ctx context.Context, spec string) ([]string, error)

ListCmds returns `git --list-cmds=<spec>` (e.g. "builtins" or "main,others").

func (*Client) MergeBase added in v0.1.4

func (c *Client) MergeBase(ctx context.Context, repo Repo, a, b string) (string, error)

MergeBase returns the best common ancestor of a and b.

func (*Client) MergeFF added in v0.1.4

func (c *Client) MergeFF(ctx context.Context, repo Repo, rev string) error

MergeFF fast forwards the branch checked out in repo's worktree to rev and updates the tree. It refuses, changing nothing, when rev is not a descendant or a dirty file would be overwritten.

func (*Client) MergeTree added in v0.1.4

func (c *Client) MergeTree(ctx context.Context, repo Repo, base, ours, theirs string) (MergeTreeResult, error)

MergeTree merges ours and theirs with base as the common ancestor.

func (*Client) Messages

func (c *Client) Messages(ctx context.Context, repo Repo, from, to string) ([]string, error)

Messages returns the full commit messages in from..to, oldest first.

func (*Client) Passthrough

func (c *Client) Passthrough(ctx context.Context, repo Repo, args ...string) error

Passthrough runs git with the terminal attached (editors, `add -p`).

func (*Client) PatchIDs added in v0.1.4

func (c *Client) PatchIDs(ctx context.Context, repo Repo, from, to string) (map[string]string, error)

PatchIDs maps the patch id of every non merge commit in from..to to that commit, so two histories can be compared for the same changes regardless of where they were rebased. The ids are verbatim: unlike --stable they count whitespace, so a whitespace only amend is a different change.

func (*Client) PatchIDsExcluding added in v0.1.4

func (c *Client) PatchIDsExcluding(ctx context.Context, repo Repo, to string, exclude ...string) (map[string]string, error)

PatchIDsExcluding is PatchIDs for the commits reachable from to but from none of exclude.

func (*Client) RebaseInProgress

func (c *Client) RebaseInProgress(ctx context.Context, repo Repo) (bool, error)

RebaseInProgress reports whether git has a rebase in progress.

func (*Client) RemoteFor added in v0.1.4

func (c *Client) RemoteFor(ctx context.Context, repo Repo, branch string) string

RemoteFor is the remote a branch tracks (branch.<name>.remote), or origin when it tracks nothing.

func (*Client) Replay added in v0.1.4

func (c *Client) Replay(ctx context.Context, repo Repo, commits []string, onto string) (ReplayResult, error)

Replay recreates commits, oldest first, on top of onto. It never touches a working tree, the index or a ref: it only creates objects, so the caller decides what to do with Tip. A merge commit is replayed against its first parent, which linearises it. A commit whose changes are already in the new parent would come out empty and is dropped instead. A root commit is replayed with an empty merge base.

func (*Client) ResetHard added in v0.1.4

func (c *Client) ResetHard(ctx context.Context, repo Repo, rev string) error

ResetHard moves the checked out branch, the index and the tree to rev. git deletes an untracked file in the way of a tracked one; callers check with AddedPaths and Untracked first.

func (*Client) RevList added in v0.1.4

func (c *Client) RevList(ctx context.Context, repo Repo, from, to string) ([]string, error)

RevList lists the commits reachable from to but not from, oldest first.

func (*Client) RevParse

func (c *Client) RevParse(ctx context.Context, repo Repo, rev string) (string, error)

RevParse resolves rev to a full object id.

func (*Client) Runner

func (c *Client) Runner() exec.Runner

Runner exposes the underlying runner (used by adapters that run other tools with the same debug/TTY settings).

func (*Client) StagedDiff

func (c *Client) StagedDiff(ctx context.Context, repo Repo) (string, error)

StagedDiff returns the diff of the index against HEAD.

func (*Client) Subject

func (c *Client) Subject(ctx context.Context, repo Repo, rev string) (string, error)

Subject returns the first line of the commit message of rev.

func (*Client) Subjects

func (c *Client) Subjects(ctx context.Context, repo Repo, rev string, n int) ([]string, error)

Subjects returns the commit subjects of rev's history, newest first, at most n.

func (*Client) Switch

func (c *Client) Switch(ctx context.Context, repo Repo, name string) error

Switch checks out an existing branch.

func (*Client) SwitchDetached added in v0.1.1

func (c *Client) SwitchDetached(ctx context.Context, repo Repo, rev string) error

SwitchDetached checks out rev with a detached HEAD.

func (*Client) Tip added in v0.1.4

func (c *Client) Tip(ctx context.Context, repo Repo, ref string) (string, bool, error)

Tip resolves a full ref name (refs/heads/x, refs/remotes/origin/x) to a commit id. ok is false when the ref does not exist.

func (*Client) TreeOf added in v0.1.4

func (c *Client) TreeOf(ctx context.Context, repo Repo, rev string) (string, error)

TreeOf returns the tree of the commit rev.

func (*Client) Untracked added in v0.1.4

func (c *Client) Untracked(ctx context.Context, repo Repo) ([]string, error)

Untracked lists the untracked, non ignored files in repo's worktree, relative to its top level.

func (*Client) UpdateRefs added in v0.1.4

func (c *Client) UpdateRefs(ctx context.Context, repo Repo, updates []RefUpdate) error

UpdateRefs applies every update in one transaction: all move or none do.

func (*Client) Worktrees added in v0.1.1

func (c *Client) Worktrees(ctx context.Context, repo Repo) ([]Worktree, error)

Worktrees lists the main checkout and every linked worktree.

type CommitInfo added in v0.1.4

type CommitInfo struct {
	Author, Email string
	// Date is the author date in strict ISO 8601 (git's %aI).
	Date    string
	Message string
	Tree    string
	// Parent is the first parent, "" for a root commit.
	Parent string
}

CommitInfo is what it takes to recreate a commit somewhere else.

type CommitOptions

type CommitOptions struct {
	// Message paragraphs; each becomes a -m argument. Empty opens the editor
	// unless NoEdit is set.
	Message []string
	Amend   bool
	NoEdit  bool
	// Edit forces the editor even with a message (or when amending).
	Edit        bool
	ResetAuthor bool
	NoVerify    bool
	// AllowEmpty permits a commit with no changes.
	AllowEmpty bool
}

CommitOptions controls Commit.

type ConfigEntry

type ConfigEntry struct {
	Key   string
	Value string
}

ConfigEntry is one key/value pair.

type Conflict added in v0.1.4

type Conflict struct {
	Commit string
	Files  []string
}

Conflict is a commit that could not be replayed cleanly.

type MergeTreeResult added in v0.1.4

type MergeTreeResult struct {
	Tree      string
	Conflicts []string
}

MergeTreeResult is a three way merge computed without a working tree: the merged tree, and the conflicting paths when it was not clean (the tree then contains conflict markers and must not be committed).

type Option

type Option func(*Client)

Option configures a Client.

func WithLockRetry

func WithLockRetry(budget time.Duration, sleep func(context.Context, time.Duration) error) Option

WithLockRetry sets the retry budget for a held index lock and the function used to wait between attempts (tests pass a fake).

type RefUpdate added in v0.1.4

type RefUpdate struct {
	Ref, New, Old string
}

RefUpdate moves Ref to New. When Old is set the ref must currently be at Old, and the whole transaction fails if any Old is stale.

type ReplayResult added in v0.1.4

type ReplayResult struct {
	// Tip is the new tip (onto itself when there was nothing to replay), or
	// "" when Conflict is set.
	Tip string
	// Replayed counts the commits recreated.
	Replayed int
	// Skipped counts the commits dropped because their changes were already
	// in the new parent, as git rebase drops them.
	Skipped int
	// Conflict is set when the replay stopped; the commits before it were
	// recreated as unreferenced objects and nothing else happened.
	Conflict *Conflict
}

ReplayResult is what Replay produced.

type Repo

type Repo struct {
	// TopLevel is the working tree root.
	TopLevel string
	// GitDir is the repository directory for this worktree
	// (e.g. .git or .git/worktrees/<name>).
	GitDir string
	// CommonDir is the shared repository directory (.git of the main worktree).
	CommonDir string
}

Repo locates a repository. All paths are absolute.

func (Repo) IsLinkedWorktree

func (r Repo) IsLinkedWorktree() bool

IsLinkedWorktree reports whether the repo is a linked worktree.

type Scope

type Scope int

Scope selects which git config file an operation targets.

const (
	// ScopeMerged reads the effective value across all files (reads only).
	ScopeMerged Scope = iota
	// ScopeGlobal targets the user's global config.
	ScopeGlobal
	// ScopeLocal targets the repository config.
	ScopeLocal
)

type Worktree added in v0.1.1

type Worktree struct {
	// Path is the working tree root.
	Path string
	Head string
	// Branch is the checked out branch (short name), empty when detached or bare.
	Branch   string
	Detached bool
	Bare     bool
}

Worktree is one entry of `git worktree list`.

Directories

Path Synopsis
Package gittest creates isolated temporary repositories for tests.
Package gittest creates isolated temporary repositories for tests.

Jump to

Keyboard shortcuts

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