Help us shape the future of Go! Take the 2026 Go Developer Survey

git

package
v0.19.0 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package git shells out to the git binary — status, staging, diff, commit, branches, push/pull. No library dependency; slow calls (push/pull) are the caller's job to run off the UI thread (a tea.Cmd goroutine).

Index

Constants

View Source
const (
	SignNone = byte(0)
	SignAdd  = byte('a')
	SignMod  = byte('m')
	SignDel  = byte('d') // lines were deleted just below this line
)

Gutter sign values produced by LineSigns.

View Source
const MaxChangedFiles = 200

MaxChangedFiles caps ChangedSince: an agent that touches more than this is not being reviewed hunk by hunk anyway.

Variables

This section is empty.

Functions

func Align

func Align(oldB, newB []byte) (signs []byte, oldFor []int)

Align diffs old→new content. It returns one sign per new line plus, for each new line, the old line it corresponds to (-1 for added/modified lines) — the mapping blame needs to survive unsaved edits. Common prefix/suffix are trimmed first, so the Myers pass only sees the edited region — typical cost is O(changed lines), not O(file).

func Amend added in v0.11.0

func Amend(top, msg string) (string, error)

Amend rewrites HEAD with whatever is staged and a new message.

func AmendNoEdit added in v0.11.0

func AmendNoEdit(top string) (string, error)

AmendNoEdit rewrites HEAD with the staged changes, keeping its message — the "forgot a file" amend, and the only way a multi-line message survives.

func ApplyHunks added in v0.19.0

func ApplyHunks(old []byte, hunks []Hunk) []byte

ApplyHunks builds the content that results from applying a subset of a file's hunks to its old content — what `git add -p` stages when you say yes to some hunks and no to others. Hunks come from one diff, so they don't overlap and are ordered by OldStart.

func ChangedPaths added in v0.19.0

func ChangedPaths(top, a, b string) (map[string]bool, error)

ChangedPaths lists the paths that differ between two tree-ish objects.

func Checkout

func Checkout(top, name string) error

func CheckoutRemote added in v0.8.0

func CheckoutRemote(top, ref string) (string, error)

CheckoutRemote creates a local branch tracking the remote ref and switches to it (origin/foo → foo). Returns the local name.

func Checkpoint added in v0.19.0

func Checkpoint(top string) (string, error)

Checkpoint snapshots the working tree and returns the checkpoint's commit SHA. Author identity is fixed so it works in repos with no user.name configured.

func Commit

func Commit(top, msg string) (string, error)

func CreateBranch

func CreateBranch(top, name string) error

func Diff

func Diff(top, path string, staged bool) (string, error)

Diff returns the unified diff for one path. Untracked files diff against /dev/null (git exits 1 there by design — the output is still the diff).

func DiffUntracked

func DiffUntracked(top, path string) string

func Fetch added in v0.3.2

func Fetch(top string) (string, error)

Fetch updates remote-tracking refs so ahead/behind counts are current.

func HasUpstream added in v0.11.0

func HasUpstream(top string) bool

HasUpstream reports whether the current branch tracks a remote branch.

func HeadSummary added in v0.6.0

func HeadSummary(top string) (string, error)

HeadSummary returns "abc1234 subject" for HEAD; errors before the first commit.

func LastCheckpoint added in v0.19.0

func LastCheckpoint(top string) string

LastCheckpoint returns the checkpoint ref's SHA, "" when none exists.

func LastCommitMsg added in v0.11.0

func LastCommitMsg(top string) string

LastCommitMsg returns HEAD's full commit message ("" when no commits).

func LineSigns

func LineSigns(oldB, newB []byte) []byte

LineSigns diffs old→new content and returns one sign per new line.

func MergeMsg added in v0.8.0

func MergeMsg(top string) string

MergeMsg returns the first line of git's prepared merge message (.git/MERGE_MSG), or "" — the commit prompt's prefill mid-merge.

func Pull

func Pull(top string) (string, error)

Pull merges by default: git ≥2.27 refuses to pull divergent branches until a reconciliation strategy is configured, erroring with a hint instead of merging — which also means no conflict state to resolve. A user-configured pull.rebase / pull.ff is respected.

func Push

func Push(top string) (string, error)

Push pushes the current branch; a branch with no upstream is published (push -u origin HEAD) instead of failing.

func PushForce added in v0.11.0

func PushForce(top string) (string, error)

PushForce force-pushes with lease: it refuses if the remote moved past what we last fetched. The safe force after rebasing or amending commits that were already pushed.

func Rebase added in v0.11.0

func Rebase(top, ref string) (string, error)

Rebase replays the current branch onto ref ("main", "origin/main", …). --autostash carries uncommitted work across the rebase — the everyday "sync before I commit" case; on conflict git parks it in a stash and says so in the output.

func ResolveOurs added in v0.8.0

func ResolveOurs(top, path string) error

ResolveOurs / ResolveTheirs settle a conflicted path by taking one side wholesale and staging the result. Hand-edited conflicts just get staged (Stage marks a conflict resolved on its own).

func ResolveTheirs added in v0.8.0

func ResolveTheirs(top, path string) error

func Restore

func Restore(top, path string) error

Restore discards a tracked file's staged and unstaged changes, restoring it to its HEAD content.

func Show

func Show(top, path string) ([]byte, error)

Show returns a file's content at HEAD (path repo-relative, slash-separated). Raw bytes — no trimming, file content must round-trip exactly.

func ShowAt added in v0.19.0

func ShowAt(top, rev, path string) ([]byte, error)

ShowAt returns a file's content at rev (path repo-relative, slash form).

func ShowCommit added in v0.6.0

func ShowCommit(top, sha string) (string, error)

ShowCommit returns a commit's message, stat, and full diff (`git show`).

func ShowIndex added in v0.15.0

func ShowIndex(top, path string) ([]byte, error)

ShowIndex returns a file's content in the index (the staged version).

func Stage

func Stage(top, path string) error

func StageAll

func StageAll(top string) error

func StageContent added in v0.19.0

func StageContent(top, path string, content []byte) error

StageContent writes content into the index for path (repo-relative, slash form), whatever the index held before. The mode follows the worktree file's executable bit.

func StagePath added in v0.19.0

func StagePath(top, path string) error

StagePath stages a path's worktree state: its content, or its deletion.

func Stash added in v0.11.0

func Stash(top string) (string, error)

Stash shelves all working-tree changes; -u includes untracked files, which is what "stash everything" means to anyone not steeped in git.

func StashFile added in v0.11.0

func StashFile(top, path string) (string, error)

StashFile shelves one file's changes ("--" keeps odd names from reading as flags). Per-hunk stashing (stash -p) is interactive-only — terminal job.

func StashPop added in v0.11.0

func StashPop(top string) (string, error)

StashPop restores the most recent stash and drops it on success.

func Top

func Top(dir string) (string, error)

Top resolves the repo's top-level directory; errors when dir is not inside a git work tree.

func TreeOf added in v0.19.0

func TreeOf(top, rev string) (string, error)

TreeOf returns the tree SHA a commit (or tree) resolves to.

func UndoCommit added in v0.6.0

func UndoCommit(top string) error

UndoCommit un-commits HEAD (reset --soft HEAD~1): the commit's changes return to the index, the working tree is untouched. Fails on the initial commit (no parent to reset to).

func Unstage

func Unstage(top, path string) error

Unstage falls back to rm --cached for repos with no commits yet (restore --staged needs a HEAD to restore from).

func UnstageAll

func UnstageAll(top string) error

func WorktreeTree added in v0.19.0

func WorktreeTree(top string) (string, error)

WorktreeTree writes the current working tree (untracked included) as a tree object and returns its SHA, without touching the index.

Types

type BlameLine

type BlameLine struct {
	SHA     string // short hash
	Author  string
	Time    int64 // author-time, unix seconds
	Summary string
}

BlameLine is the last commit that touched one line of the HEAD version.

func Blame

func Blame(top, path string) ([]BlameLine, error)

Blame runs `git blame --porcelain HEAD` and returns one entry per line of the file at HEAD. The caller maps buffer lines through Align's oldFor.

type Branch added in v0.8.0

type Branch struct {
	Name   string
	Remote bool
}

Branch is one pickable ref: a local branch, or a remote-tracking branch ("origin/foo") with no local counterpart.

func Branches

func Branches(top string) ([]Branch, error)

type FileDiff added in v0.19.0

type FileDiff struct {
	Path   string // repo-relative, slash-separated
	Status byte   // 'A' added, 'M' modified, 'D' deleted
	Binary bool
	Hunks  []Hunk
}

FileDiff is one changed file between two trees. Hunks is nil for added, deleted and binary files: the whole file is the change.

func ChangedSince added in v0.19.0

func ChangedSince(top, sha string) ([]FileDiff, error)

ChangedSince diffs the checkpoint commit against the current working tree (untracked files included), one FileDiff per changed path.

func DiffTrees added in v0.19.0

func DiffTrees(top, a, b string) ([]FileDiff, error)

DiffTrees diffs two tree-ish objects, one FileDiff per changed path.

type FileStatus

type FileStatus struct {
	Path        string // repo-top-relative
	Index, Work byte
}

FileStatus is one changed path from porcelain v2. Index/Work hold the XY letters ('.' = unchanged, '?' = untracked, '!' = conflict).

func (FileStatus) Conflict

func (f FileStatus) Conflict() bool

func (FileStatus) Staged

func (f FileStatus) Staged() bool

func (FileStatus) Unstaged

func (f FileStatus) Unstaged() bool

func (FileStatus) Untracked

func (f FileStatus) Untracked() bool

type GraphCommit added in v0.8.0

type GraphCommit struct {
	Hash, Short string
	Parents     []string // full hashes
	Refs        string   // %D decoration: "HEAD -> main, origin/main"; "" = none
	Subject     string
	Author      string
	Age         string // %ar relative time
}

GraphCommit is one commit for the app's custom graph view, which does its own lane layout (git's --graph output was the previous source; it spends extra rows shuffling lanes, unreadable with several branches).

func GraphLog added in v0.8.0

func GraphLog(top string, n int) ([]GraphCommit, error)

GraphLog returns all-branch history, newest first, topo-ordered (children always precede parents — the lane layout depends on it), capped at n.

type Hunk added in v0.19.0

type Hunk struct {
	OldStart, OldLines int // 1-based; OldLines may be 0 (pure insertion)
	NewStart, NewLines int
	Header             string // text after the @@ … @@ (enclosing function)
	Old, New           []string
	Added, Removed     int
	OldNoNL, NewNoNL   bool   // that side's last line has no trailing newline
	Text               string // the hunk as git printed it (header + prefixed lines)
}

Hunk is one change block of a unified diff. Old and New hold the full lines of each side (context included, no +/- prefix), so replacing the New range in the current file with Old reverts the hunk exactly.

func ParseHunks added in v0.19.0

func ParseHunks(patch string) []Hunk

ParseHunks extracts the hunks of a single-file unified diff.

func (Hunk) FirstChange added in v0.19.0

func (h Hunk) FirstChange() int

FirstChange is the 1-based line (in the new file) of the hunk's first changed line — past the leading context git adds around it. For a pure deletion it is the line the removed lines used to follow.

func (Hunk) Signature added in v0.19.0

func (h Hunk) Signature() string

Signature identifies a hunk's content, for remembering accepted hunks across recomputes; line numbers are left out so an accepted hunk stays accepted when an earlier hunk is reverted.

type LogEntry added in v0.6.0

type LogEntry struct {
	SHA     string // short hash
	Author  string
	Time    int64 // author-time, unix seconds
	Subject string
}

LogEntry is one `git log` commit line.

func Log added in v0.6.0

func Log(top string, n int) ([]LogEntry, error)

Log returns the most recent commits, newest first, capped at n. Empty (not an error) before the first commit.

type Snapshot

type Snapshot struct {
	Top           string // repo top-level dir, absolute
	Branch        string
	Oid           string // HEAD commit; changes on commit/checkout/pull
	Upstream      string
	Ahead, Behind int
	Merging       bool // MERGE_HEAD exists: a commit is needed to conclude
	Files         []FileStatus
}

Snapshot is everything the UI needs, produced by one Status call.

func Status

func Status(top string) (Snapshot, error)

Status parses `git status --porcelain=v2 --branch` into a Snapshot.

Jump to

Keyboard shortcuts

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