gitworkbench

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 24 Imported by: ? 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

Overview

[INPUT]: Git refs/heads and refs/remotes via Runner.Read; Git's branch validation and mutation semantics. [OUTPUT]: Branch/RemoteBranch models, local and remote-tracking ref discovery, safe switch/create. [POS]: Git domain reference boundary, read-only remote enumeration never contacts network. [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md

Package gitworkbench owns Solco's local Git review model: one command runner, repository facts, working-tree change snapshots, a clean-room patch parser, word diff, changed-file trees, commit transactions and branch switching. It supersedes internal/gitintel as the single Git cache.

Hard rules:

  • every Git invocation is argv-based through exec.CommandContext; never a shell string;
  • reads carry bounded time/output and never mutate;
  • mutations (add/commit/switch) are single-flight per repository root and run only on explicit user intent;
  • no automatic network fetch, no force, no reset --hard, no clean;
  • errors classify by operation class; stderr text stays in the returned error for the UI but is never logged with file/commit content by this package.

Index

Constants

View Source
const (
	RefHeadsPrefix   = "refs/heads/"
	RefRemotesPrefix = "refs/remotes/"
	RefTagsPrefix    = "refs/tags/"
)

Ref namespaces the graph reads. A hidden ref is always a full name.

View Source
const (
	OpKindDiscard         = "discard"
	OpKindDeleteUntracked = "delete-untracked"
	OpKindBranchDelete    = "branch-delete"
	OpKindStashDrop       = "stash-drop"
	OpKindStashClear      = "stash-clear"
	OpKindApplyPatch      = "apply-patch"
	OpKindResolveConflict = "resolve-conflict"

	OpStatusPending     = "pending"
	OpStatusSucceeded   = "succeeded"
	OpStatusFailed      = "failed"
	OpStatusInterrupted = "interrupted"
)

Operation kinds and states.

View Source
const (
	// ReadTimeout is the hard deadline for one read command.
	ReadTimeout = 5 * time.Second
	// MutateTimeout bounds one mutation (commit hooks may be slow).
	MutateTimeout = 30 * time.Second
	// MaxReadOutput bounds captured stdout of one read command.
	MaxReadOutput = 32 << 20 // 32 MiB
	// MaxSnapshotBytes is the whole-snapshot memory budget; a snapshot that
	// would exceed it degrades (TooLarge / Truncated), never freezes.
	MaxSnapshotBytes = 64 << 20 // 64 MiB
	// MaxPatchBytesPerFile bounds the rendered patch retained per file.
	MaxPatchBytesPerFile = 4 << 20 // 4 MiB
	// MaxUntrackedFiles bounds individually listed untracked entries.
	MaxUntrackedFiles = 1000
	// LargeDiffLines is the changed-line count (additions plus deletions)
	// past which a file's diff waits behind a Show button instead of being
	// read, parsed and drawn with the rest of the review.
	LargeDiffLines = 5000
	// MaxOnDemandPatchBytes bounds the diff of one file read when the user
	// opens it; past it the file is too large for the review.
	MaxOnDemandPatchBytes = 16 << 20 // 16 MiB
	// OnDemandTimeout is the deadline of that read.
	OnDemandTimeout = 20 * time.Second
)

Policy bounds for Git subprocess work (plan §13/§15/§35).

View Source
const (
	// MaxWordDiffRunes caps one input line's participation in word diffing.
	MaxWordDiffRunes = 2000
	// MaxWordDiffProduct caps tokensOld*tokensNew against pathological cost.
	MaxWordDiffProduct = 250000
	// MaxWordDiffRewriteRatio suppresses marks when lines are mostly
	// rewritten (noisy word marks on unrelated lines hurt review).
	MaxWordDiffRewriteRatio = 0.72
)

Word diff bounds (plan §18): presentation-only ranges, never Git authority.

View Source
const AutostashMessage = "Solco autostash"

AutostashMessage labels the temporary stash so a kept one is recognisable.

View Source
const MaxBlameLines = 5000

MaxBlameLines bounds one blame read.

View Source
const MaxCommitPromptBytes = maxCommitPreviewBytes

MaxCommitPromptBytes remains exported for callers that bound the legacy prompt. The canonical Preview path is always at or below this limit.

View Source
const MaxConflictBytes = 2 << 20

MaxConflictBytes bounds each version read for the conflict editor, and the result it writes back.

View Source
const MaxContextWindowBytes = 1 << 20 // 1 MiB

MaxContextWindowBytes bounds one context-expansion read.

View Source
const MaxGraphLimit = 20000

MaxGraphLimit is the largest window a graph read may ask for.

View Source
const MaxHistoryMove = 100

MaxHistoryMove bounds how far one move shifts a run.

View Source
const MaxPatchFileBytes = 8 << 20

MaxPatchFileBytes bounds a patch file Solco will apply.

View Source
const MaxPatchFiles = 500

MaxPatchFiles bounds how many files one operation selects from.

View Source
const MaxPushRefs = 200

MaxPushRefs bounds one multi-ref push.

View Source
const MaxRebaseCommits = 100

MaxRebaseCommits bounds a plan.

View Source
const (

	// MaxRecoveryBytes bounds what one recovery point keeps: past it the
	// destructive operation is refused instead of running with nothing to
	// come back to.
	MaxRecoveryBytes = 128 << 20
)
View Source
const MaxReflogEntries = 300

MaxReflogEntries bounds the reflog list.

View Source
const NetworkTimeout = 120 * time.Second

NetworkTimeout bounds one explicit network operation (fetch/pull/push).

View Source
const StaleAfter = 30 * time.Second

StaleAfter is the stale-while-refresh threshold.

Variables

View Source
var ErrStale = errors.New("review snapshot is stale: repository changed since review")

ErrStale is returned when the repository moved between review and commit; the UI must re-review, never auto-commit.

Functions

func BuildConflictResult added in v0.3.0

func BuildConflictResult(segs []ConflictSegment, choices []HunkChoice) string

BuildConflictResult joins the segments with one choice per hunk (a missing choice is ChoiceNone). Undecided hunks keep readable seven-character markers, which ResolveWith refuses to stage.

func CommitMessagePrompt

func CommitMessagePrompt(snap *ChangesSnapshot, selected []string) string

CommitMessagePrompt returns a privacy-preserving, metadata-only prompt. For explicitly approved code snippets, use PrepareCommitPrompt with opt-in. Deprecated: prefer PrepareCommitPrompt, which exposes privacy exclusions.

func EnsureAncestorsOpen

func EnsureAncestorsOpen(collapsed map[string]bool, path string)

EnsureAncestorsOpen clears the collapsed marks on every directory above path so a freshly selected file's row is visible.

func Explain

func Explain(err error) string

Explain says in one sentence why a Git network or merge command failed. It returns "" when err is not a Git failure with output to read.

func HasConflictMarkers added in v0.3.0

func HasConflictMarkers(text string) bool

HasConflictMarkers reports whether text still holds a conflict block (the check ResolveWith applies, for a button that should wait for it).

func IsGenerated

func IsGenerated(path string) bool

IsGenerated reports whether the path looks like generated/dependency output by the table above.

func LinePatch

func LinePatch(path string, h Hunk, selected map[int]bool, unstage bool) (string, bool)

LinePatch builds the patch that stages — or, with unstage, takes back out of the index — only the selected lines of one hunk of a tracked file's text change. It is `git add -p`'s edit: lines outside the selection stay as they are on the side the patch is applied to.

Stage: h is a hunk of index→worktree and the patch is applied to the index as it is. An unselected addition is left out; an unselected deletion stays as context (the index keeps the line).

Unstage: h is a hunk of HEAD→index and the patch is applied in reverse to the index. An unselected addition stays as context (the index keeps it); an unselected deletion is left out (the index stays without it).

selected holds indices into h.Lines; only additions and deletions count. It returns false when the selection holds no change line.

func LocalChangesBlocked

func LocalChangesBlocked(err error) bool

LocalChangesBlocked reports whether a Git failure is the refusal to touch the working tree because of local changes — the case "Stash and reapply" answers.

func MovedLines added in v0.3.0

func MovedLines(hunks []Hunk) map[[2]int]MovedLine

MovedLines finds the deleted lines of the hunks whose text, ignoring the surrounding whitespace, reappears as an added line elsewhere in the same file. A text counts only when it is unique among the deleted lines and among the added ones, so a repeated line is never guessed at; and the two ends must sit in different blocks of change (a deleted line directly followed by the same text added is an edit of the indentation, not a move). The keys are {hunk index, line index in Hunk.Lines}, like a pick in the diff.

func PatchLinesFor added in v0.3.0

func PatchLinesFor(src []PatchSourceLine, hunks []Hunk, picks map[[2]int]bool) ([]int, error)

PatchLinesFor turns a selection made on the diff the user sees (picks are {hunk, line index in Hunk.Lines}) into the PatchSourceLine indices RewriteWithPatch takes. The two diffs are read by different code, so every line is matched by kind and text first: a file whose two readings differ is refused (select it whole instead) rather than patched on a guess.

Types

type AmendBackend added in v0.3.0

type AmendBackend interface {
	AmendTo(ctx context.Context, root, commit string) error
}

AmendBackend implements AmendTo: the staged changes become part of the commit, and the commits above it are replayed. Runner has validated the operation, required staged changes only and an attached branch and holds the repository's lock; the Runner rolls a failure back.

type AutostashResult

type AutostashResult struct {
	// Stashed is false when there was nothing to put away.
	Stashed bool
	// Kept is true when the changes could not be reapplied (conflicts with the
	// action's result, or the action left the repository mid-operation) and
	// stay in the stash.
	Kept bool
}

AutostashResult says what became of the stashed changes.

type Backend added in v0.3.0

type Backend interface {
	// Name says which implementation this is, for logs and tests.
	Name() string
}

Backend is the marker of a second implementation of some Runner capabilities. A capability is a small interface below; the Runner method that owns it type-asserts Backend to that interface and, when the backend does not implement it, keeps running on the argv `git` path in this package. That is how capabilities move to the backend one group at a time (2026-11-12 decision) without a signature changing for the callers.

A backend is held to this package's policy, not to its own: argv only, GIT_TERMINAL_PROMPT=0, no pager, reads bounded by ReadTimeout and writes by MutateTimeout, output bounded by MaxReadOutput, failures returned as *Error (build one with NewError), no automatic fetch, no force, no clean. Single-flight per repository root stays with the Runner method that calls the backend (LockRepo), so a backend must not lock again.

type BlameLine

type BlameLine struct {
	Line    int
	Hash    string
	Short   string
	Author  string
	Time    time.Time
	Summary string
	Text    string
}

BlameLine is one line of a file with the commit that last wrote it.

type Branch

type Branch struct {
	Name      string
	Current   bool
	HeadShort string
	Upstream  string // what it tracks, "origin/main"; "" when nothing
}

Branch is one local branch of the repository (plan §23.1: local only in core 0.10; no remote management, no ahead/behind network calls).

type BranchBackend added in v0.3.0

type BranchBackend interface {
	ListBranches(ctx context.Context, root string) ([]Branch, error)
}

BranchBackend implements ListBranches. It returns the local branches sorted by name, without a detached HEAD pseudo-branch, exactly as the argv path does.

type Cache

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

Cache is the single per-process Git change cache, keyed by repo root. It supersedes internal/gitintel; no second Git cache may exist alongside.

func NewCache

func NewCache(runner *Runner) *Cache

NewCache builds the cache over one runner.

func (*Cache) Get

func (c *Cache) Get(root string) (*ChangesSnapshot, bool)

Get returns the cached snapshot and whether it is fresh enough to show without a refresh banner (StaleAfter since generation).

func (*Cache) Invalidate

func (c *Cache) Invalidate(root string)

Invalidate drops one root (after mutations the caller refreshes directly).

func (*Cache) NeedsRefresh

func (c *Cache) NeedsRefresh(root string) bool

NeedsRefresh reports whether a background refresh is worth starting.

func (*Cache) Refresh

func (c *Cache) Refresh(ctx context.Context, root string) (*ChangesSnapshot, error)

Refresh acquires a new snapshot for root. Concurrent refreshes of one root share one call; the loser waits and receives the same result. The snapshot always lands in the cache; callers must still verify Root/Signature match their current context before swapping visible state.

type ChangeFile

type ChangeFile struct {
	Path        string
	OldPath     string // rename/copy source
	Status      ChangeStatus
	Additions   int
	Deletions   int
	Binary      bool
	Generated   bool
	Deferred    bool // diff held back for its size: counts known, Patch/Hunks empty until ReadFileDiff
	TooLarge    bool // cannot be shown even on demand (untracked, past MaxOnDemandPatchBytes)
	Untracked   bool
	Fingerprint string
	Patch       []byte // parsed-model source; nil when Deferred/TooLarge/Binary
	Hunks       []Hunk
	Truncated   bool // patch retained below full size
	// Staged/Unstaged mark which sides of git's status carry the change,
	// driving the Stage/Unstage file actions. Both false for untracked.
	Staged   bool
	Unstaged bool
	// StagedHunks and UnstagedHunks are the per-side parses (HEAD vs index,
	// index vs worktree) behind the staged/unstaged split views; each nil
	// when that side carries no change or the side patch failed.
	StagedHunks   []Hunk
	UnstagedHunks []Hunk
}

ChangeFile models one changed path in the working tree (plan §16 model).

type ChangeStatus

type ChangeStatus string

ChangeStatus is the coarse working-tree change kind for one path.

const (
	StatusModified   ChangeStatus = "modified"
	StatusAdded      ChangeStatus = "added"
	StatusDeleted    ChangeStatus = "deleted"
	StatusRenamed    ChangeStatus = "renamed"
	StatusCopied     ChangeStatus = "copied"
	StatusTypeChange ChangeStatus = "typechange"
	StatusConflicted ChangeStatus = "conflicted"
	StatusUntracked  ChangeStatus = "untracked"
)

func (ChangeStatus) Letter

func (s ChangeStatus) Letter() string

Letter is the one-character status code used in tree rows (M/A/D/R/C/T/U/X).

type ChangesSnapshot

type ChangesSnapshot struct {
	Root      string
	Head      string
	Branch    string
	NoHead    bool
	Signature string
	Files     []ChangeFile
	DiffBase  string // revision the combined diffs compare: HEAD, the empty tree, or from..to of a commit

	TotalAdditions int
	TotalDeletions int

	// Truncated marks whole-snapshot degradation (untracked > 1000 or the
	// memory budget overflow); UI shows an explicit degraded note.
	Truncated          bool
	TruncatedUntracked int

	GeneratedAt time.Time
	Err         string
}

ChangesSnapshot is the immutable fact set for one repository root at one moment (plan §14/§21). Renders never recompute it; the cache owns refresh.

func (*ChangesSnapshot) ByPath

func (s *ChangesSnapshot) ByPath(path string) (ChangeFile, bool)

ByPath returns the change record for path, if present.

type CherryPickBackend added in v0.3.0

type CherryPickBackend interface {
	CherryPickCommits(ctx context.Context, root string, hashes []string) error
}

CherryPickBackend applies the commits to HEAD, oldest first. Runner has validated them (full hashes, no merges), required a clean tree and holds the lock. A stop on conflicts stays in progress, as with `git cherry-pick`.

type CommandEntry added in v0.3.0

type CommandEntry struct {
	Seq      uint64
	Time     int64 // unix nanoseconds, when the command finished
	Root     string
	Args     []string
	Class    OpClass
	Duration time.Duration
	ExitCode int      // 0 on success
	Failure  ErrClass // empty on success
}

CommandEntry is one finished Git command. Args is the argv after the executable, as run. The message of a commit and other stdin never appear: they travel by pipe, not by argv.

func (CommandEntry) Created added in v0.3.0

func (e CommandEntry) Created() time.Time

Created is the finish time.

func (CommandEntry) Failed added in v0.3.0

func (e CommandEntry) Failed() bool

Failed reports whether the command did not succeed.

func (CommandEntry) Line added in v0.3.0

func (e CommandEntry) Line() string

Line is the command as one shell-looking line, `git` first. It is for reading and copying; words with spaces are single-quoted.

type CommandLog added in v0.3.0

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

CommandLog keeps the last commands the Runner (and a Backend) ran. The zero value is not usable; make one with NewCommandLog. Safe for concurrent use.

func NewCommandLog added in v0.3.0

func NewCommandLog() *CommandLog

NewCommandLog returns an empty log. Install it with `runner.Commands = log` (and give the same one to the engine).

func (*CommandLog) Clear added in v0.3.0

func (l *CommandLog) Clear(root string)

Clear forgets every command of root.

func (*CommandLog) Entries added in v0.3.0

func (l *CommandLog) Entries(root string, withReads bool) []CommandEntry

Entries returns the commands run in root, newest first. Reads are left out unless withReads.

func (*CommandLog) Record added in v0.3.0

func (l *CommandLog) Record(e CommandEntry)

Record adds one finished command. A nil log ignores it, so call sites need no check. Seq is assigned here; Time defaults to now.

type CommitDraft

type CommitDraft struct {
	Subject string
	Body    string
	Paths   []string
	Amend   bool
	// NoVerify skips the pre-commit and commit-msg hooks (--no-verify);
	// SignOff appends a Signed-off-by trailer (-s). Both are per commit.
	NoVerify bool
	SignOff  bool
	// CoAuthors are "Name <email>" people who share the commit: each becomes a
	// Co-authored-by trailer. ResetAuthor (with Amend only) makes the amended
	// commit's author the current user and the time now (--reset-author).
	CoAuthors   []string
	ResetAuthor bool
}

CommitDraft is the user-authored commit intent (plan §22): subject required, body optional, selected paths only. No AI generation in 0.10. Amend replaces the last commit instead of adding one; the caller prefills the message from LastCommitMessage.

type CommitFilter added in v0.3.0

type CommitFilter struct {
	// Path keeps the commits that touched this file or folder (relative to the
	// repository root, taken literally).
	Path string
	// Since and Until are whole days, YYYY-MM-DD, both ends included; either may
	// be empty. They compare the commit date.
	Since, Until string
	// CurrentBranchOnly reads HEAD's history instead of every branch, remote and
	// tag the graph shows.
	CurrentBranchOnly bool
	// Hidden are the refs the graph hides; they stay hidden here too.
	Hidden []string
	Limit  int
}

CommitFilter is the Git-side query of the Commits list. The zero value asks for nothing but the graph's own scope.

func (CommitFilter) Active added in v0.3.0

func (f CommitFilter) Active() bool

Active says whether the filter narrows anything.

type CommitInfo

type CommitInfo struct {
	Hash    string // full hash
	Short   string
	Subject string
	Author  string
	Time    time.Time
	Parents []string // real Git ancestry for native graph projection
	// Refs are the refs that point at this commit (graph reads only).
	Refs []CommitRef
}

CommitInfo is one entry of the commit history.

type CommitPreflight

type CommitPreflight struct {
	Root      string
	Head      string
	Branch    string
	Signature string
	// Fingerprints maps each selected path to the ChangeFile fingerprint the
	// user reviewed (presentation cache identity).
	Fingerprints map[string]string
	// ContentIDs maps each selected path to its authoritative live content/object
	// identity (blob hash via git hash-object, "deleted", or symlink target).
	ContentIDs map[string]string
	// Untracked marks paths that must be `git add`ed before the pathspec
	// commit (untracked paths are invisible to `git commit -- <path>`).
	Untracked map[string]bool
}

CommitPreflight is the stale-state fence captured at Commit-surface open and revalidated immediately before mutation (plan §22.3).

type CommitPromptPreview

type CommitPromptPreview struct {
	Text          string
	IncludedFiles int
	ExcludedFiles int
	Truncated     bool
}

func PrepareCommitPrompt

func PrepareCommitPrompt(snapshot *ChangesSnapshot, selected []string, includeExcerpt bool) CommitPromptPreview

PrepareCommitPrompt defaults to statistics, not source code. The user may explicitly allow excerpts, but secrets/credentials/config paths are always excluded; sensitive entries never appear in the copied prompt.

type CommitRef

type CommitRef struct {
	Kind CommitRefKind
	Name string
	Full string
	Head bool // the checked-out branch ("HEAD -> name")
}

CommitRef is one ref pointing at a commit. Full is the whole name (the key a hide list uses); Name is the short form chips show.

type CommitRefKind

type CommitRefKind string

CommitRefKind says which namespace a decoration came from.

const (
	RefBranch CommitRefKind = "branch"
	RefRemote CommitRefKind = "remote"
	RefTag    CommitRefKind = "tag"
)

type CommitResult

type CommitResult struct {
	Hash      string
	Branch    string
	Committed []string
}

CommitResult is the verified outcome of one transaction.

type ConflictHunk added in v0.3.0

type ConflictHunk struct {
	Ours, Base, Theirs string
}

ConflictHunk is one region both sides changed. Each text keeps its line endings (a side that has no lines is "").

type ConflictSegment added in v0.3.0

type ConflictSegment struct {
	Text string
	Hunk *ConflictHunk
}

ConflictSegment is either text both sides agree on (Hunk nil) or a hunk.

func ParseConflictMarkers added in v0.3.0

func ParseConflictMarkers(merged string) ([]ConflictSegment, error)

ParseConflictMarkers cuts merge-file's --diff3 output (markers of conflictMarkerSize characters, labelled Current / Base / Incoming) into segments. Text that merely resembles a marker is kept as text.

type ConflictSide

type ConflictSide string

ConflictSide is which version of a conflicted file to keep.

const (
	// ConflictOurs keeps the current branch's version.
	ConflictOurs ConflictSide = "ours"
	// ConflictTheirs takes the incoming version.
	ConflictTheirs ConflictSide = "theirs"
	// ConflictMarked accepts the file as it is on disk (the user edited it).
	ConflictMarked ConflictSide = "marked"
)

type ConflictSides added in v0.3.0

type ConflictSides struct {
	Path               string
	Ours, Base, Theirs string
	Segments           []ConflictSegment
	// Editable is false when the file cannot be merged line by line; Reason
	// then says why, and the whole-file choices stay.
	Editable bool
	Reason   string
}

ConflictSides is what the editor shows for one unmerged file.

type CourierFile added in v0.3.0

type CourierFile struct {
	Path    string
	Added   int
	Removed int
}

CourierFile is one file a patch touches, with its line counts.

type CourierPreview added in v0.3.0

type CourierPreview struct {
	Clean   bool
	Files   []CourierFile
	Problem string
}

CourierPreview is what `git apply --check` says about a patch on a destination worktree. Clean is the only state that may be delivered; otherwise Problem says why, in Git's own words trimmed to the first lines.

type CourierSource added in v0.3.0

type CourierSource struct {
	Path    string
	OldPath string // a rename's source
	Commit  string // full hash; empty = the working tree
	Hunks   []Hunk
	Picks   map[[2]int]bool
}

CourierSource names what to send: one file's whole change or just the picked lines of it, from the working tree (Commit empty) or from one commit.

Picks are {hunk index, line index in Hunk.Lines} over Hunks, the diff the user picked on: for the working tree that is the side shown (index→worktree or HEAD→index), for a commit its own diff. A nil Picks is the whole file.

type DiffLine

type DiffLine struct {
	Kind      LineKind
	OldLine   int // 1-based; 0 for pure additions
	NewLine   int // 1-based; 0 for pure deletions
	Text      string
	NoNewline bool // "\ No newline at end of file" follows this line
}

DiffLine is one parsed line of a hunk (plan §16).

type ErrClass

type ErrClass string

ErrClass is a coarse, UI-safe classification of a Git failure.

const (
	ErrGitMissing     ErrClass = "git_missing"
	ErrNotARepo       ErrClass = "not_a_repo"
	ErrStaleState     ErrClass = "stale_state"
	ErrHookFailed     ErrClass = "hook_failed"
	ErrConflict       ErrClass = "conflict"
	ErrMergeInProgess ErrClass = "merge_in_progress"
	ErrRefusal        ErrClass = "git_refusal"
	ErrLocked         ErrClass = "index_locked"
	ErrTimeout        ErrClass = "timeout"
	ErrTooLarge       ErrClass = "too_large"
	ErrCancelled      ErrClass = "cancelled"
	ErrOther          ErrClass = "other"
)

func ClassifyStderr added in v0.3.0

func ClassifyStderr(stderr string) ErrClass

ClassifyStderr is the argv path's own stderr classifier: a backend that has Git's words in hand classes the failure the same way.

type Error

type Error struct {
	Class    ErrClass
	OpClass  OpClass
	Op       string // git subcommand, e.g. "diff", "commit"
	ExitCode int
	Stderr   string   // truncated; UI display only, never logged by this package
	Paths    []string // conflicting files of a stopped merge/rebase; UI display only
	// contains filtered or unexported fields
}

Error is a structured Git failure: it keeps the operation class and the raw stderr for surfacing in the UI, and a coarse class for branching.

func GitError

func GitError(err error) (*Error, bool)

GitError extracts the structured *Error from err, if any.

func NewError added in v0.3.0

func NewError(class ErrClass, op OpClass, sub string, exitCode int, stderr string, cause error) *Error

NewError builds the structured failure a Backend returns, so a caller branches on the same classes whichever path ran. stderr is truncated like the argv path's; cause may be nil.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type FileDiff

type FileDiff struct {
	Hunks         []Hunk
	StagedHunks   []Hunk
	UnstagedHunks []Hunk
}

FileDiff is what an on-demand read of one deferred file produced: its combined hunks, and each side's when changes sit staged and unstaged at once (otherwise the combined hunks are the side).

type FlatRow

type FlatRow struct {
	Node  *TreeNode
	Depth int
}

FlatRow is one visible row of the expanded-tree projection.

func Flatten

func Flatten(node *TreeNode, collapsed map[string]bool) []FlatRow

Flatten projects the tree into visible rows given the collapsed-dir set. Directories default to expanded (changes trees are small); a key present with value true marks a user-collapsed directory.

type GraphQuery

type GraphQuery struct {
	Limit  int
	Hidden []string
}

GraphQuery bounds a graph read. Hidden holds full ref names left out of the graph: a commit only they reach disappears, a commit shared with a visible ref stays.

type HistoryAction added in v0.3.0

type HistoryAction string

HistoryAction is what RewriteHistory does to the selected run of commits.

const (
	HistoryReword HistoryAction = "reword" // new message for exactly one commit
	HistorySquash HistoryAction = "squash" // into the commit just below the run, messages joined
	HistoryFixup  HistoryAction = "fixup"  // into the commit just below the run, messages dropped
	HistoryDrop   HistoryAction = "drop"   // remove the commits
	HistoryMove   HistoryAction = "move"   // Offset places toward older (>0) or newer (<0) commits
)

type HistoryBackend added in v0.3.0

type HistoryBackend interface {
	RewriteHistory(ctx context.Context, root string, op HistoryOp) error
}

HistoryBackend implements RewriteHistory's rewrite step on one run of commits of the checked-out branch. Runner.RewriteHistory has already validated the operation, required a clean tree and an attached branch and holds the repository's lock; the backend only rewrites. It may leave a rebase stopped (conflict or failure): the Runner aborts it, so the repository is never left half-done.

type HistoryChange added in v0.3.0

type HistoryChange string

HistoryChange says what a rewrite does to one row of the preview.

const (
	ChangeNone     HistoryChange = ""
	ChangeMoved    HistoryChange = "moved"
	ChangeReworded HistoryChange = "reworded"
	ChangeDropped  HistoryChange = "dropped"
	ChangeSquashed HistoryChange = "squashed" // folded into Into, message kept as part of it
	ChangeFixedUp  HistoryChange = "fixed up" // folded into Into, message dropped
	ChangeAbsorbs  HistoryChange = "absorbs"  // the commit that takes the others in; Absorbed counts them
)

type HistoryOp added in v0.3.0

type HistoryOp struct {
	Action  HistoryAction
	Hashes  []string
	Message string // reword only
	Offset  int    // move only
}

HistoryOp is one rewrite. Hashes are full hashes of commits that sit next to each other on the checked-out branch, in any order.

type HistoryPreview added in v0.3.0

type HistoryPreview struct {
	// Above is how many newer commits are not listed: they keep their order
	// and are replayed on top, so they get new hashes.
	Above int
	Rows  []HistoryPreviewRow
}

HistoryPreview is the part of the branch a rewrite touches, in the order it will have afterwards (removed commits stay in the list, marked).

func PreviewHistory added in v0.3.0

func PreviewHistory(commits []CommitInfo, op HistoryOp) (HistoryPreview, error)

PreviewHistory computes what op would do to the branch whose commits are given (newest first, the first one is HEAD). It changes nothing. It refuses what RewriteHistory would refuse for reasons visible in the list: a commit off the branch's first-parent line, a run that is not adjacent, a merge in the replayed range, nothing below to squash into, an empty branch, a move past either end.

type HistoryPreviewRow added in v0.3.0

type HistoryPreviewRow struct {
	Hash, Short string
	Subject     string // the new subject for a reworded commit
	Change      HistoryChange
	Removed     bool   // gone after the rewrite: shown struck through at its old place
	Into        string // short hash of the commit a squashed or fixed-up commit goes into
	Absorbed    int    // for ChangeAbsorbs
}

HistoryPreviewRow is one commit of the preview.

type Hunk

type Hunk struct {
	OldStart int
	OldLines int
	NewStart int
	NewLines int
	Section  string // trailing @@ context
	Lines    []DiffLine
}

Hunk is one @@ region of a file patch.

type HunkChoice added in v0.3.0

type HunkChoice int

HunkChoice is what to put where a hunk was.

const (
	ChoiceNone   HunkChoice = iota // not decided: the markers stay in the result
	ChoiceOurs                     // the current branch's lines
	ChoiceTheirs                   // the incoming lines
	ChoiceBoth                     // current, then incoming
	ChoiceBase                     // the common ancestor's lines
)

type IgnoreScope added in v0.3.0

type IgnoreScope string

IgnoreScope is where an ignore rule is written.

const (
	// IgnoreInRepository writes <root>/.gitignore: the rule travels with the
	// repository when it is committed.
	IgnoreInRepository IgnoreScope = "gitignore"
	// IgnoreLocally writes the repository's info/exclude: only this clone sees it.
	IgnoreLocally IgnoreScope = "exclude"
)

type LineKind

type LineKind uint8

LineKind is the role of one diff line in a hunk.

const (
	KindContext LineKind = iota
	KindAdd
	KindDelete
)

type MovedLine added in v0.3.0

type MovedLine struct {
	Removed bool
	Other   int
}

MovedLine says a changed line was moved rather than rewritten. For a deleted line Other is the line number the text has in the new file; for an added line, the number it had in the old file.

type OpClass

type OpClass string

OpClass separates read policy from mutation policy.

const (
	OpRead   OpClass = "read"
	OpMutate OpClass = "mutate"
)

type Operation added in v0.3.0

type Operation struct {
	Version    int      `json:"version"`
	ID         string   `json:"id"`
	Kind       string   `json:"kind"`
	Status     string   `json:"status"`
	CreatedAt  int64    `json:"created_at_ns"` // Unix nanoseconds: two operations in one second still sort
	FinishedAt int64    `json:"finished_at_ns,omitempty"`
	UndoneAt   int64    `json:"undone_at_ns,omitempty"`
	Paths      []string `json:"paths,omitempty"`
	// Removed are tracked paths that were already deleted in the working tree
	// when a discard brought them back: recovering takes them away again.
	Removed []string `json:"removed,omitempty"`
	// Snapshot is the pinned commit that holds what the operation destroyed
	// (a tree of the affected paths; for a branch, its tip; for a stash, the
	// stash commit).
	Snapshot string `json:"snapshot,omitempty"`
	// After is the tree the touched paths had once the operation finished
	// (apply-patch): recovery refuses when they are no longer that.
	After string `json:"after_tree,omitempty"`
	// Name is the branch's or stash's own name, for the kinds that have one.
	Name  string `json:"name,omitempty"`
	Error string `json:"error,omitempty"`
}

Operation is one destructive action and what a later recovery must revalidate. It holds names and object ids, never file content.

func (Operation) CanUndo added in v0.3.0

func (o Operation) CanUndo() bool

CanUndo is a hint for the UI: the preflight in UndoOperation is the authority.

func (Operation) Created added in v0.3.0

func (o Operation) Created() time.Time

Created is when the operation started.

type PatchAction added in v0.3.0

type PatchAction string

PatchAction is what RewriteWithPatch does with the selected changes.

const (
	PatchRemove PatchAction = "remove" // delete the changes from the commit; they are gone
	PatchSplit  PatchAction = "split"  // pull them into a new commit right after the commit
	PatchMove   PatchAction = "move"   // move them into another commit of the branch (Dest)
	PatchUndo   PatchAction = "undo"   // take them out of the commit and back into the work tree, staged
)

type PatchBackend added in v0.3.0

type PatchBackend interface {
	PatchSource(ctx context.Context, root, commit, path, previousPath string) ([]PatchSourceLine, error)
	RewriteWithPatch(ctx context.Context, root string, op PatchOp) error
}

PatchBackend implements Custom Patch. Runner has validated the operation, required a clean tree and an attached branch and holds the repository's lock; a rebase it leaves stopped is aborted by the Runner.

type PatchFile added in v0.3.0

type PatchFile struct {
	Path         string
	PreviousPath string // the old path of a renamed file
	Whole        bool
	Lines        []int
}

PatchFile is the part of one file's diff in the commit that is selected: all of it (Whole, also a rename, a deletion or an added file) or the lines whose PatchSourceLine.Index is listed.

type PatchOp added in v0.3.0

type PatchOp struct {
	Action  PatchAction
	Commit  string
	Dest    string
	Message string
	Files   []PatchFile
}

PatchOp is one Custom Patch operation on the checked-out branch. Commit is the full hash the changes come from; Dest the one they move into (move only); Message the new commit's message (split only).

type PatchSourceLine added in v0.3.0

type PatchSourceLine struct {
	Index      int
	Text       string
	Selectable bool
}

PatchSourceLine is one line of the diff a selection is made from. Index is what PatchFile.Lines refers to; Selectable lines are the added and removed ones (headers, hunk markers and context cannot be picked).

type PullMode

type PullMode string

PullMode is how a pull integrates what it fetched.

const (
	PullFastForward PullMode = "ff"
	PullMerge       PullMode = "merge"
	PullRebase      PullMode = "rebase"
)

type PushKind

type PushKind string

PushKind says what a PushRef is.

const (
	PushBranch PushKind = "branch"
	PushTag    PushKind = "tag"
)

type PushOffer

type PushOffer struct {
	Remote   string
	Branches []PushRef // the current branch first, then by name
	Tags     []PushRef // newest first, as ListTags orders them
}

PushOffer is what the dialog lists for one remote.

type PushRef

type PushRef struct {
	Kind PushKind
	Name string // the local branch or tag
	Dest string // the branch's name on the remote (== Name for a tag)

	Ahead, Behind int  // against the upstream, or the fetched same-name remote branch
	New           bool // the remote has no such branch (as far as the last fetch knows)
	Tracked       bool // the branch has an upstream on this remote
	Current       bool // the branch checked out here

	// Blocked is why the ref cannot be pushed without force ("" when it can).
	// There is no force push here; a diverged branch is pulled first.
	Blocked string
}

PushRef is one ref the multi-push dialog offers: a local branch with something to send (or none of it on the remote yet), or a local tag.

type RebaseAction

type RebaseAction string

RebaseAction is one line of an interactive rebase todo.

const (
	RebasePick   RebaseAction = "pick"
	RebaseReword RebaseAction = "reword"
	RebaseSquash RebaseAction = "squash"
	RebaseFixup  RebaseAction = "fixup"
	RebaseDrop   RebaseAction = "drop"
)

type RebaseCommit

type RebaseCommit struct {
	CommitInfo
	Published bool   // reachable from a remote-tracking ref: rewriting it needs a force push
	Message   string // the full message, what a reword starts from
}

RebaseCommit is a commit the plan can rewrite.

type RebaseStep

type RebaseStep struct {
	Hash    string
	Action  RebaseAction
	Message string
}

RebaseStep is one planned commit: its action and, for reword, the new message.

func PlanAutosquash added in v0.3.0

func PlanAutosquash(plan []RebaseCommit) (steps []RebaseStep, moved int)

PlanAutosquash orders a plan (oldest first) the way `rebase --autosquash` does: each "fixup! X" commit moves to just after the nearest older commit whose subject is X (else starts with X) and becomes a fixup; one with no target stays where it was, picked. moved counts the fixups that found one.

type ReflogEntry

type ReflogEntry struct {
	Hash     string
	Selector string // HEAD@{n}
	Action   string // "commit: fix typo", "checkout: moving from a to b"
	Subject  string // the commit's own subject
	Time     time.Time
}

ReflogEntry is one move of HEAD.

type Remote

type Remote struct {
	Name     string
	FetchURL string
	PushURL  string // "" when it equals FetchURL
}

Remote is one configured remote.

type RemoteBranch

type RemoteBranch struct {
	Remote    string
	Name      string
	HeadShort string
}

RemoteBranch is one locally cached remote-tracking ref. Listing refs does not fetch, mutate or infer whether the remote is reachable.

type ReplayKind added in v0.3.0

type ReplayKind string

ReplayKind is the sort of reflog action a plan replays.

const (
	ReplayCheckout ReplayKind = "checkout"
	ReplayCommit   ReplayKind = "commit"
	ReplayRebase   ReplayKind = "rebase"
)

type ReplayPlan added in v0.3.0

type ReplayPlan struct {
	Redo        bool
	Kind        ReplayKind
	From, To    string
	Identity    string
	Description string
}

ReplayPlan is the one action an undo (or redo) would take now. Identity binds a confirmation to exactly this action: both endpoint hashes and the kind must still be the next replay when it is accepted, so another Git client moving HEAD in between makes the confirmation refuse rather than undo something the user never approved.

type RepoFacts

type RepoFacts struct {
	Root      string
	Branch    string
	Head      string // empty when the repository has no commits yet
	Signature string
	// NoHead marks an unborn branch (repository without any commit).
	NoHead bool
}

RepoFacts is the identity set of one repository at one moment: root, current branch, HEAD hash, and a status signature covering the full working-tree/index state. It is the stale-state fence input (plan §22.3).

func (RepoFacts) HeadByte

func (f RepoFacts) HeadByte() []byte

HeadByte returns the HEAD hash bytes for signature hashing, with a stable marker for the unborn-branch case.

type ResetMode

type ResetMode string

ResetMode is one of Git's three reset depths.

const (
	ResetSoft  ResetMode = "soft"  // move the branch only; changes stay staged
	ResetMixed ResetMode = "mixed" // move the branch and unstage; files untouched
	ResetHard  ResetMode = "hard"  // move the branch and rewrite the files
)

type Runner

type Runner struct {
	// GitBinary defaults to "git".
	GitBinary string
	// Now overrides the clock for tests.
	Now func() time.Time
	// Backend, when set, serves the capabilities it implements (see
	// backend.go); the rest run on the argv path below.
	Backend Backend
	// Journal turns on the Safety Journal (journal.go): Discard, DeleteUntracked,
	// DeleteBranch and StashDrop keep a recovery point first. Off by default.
	Journal bool
	// Commands, when set, keeps the Git commands this Runner runs (command_log.go).
	Commands *CommandLog
	// contains filtered or unexported fields
}

Runner owns every Git subprocess this package spawns. The zero value is usable; GitBinary overrides the executable in tests.

func (*Runner) AddRemote

func (r *Runner) AddRemote(ctx context.Context, root, name, url string) error

AddRemote registers a new remote.

func (*Runner) AddSubmodule

func (r *Runner) AddSubmodule(ctx context.Context, root, address, rel string) error

AddSubmodule clones url into rel and records it (staged: .gitmodules and the gitlink). It contacts the network.

func (*Runner) AddWorktree

func (r *Runner) AddWorktree(ctx context.Context, root, path string) error

AddWorktree checks out a new work tree at path on a branch named after the path's folder, created from HEAD.

func (*Runner) AmendTo added in v0.3.0

func (r *Runner) AmendTo(ctx context.Context, root, commit string) error

AmendTo amends the commit with whatever is staged. Only staged changes may exist (untracked files do not count): anything unstaged would have to be carried through the rebase. A failure, a conflict included, leaves the repository as it was, the changes staged again.

func (*Runner) ApplyLines

func (r *Runner) ApplyLines(ctx context.Context, root, path string, h Hunk, selected map[int]bool, unstage bool) error

ApplyLines stages (or unstages) the selected lines of one hunk of path's change in the index; the worktree is never touched. Tracked files only: the caller offers it for modified text files shown on one side.

func (*Runner) ApplyPatch

func (r *Runner) ApplyPatch(ctx context.Context, root, file string) error

ApplyPatch applies a patch file (a diff, or a format-patch mailbox) to the working tree only — never the index, never a commit. The patch is checked first, so a patch that does not fit changes nothing.

func (*Runner) Blame

func (r *Runner) Blame(ctx context.Context, root, rev, rel string) ([]BlameLine, error)

Blame annotates a file at HEAD (or rev) line by line.

func (*Runner) BlobSize

func (r *Runner) BlobSize(ctx context.Context, root, spec string) (int64, error)

BlobSize returns the byte size of the blob named by spec ("<rev>:<path>", ":0:<path>" for the index) without reading it.

func (*Runner) BranchUpstream

func (r *Runner) BranchUpstream(ctx context.Context, root, branch string) string

BranchUpstream reads what a local branch tracks ("" when nothing).

func (*Runner) CapturePreflight

func (r *Runner) CapturePreflight(ctx context.Context, root string, snap *ChangesSnapshot, selected []string) (CommitPreflight, error)

CapturePreflight snapshots HEAD/branch/status signature plus per-file fingerprints and live object identities for the selected paths.

func (*Runner) CheckoutDetached

func (r *Runner) CheckoutDetached(ctx context.Context, root, hash string) error

CheckoutDetached moves HEAD to one exact commit (detached). Git itself refuses when local changes would be overwritten.

func (*Runner) CheckoutRemoteBranch

func (r *Runner) CheckoutRemoteBranch(ctx context.Context, root, ref string) (SwitchResult, error)

CheckoutRemoteBranch checks out a remote-tracking branch: the local branch of the same name when one exists, otherwise a new one that tracks it (what Fork's "Check Out…" on a remote branch does).

func (*Runner) CherryPickCommit

func (r *Runner) CherryPickCommit(ctx context.Context, root, hash string) error

CherryPickCommit applies one verified full commit ID to current HEAD. Selecting a merge commit without mainline is deliberately refused.

func (*Runner) CherryPickCommits added in v0.3.0

func (r *Runner) CherryPickCommits(ctx context.Context, root string, hashes []string) error

CherryPickCommits applies the commits to HEAD in the order given (oldest first), as one operation. Merge commits are refused. A conflict leaves the cherry-pick in progress for the sequencer's continue / skip / abort.

func (*Runner) Commit

func (r *Runner) Commit(ctx context.Context, root string, draft CommitDraft, pre CommitPreflight, snap *ChangesSnapshot) (CommitResult, error)

Commit executes the index-preserving selected-file transaction (plan §22.4). Holds the single-flight repository lock for the entire transaction.

func (*Runner) CommitByHash

func (r *Runner) CommitByHash(ctx context.Context, root, hash string) (*CommitInfo, error)

CommitByHash reads one commit's list metadata (no decorations).

func (*Runner) CommitMessage

func (r *Runner) CommitMessage(ctx context.Context, root, hash string) (string, error)

CommitMessage reads the full message (subject, blank line, body) of one commit, trailing whitespace trimmed. The hash must name a commit; a non-commit is refused before the log runs.

func (*Runner) CommitSnapshot

func (r *Runner) CommitSnapshot(ctx context.Context, root, hash string) (*ChangesSnapshot, error)

CommitSnapshot builds the change set of one commit: its diff against the first parent (or the empty tree for a root commit). Review-only: the staged/unstaged sides and the worktree do not apply.

func (*Runner) CompareCommits added in v0.3.0

func (r *Runner) CompareCommits(ctx context.Context, root, base, hash string) (*ChangesSnapshot, error)

CompareCommits is the review of two commits against each other: what a change from base to hash would be (`git diff base hash`), as one snapshot whose DiffBase is base..hash, the shape a single commit's review has.

func (*Runner) CompareToWorktree

func (r *Runner) CompareToWorktree(ctx context.Context, root, hash string) (*ChangesSnapshot, error)

CompareToWorktree is the review of one commit against the working tree (staged and unstaged changes included, untracked files not): what changed between that commit and what is on disk now.

func (*Runner) CourierPatch added in v0.3.0

func (r *Runner) CourierPatch(ctx context.Context, root string, srcs ...CourierSource) (string, error)

CourierPatch makes the patch of the sources, one after the other. A whole file keeps what Git itself writes (binary data, modes, renames); picked lines are cut against the side they were picked on, so a destination that does not hold that side refuses them in the preview.

func (*Runner) CreateBranch

func (r *Runner) CreateBranch(ctx context.Context, root, name string) (SwitchResult, error)

CreateBranch creates and checks out a new local branch (`git switch -c`). No tracking setup, no start-point customization in core 0.10. The name is validated by check-ref-format first, so it cannot start with '-' and the option-value form is injection-safe.

func (*Runner) CreateBranchAt

func (r *Runner) CreateBranchAt(ctx context.Context, root, name, hash string) (SwitchResult, error)

CreateBranchAt creates and checks out a branch at one exact commit.

func (*Runner) CreateFixup added in v0.3.0

func (r *Runner) CreateFixup(ctx context.Context, root, hash string) error

CreateFixup commits the staged changes as "fixup! <subject>" of hash, a commit on the current history. Nothing staged, or a merge or rebase in progress, is refused.

func (*Runner) CreateTag

func (r *Runner) CreateTag(ctx context.Context, root, name string) error

CreateTag creates a lightweight tag at HEAD.

func (*Runner) CreateTagAnnotated

func (r *Runner) CreateTagAnnotated(ctx context.Context, root, name, hash, message string) error

CreateTagAnnotated creates a tag at hash (HEAD when empty). A message makes it an annotated tag (travels by stdin, never argv); without one it is the lightweight tag CreateTag makes.

func (*Runner) CreateTagAt

func (r *Runner) CreateTagAt(ctx context.Context, root, name, hash string) error

CreateTagAt tags one exact commit.

func (*Runner) CurrentBranch

func (r *Runner) CurrentBranch(ctx context.Context, root string) string

CurrentBranch returns the checked-out branch, "" on a detached HEAD.

func (*Runner) DefaultRemote

func (r *Runner) DefaultRemote(ctx context.Context, root string) string

DefaultRemote returns the repository's remote to act against: the first configured remote, or "origin" when none is configured yet.

func (*Runner) DeleteBranch

func (r *Runner) DeleteBranch(ctx context.Context, root, name string) error

DeleteBranch deletes a local branch with Git's safe -d: unmerged branches are refused, never forced away.

func (*Runner) DeleteRemoteBranch

func (r *Runner) DeleteRemoteBranch(ctx context.Context, root, remote, name string) error

DeleteRemoteBranch removes one branch from its remote (`git push <remote> :refs/heads/<name>`). The branch must be one Git lists as remote-tracking.

func (*Runner) DeleteRemoteTag

func (r *Runner) DeleteRemoteTag(ctx context.Context, root, remote, name string) error

DeleteRemoteTag removes one tag from a configured remote's server.

func (*Runner) DeleteTag

func (r *Runner) DeleteTag(ctx context.Context, root, name string) error

DeleteTag removes one tag.

func (*Runner) DeleteUntracked

func (r *Runner) DeleteUntracked(root string, paths []string) error

DeleteUntracked removes untracked paths from the worktree directly — the sanctioned replacement for `git clean -f`, which stays banned. The UI must confirm before calling: the files are deleted, not stashed.

func (*Runner) DeliverCourier added in v0.3.0

func (r *Runner) DeliverCourier(ctx context.Context, dest, patch string) error

DeliverCourier applies a patch that PreviewCourier called clean to the destination's working tree: unstaged, the index and every ref untouched, and under that repository's Safety Journal (Undo Git Action there takes it back). The check runs again right before, so a destination that changed since the preview is refused.

func (*Runner) Discard

func (r *Runner) Discard(ctx context.Context, root string, paths []string) error

Discard throws away the worktree changes of tracked paths (`git restore --`). The UI must confirm before calling: the content is unrecoverable.

func (*Runner) DiscardCourierLines added in v0.3.0

func (r *Runner) DiscardCourierLines(ctx context.Context, root string, src CourierSource) error

DiscardCourierLines takes the picked lines of a working-tree source out of its working tree again (Move): the reverse of what CourierPatch cut, under the Safety Journal. The lines must still be there as they were read.

func (*Runner) Facts

func (r *Runner) Facts(ctx context.Context, root string) (RepoFacts, error)

Facts captures root/branch/HEAD plus the status signature in as few Git calls as possible. The signature hashes `status --porcelain=v1 -z` output (index + worktree + untracked), so any index/worktree mutation changes it.

func (*Runner) Fetch

func (r *Runner) Fetch(ctx context.Context, root, remote string) error

Fetch refreshes one remote (explicit user intent; never automatic).

func (*Runner) FetchAll

func (r *Runner) FetchAll(ctx context.Context, root string, prune bool) error

FetchAll fetches every configured remote, optionally dropping remote-tracking branches the servers no longer have.

func (*Runner) FetchedAt

func (r *Runner) FetchedAt(ctx context.Context, root string) (at time.Time, ok bool)

FetchedAt reports when the repository's remotes were last fetched: the newest modification time of FETCH_HEAD, the file every fetch rewrites, in the worktree's own git dir and in the repository's common one (a fetch run from any linked worktree updates the shared remote refs, but writes only its own FETCH_HEAD). ok is false when nothing was ever fetched — a repository with no remote included.

func (*Runner) FileHistory

func (r *Runner) FileHistory(ctx context.Context, root, rel string, limit int) ([]CommitInfo, error)

FileHistory lists the commits that touched one path, following renames, newest first.

func (*Runner) FileLines

func (r *Runner) FileLines(ctx context.Context, root, relPath string, start, count int) ([]string, error)

FileLines reads a bounded window of working-tree file lines for unchanged-context expansion (plan §19.4). Read-only and bounded; callers run it on background lanes only — never from a render pass. start is 1-based; count lines from there.

func (*Runner) FilterCommits added in v0.3.0

func (r *Runner) FilterCommits(ctx context.Context, root string, f CommitFilter) ([]CommitInfo, error)

FilterCommits asks Git for the commits that pass the filter, newest first. A malformed date, a range that ends before it begins and a path outside the repository are refused before Git runs.

func (*Runner) FinishSequencer

func (r *Runner) FinishSequencer(ctx context.Context, root string, expected SequencerKind, abort bool) error

FinishSequencer revalidates live state before any Git mutation. Abort is explicit and may throw away conflict-resolution edits, so the UI confirms first. Continue refuses to operate while any index entry is unresolved.

func (*Runner) FormatPatch

func (r *Runner) FormatPatch(ctx context.Context, root, hash string) ([]byte, error)

FormatPatch is one commit as an mbox patch (`git format-patch -1 --stdout`), the text "Save as Patch" writes.

func (*Runner) GraphPosition

func (r *Runner) GraphPosition(ctx context.Context, root string, q GraphQuery, hash string) (int, error)

GraphPosition is the 0-based row a commit has in the graph ListCommitGraph draws for q (without a limit), or -1 when the graph never reaches it — the size the window must grow to for the commit to be a row.

func (*Runner) IgnorePaths added in v0.3.0

func (r *Runner) IgnorePaths(ctx context.Context, root string, paths []string, scope IgnoreScope) (int, error)

IgnorePaths adds one anchored rule per untracked path (a folder gets a trailing slash) to the scope's file and returns how many lines it added; a rule already there is not written again. A tracked path is refused: ignoring it would not untrack it, and Solco Git never untracks for you.

func (*Runner) InteractiveRebase

func (r *Runner) InteractiveRebase(ctx context.Context, root, base string, steps []RebaseStep) error

InteractiveRebase replays base..HEAD as the steps say. The todo is handed to Git through GIT_SEQUENCE_EDITOR (a copy of a file we wrote), rewords become an `exec git commit --amend -F` line, and a rebase that stops is aborted at once like RebaseOnto: the repository is never left half-done.

func (*Runner) LastCommitMessage

func (r *Runner) LastCommitMessage(ctx context.Context, root string) (subject, body string, err error)

LastCommitMessage returns the subject and body of HEAD, for the Amend prefill. It fails on an unborn branch.

func (*Runner) ListBranches

func (r *Runner) ListBranches(ctx context.Context, root string) ([]Branch, error)

ListBranches enumerates local branches cheaply (no network).

func (*Runner) ListCommitGraph

func (r *Runner) ListCommitGraph(ctx context.Context, root string, q GraphQuery) ([]CommitInfo, error)

ListCommitGraph reads every branch, remote-tracking branch and tag, plus HEAD, newest first in date order (a parent never precedes its children, which the lane projection relies on). Stashes and notes stay out.

func (*Runner) ListCommits

func (r *Runner) ListCommits(ctx context.Context, root string, limit int) ([]CommitInfo, error)

ListCommits reads the history of HEAD, newest first, bounded.

func (*Runner) ListRemoteBranches

func (r *Runner) ListRemoteBranches(ctx context.Context, root string) ([]RemoteBranch, error)

ListRemoteBranches reads refs/remotes without network activity. Symbolic HEAD pointers are excluded; only actual branch refs belong in the tree.

func (*Runner) ListRemotes

func (r *Runner) ListRemotes(ctx context.Context, root string) ([]Remote, error)

ListRemotes reads the configured remotes (no network).

func (*Runner) ListSubmodules

func (r *Runner) ListSubmodules(ctx context.Context, root string) ([]Submodule, error)

ListSubmodules reads `git submodule status` (no network, not recursive).

func (*Runner) ListTags

func (r *Runner) ListTags(ctx context.Context, root string) ([]Tag, error)

ListTags enumerates tags, newest creation first, bounded.

func (*Runner) ListTree

func (r *Runner) ListTree(ctx context.Context, root, rev, dir string) ([]TreeEntry, error)

ListTree lists the direct children of dir ("" is the repository root) in rev's tree: directories first, then by name, case-insensitively. rev is anything Git resolves to a commit or tree (a hash, a branch, a tag); a revision starting with "-" or a dir that climbs out of the tree is refused before Git is asked. A directory that did not exist at rev is an empty list, not an error.

func (*Runner) ListWorktrees

func (r *Runner) ListWorktrees(ctx context.Context, root string) ([]Worktree, error)

ListWorktrees enumerates the repository's work trees (no network).

func (*Runner) LockRepo

func (r *Runner) LockRepo(root, op string) (func(), error)

LockRepo serializes mutations per canonical repository root.

func (*Runner) MergeFastForward

func (r *Runner) MergeFastForward(ctx context.Context, root, target string) error

MergeFastForward updates the checked-out branch to a selected EXISTING local branch, only if the current HEAD is its ancestor. A divergent history is refused: no conflict markers, no surprise merge commits. Users can decide separately whether they want a no-ff merge in a later explicitly designed conflict-resolution workflow.

func (*Runner) MergeInProgress

func (r *Runner) MergeInProgress(ctx context.Context, root string) bool

MergeInProgress reports an in-progress merge/revert/cherry-pick state, where Git refuses partial commits (fail-closed input for Commit).

func (*Runner) MergeNoFastForward

func (r *Runner) MergeNoFastForward(ctx context.Context, root, target string) error

MergeNoFastForward performs an explicitly confirmed merge. It cannot silently merge a dirty tree; conflicts may leave MERGE_HEAD for the user to resolve in the inspector or Terminal.

func (*Runner) MergeSquash

func (r *Runner) MergeSquash(ctx context.Context, root, target string) error

MergeSquash folds every change of target into the index without committing, so the user reviews the result and commits it as one. It needs a clean working tree; if it stops on conflicts it is rolled back (`reset --merge`) because a squash leaves no MERGE_HEAD for a Continue/Abort banner to hold.

func (*Runner) Mutate

func (r *Runner) Mutate(ctx context.Context, root string, args ...string) ([]byte, error)

Mutate runs one explicit mutation command single-flight per repo root. Callers must have already revalidated state; the runner only serializes.

func (*Runner) Operations added in v0.3.0

func (r *Runner) Operations(ctx context.Context, root string) ([]Operation, error)

Operations lists the journal, newest first. A pending record that has been pending far longer than any operation runs is shown as interrupted. Records past the keep count or lifetime are pruned (with their pinned commits).

func (*Runner) PatchSource added in v0.3.0

func (r *Runner) PatchSource(ctx context.Context, root, commit, path, previousPath string) ([]PatchSourceLine, error)

PatchSource lists the lines of a file's diff in a commit that a selection can name. Reading only: no state changes.

func (*Runner) PlanReplay added in v0.3.0

func (r *Runner) PlanReplay(ctx context.Context, root string, redo bool) (plan ReplayPlan, ok bool, err error)

PlanReplay reads the whole HEAD reflog and says what an undo (or redo) would replay; ok is false when there is nothing eligible.

func (*Runner) PreviewCourier added in v0.3.0

func (r *Runner) PreviewCourier(ctx context.Context, dest, patch string) (CourierPreview, error)

PreviewCourier checks the patch against the destination worktree without changing anything. A destination with a merge, rebase, revert or cherry-pick in progress is refused: its working tree is not the quiet one a patch fits.

func (*Runner) PublishedCommits added in v0.3.0

func (r *Runner) PublishedCommits(ctx context.Context, root string, hashes []string) ([]string, error)

PublishedCommits returns those of hashes that a remote-tracking ref already holds: rewriting them means the branch can only be pushed by force. A repository without remotes publishes nothing. Read only.

func (*Runner) Pull

func (r *Runner) Pull(ctx context.Context, root, remote, branch string, mode PullMode) error

Pull fetches branch from remote and integrates it into the current branch. Fast-forward refuses a diverged history; merge may pause on conflicts (the merge banner then offers Continue/Abort); a rebase that stops on conflicts is aborted at once and reported with the paths, like RebaseOnto.

func (*Runner) PullFFOnly

func (r *Runner) PullFFOnly(ctx context.Context, root, remote, branch string) error

PullFFOnly pulls with --ff-only: Git refuses a diverged history instead of creating surprise merges, and the UI surfaces the refusal.

func (*Runner) Push

func (r *Runner) Push(ctx context.Context, root, remote, branch string, setUpstream bool) error

Push publishes the branch to the remote; setUpstream sets tracking the first time a branch is published.

func (*Runner) PushMany

func (r *Runner) PushMany(ctx context.Context, root, remote string, refs []PushRef, setUpstream bool) error

PushMany publishes the given refs to remote in one `git push`: each branch lands on its Dest, each tag on itself. setUpstream (-u) records tracking for the pushed branches that have none. There is never a force: every refspec is fully qualified and carries no "+", a ref that is Blocked is refused, and a branch or tag that no longer exists locally is refused before Git is asked.

func (*Runner) PushTag

func (r *Runner) PushTag(ctx context.Context, root, remote, name string) error

PushTag publishes one existing tag (explicit; plain Push never sends tags).

func (*Runner) PushTo

func (r *Runner) PushTo(ctx context.Context, root, remote, src, dst string, setUpstream bool) error

PushTo publishes local branch src as dst on the remote: a branch whose upstream has another name (or lives on a second remote) must land on that upstream, not on a same-named branch of the first remote.

func (*Runner) Read

func (r *Runner) Read(ctx context.Context, root string, args ...string) ([]byte, error)

Read runs one bounded, read-only Git command in root. It never mutates worktree or index state (GIT_OPTIONAL_LOCKS=0 keeps even refreshes lockless).

func (*Runner) ReadBlob

func (r *Runner) ReadBlob(ctx context.Context, root, spec string, max int64) ([]byte, error)

ReadBlob returns the blob named by spec when it is at most max bytes; a larger one is refused with ErrTooLarge before any of it is read.

func (*Runner) ReadConflict added in v0.3.0

func (r *Runner) ReadConflict(ctx context.Context, root, rel string) (ConflictSides, error)

ReadConflict reads the three versions of an unmerged file and the merge Git would make of them, cut into hunks. A file that cannot be edited line by line (a side deleted it, binary, too large, a link or submodule) comes back with Editable false and the reason.

func (*Runner) ReadFileDiff

func (r *Runner) ReadFileDiff(ctx context.Context, root, base string, cf ChangeFile) (FileDiff, error)

ReadFileDiff reads the diff of one deferred file: through Git for a tracked path, against base (the DiffBase of its snapshot), and from the disk for an untracked one. The output is bounded by MaxOnDemandPatchBytes; past it the error is ErrTooLarge.

func (*Runner) ReadPushOffer

func (r *Runner) ReadPushOffer(ctx context.Context, root, remote string) (PushOffer, error)

ReadPushOffer lists, for remote, the local branches that have commits to send (or are not on the remote yet) and the local tags. It reads only what the last fetch recorded; no network. A branch tracking another remote is not offered here.

func (*Runner) RebaseOnto

func (r *Runner) RebaseOnto(ctx context.Context, root, target string) error

RebaseOnto replays the current branch on top of a local or remote-tracking branch. A rebase that stops on conflicts is aborted at once and reported with the conflicting paths: Solco has no rebase continue/skip workflow, so it never leaves one half-done (the user resolves it in the Terminal or merges instead).

func (*Runner) RebaseOntoFrom added in v0.3.0

func (r *Runner) RebaseOntoFrom(ctx context.Context, root, target, upstream string) error

RebaseOntoFrom is `git rebase --onto target upstream`: the commits after upstream (a full hash on the current branch, exclusive) are replayed on top of target, and upstream and everything before it stay behind. Merge commits in that run are refused (a plain rebase would flatten them); a conflict aborts as in RebaseOnto.

func (*Runner) RebasePlan

func (r *Runner) RebasePlan(ctx context.Context, root, base string) ([]RebaseCommit, error)

RebasePlan lists base..HEAD oldest first. Merge commits in the range are refused (a linear rebase would flatten them silently).

func (*Runner) Reflog

func (r *Runner) Reflog(ctx context.Context, root string, limit int) ([]ReflogEntry, error)

Reflog lists where HEAD has been, newest first.

func (*Runner) RemoveRemote

func (r *Runner) RemoveRemote(ctx context.Context, root, name string) error

RemoveRemote deletes a remote and its tracking branches.

func (*Runner) RemoveSubmodule

func (r *Runner) RemoveSubmodule(ctx context.Context, root, rel string) error

RemoveSubmodule unregisters one listed submodule and stages its removal (`submodule deinit` then `rm`); Git's own modules folder stays for a later re-add.

func (*Runner) RemoveWorktree

func (r *Runner) RemoveWorktree(ctx context.Context, root, path string) error

RemoveWorktree deletes one linked work tree. The main work tree is never a target, and Git itself refuses one with changes or a lock.

func (*Runner) RenameBranch

func (r *Runner) RenameBranch(ctx context.Context, root, name, to string) error

RenameBranch renames a local branch (`git branch -m`); the new name is checked by check-ref-format first.

func (*Runner) RenameRemote

func (r *Runner) RenameRemote(ctx context.Context, root, name, to string) error

RenameRemote renames a remote; Git moves its tracking refs along.

func (*Runner) Replay added in v0.3.0

func (r *Runner) Replay(ctx context.Context, root string, redo bool, expected string) error

Replay undoes (or redoes) the action PlanReplay reported. expected is that plan's Identity, or empty to take whatever is next. A merge, revert, cherry-pick or rebase in progress refuses, as does a history that moved since the plan was read.

func (*Runner) RequireCleanWorktree

func (r *Runner) RequireCleanWorktree(ctx context.Context, root string) error

RequireCleanWorktree prevents history mutations from silently combining pending local edits with merge/revert. This checks both staged and unstaged files and untracked files; a failed status read fails closed.

func (*Runner) ResetTo

func (r *Runner) ResetTo(ctx context.Context, root, hash string, mode ResetMode) (previous string, err error)

ResetTo moves the current branch to one commit. Hard additionally demands a clean working tree, so no uncommitted work can be lost; the commits it drops stay reachable through the reflog and the previous HEAD is returned so the UI can say how to get back.

func (*Runner) ResolveCommit

func (r *Runner) ResolveCommit(ctx context.Context, root, fullRef string) (string, error)

ResolveCommit names the commit a full ref points at (an annotated tag is peeled). Anything but a refs/ name is refused.

func (*Runner) ResolveConflict

func (r *Runner) ResolveConflict(ctx context.Context, root, rel string, side ConflictSide) error

ResolveConflict resolves one unmerged file: keep a side, or accept the file as the user edited it (refused while conflict markers remain).

func (*Runner) ResolveRoot

func (r *Runner) ResolveRoot(ctx context.Context, dir string) (string, error)

ResolveRoot walks up from dir to the enclosing worktree top-level. The empty string means "not inside a repository".

func (*Runner) ResolveWith added in v0.3.0

func (r *Runner) ResolveWith(ctx context.Context, root, rel, content string) error

ResolveWith settles one unmerged text file with the given result: it is written to the working tree and staged. Refused while the result still holds conflict markers, is too large, or the file is no longer in conflict. With the journal on, the working-tree file it replaces (the markers, or edits made elsewhere) is kept first, and Recovery can reopen the conflict.

func (*Runner) RestoreFile

func (r *Runner) RestoreFile(ctx context.Context, root, hash, rel string) error

RestoreFile writes one file as it was in a commit into the working tree (unstaged, so it shows up as a change to review or discard).

func (*Runner) RevertCommit

func (r *Runner) RevertCommit(ctx context.Context, root, hash string) error

RevertCommit creates an inverse commit for an exact full Git commit ID, preserving public history. The UI must confirm the selected commit and explain that conflicts may require manual resolution in the Terminal.

func (*Runner) RewriteHistory added in v0.3.0

func (r *Runner) RewriteHistory(ctx context.Context, root string, op HistoryOp) error

RewriteHistory applies op to the checked-out branch. It needs a HistoryBackend (the LazyGit engine); without one it refuses and InteractiveRebase remains the way. A conflict or any other failure aborts the rebase: nothing changes, and a conflict is reported as ErrConflict with the files that clashed.

func (*Runner) RewriteWithPatch added in v0.3.0

func (r *Runner) RewriteWithPatch(ctx context.Context, root string, op PatchOp) error

RewriteWithPatch applies op to the checked-out branch. Any failure, including a conflict, aborts the rebase and leaves the repository as it was.

func (*Runner) SequencerState

func (r *Runner) SequencerState(ctx context.Context, root string) (SequencerStatus, error)

SequencerState asks Git for *this worktree's* state. It fails closed if any marker lookup fails and never trusts a stale UI snapshot.

func (*Runner) SetRemoteURL

func (r *Runner) SetRemoteURL(ctx context.Context, root, name, url string) error

SetRemoteURL repoints an existing remote's fetch (and push) address.

func (*Runner) SetUpstream

func (r *Runner) SetUpstream(ctx context.Context, root, branch, upstream string) error

SetUpstream makes a local branch track a listed remote-tracking branch ("origin/main").

func (*Runner) Snapshot

func (r *Runner) Snapshot(ctx context.Context, root string) (*ChangesSnapshot, error)

Snapshot acquires the working-tree change snapshot for root: working tree + index vs HEAD, plus untracked files (plan §14). Repository without HEAD compares to the empty tree.

func (*Runner) SquashFixups added in v0.3.0

func (r *Runner) SquashFixups(ctx context.Context, root, hash string) (int, error)

SquashFixups folds the "fixup!" commits of hash and everything after it into their targets (one rebase onto hash's parent) and returns how many it folded. No fixup with a target in that range is a refusal; a conflict aborts the rebase like every other history rewrite.

func (*Runner) Stage

func (r *Runner) Stage(ctx context.Context, root string, paths []string) error

Stage moves worktree changes of paths into the index (`git add --`).

func (*Runner) StashApply

func (r *Runner) StashApply(ctx context.Context, root, ref string) error

StashApply re-applies one stash entry and keeps it (Pop applies and drops).

func (*Runner) StashClear

func (r *Runner) StashClear(ctx context.Context, root string) error

StashClear drops every stash entry.

func (*Runner) StashDrop

func (r *Runner) StashDrop(ctx context.Context, root, ref string) error

StashDrop deletes one stash entry.

func (*Runner) StashLines added in v0.3.0

func (r *Runner) StashLines(ctx context.Context, root string, src CourierSource, message string) error

StashLines saves the picked lines of one working-tree file as a stash entry and takes them out of the working tree. The stash is the native kind (HEAD plus only those lines, with an index parent), so pop, apply, drop and the Stashes list treat it like any other. Picks are over src.Hunks, the unstaged diff the user picked on.

The file must be tracked and must have nothing staged: the patch is cut against HEAD, and a staged change would make the stash and the working tree disagree about what the lines were. Everything that can refuse does so before the stash is stored, and the removal is `git apply --reverse`, all or nothing; if it still fails the stash just stored is dropped again.

func (*Runner) StashList

func (r *Runner) StashList(ctx context.Context, root string) ([]Stash, error)

StashList enumerates the stash entries, newest first.

func (*Runner) StashPatch

func (r *Runner) StashPatch(ctx context.Context, root, ref string) ([]byte, error)

StashPatch is one stash entry as a plain diff patch, untracked files included (`git stash show -p --include-untracked`), for "Save as Patch".

func (*Runner) StashPop

func (r *Runner) StashPop(ctx context.Context, root, ref string) error

StashPop applies a stash entry and drops it on success.

func (*Runner) StashPush

func (r *Runner) StashPush(ctx context.Context, root, message string) error

StashPush stashes the worktree and index; untracked files join with -u so "stash" puts the whole change set away, as the Changes list shows it.

func (*Runner) StashPushMode added in v0.3.0

func (r *Runner) StashPushMode(ctx context.Context, root string, mode StashMode, message string) error

StashPushMode saves the changes StashMode names, with an optional message.

func (*Runner) StashPushPaths

func (r *Runner) StashPushPaths(ctx context.Context, root, message string, paths []string) error

StashPushPaths stashes only the listed files (untracked ones included).

func (*Runner) StashRename

func (r *Runner) StashRename(ctx context.Context, root, hash, message string) error

StashRename gives one stash a new message. The stash is found by its commit hash (its stash@{n} index moves whenever another stash is made), rebuilt under the new message — it lands on top of the list, as in Fork — and the old entry is dropped only once the new one exists.

func (*Runner) StashSnapshot

func (r *Runner) StashSnapshot(ctx context.Context, root, hash string) (*ChangesSnapshot, error)

StashSnapshot is a stash as one review: the tracked changes it holds (against the commit it was made on) plus, when it was made with -u, the untracked files Git keeps on the stash commit's third parent.

func (*Runner) Stdin

func (r *Runner) Stdin(ctx context.Context, root, stdin string, args ...string) ([]byte, error)

Stdin runs one mutation with stdin content (commit message transport). The message travels by pipe, never by argv, avoiding argv length limits and keeping message text out of process listings.

func (*Runner) SwitchBranch

func (r *Runner) SwitchBranch(ctx context.Context, root, name string) (SwitchResult, error)

SwitchBranch moves to an existing local branch via `git switch` (plan §23.2): no force, no checkout --; Git's refusal is returned, not fought.

func (*Runner) UndoLastCommit

func (r *Runner) UndoLastCommit(ctx context.Context, root string) error

UndoLastCommit soft-resets a LOCAL unpushed non-root HEAD commit: changes remain staged. Never silently rewrite a commit referenced by a known remote-tracking ref; published history should use Revert instead.

func (*Runner) UndoOperation added in v0.3.0

func (r *Runner) UndoOperation(ctx context.Context, root, id string) error

UndoOperation recovers what a journaled operation destroyed. It revalidates the repository first and refuses when it has changed since.

func (*Runner) UnmergedPaths

func (r *Runner) UnmergedPaths(ctx context.Context, root string) ([]string, error)

UnmergedPaths lists the files that still have unresolved conflicts.

func (*Runner) UnsetUpstream

func (r *Runner) UnsetUpstream(ctx context.Context, root, branch string) error

UnsetUpstream stops a local branch tracking anything.

func (*Runner) Unstage

func (r *Runner) Unstage(ctx context.Context, root string, noHead bool, paths []string) error

Unstage moves index changes of paths back out of the index. On an unborn branch the staged files are simply unlinked from the index (`git rm --cached`), since there is no HEAD to restore from.

func (*Runner) UpdateSubmodule

func (r *Runner) UpdateSubmodule(ctx context.Context, root, rel string) error

UpdateSubmodule initialises (when needed) and checks out the commit the superproject records for one listed submodule. It may contact the network.

func (*Runner) Upstream

func (r *Runner) Upstream(ctx context.Context, root string) (UpstreamStatus, error)

Upstream reads the tracking status of the current branch: no network.

func (*Runner) ValidateBranchName

func (r *Runner) ValidateBranchName(ctx context.Context, root, name string) error

ValidateBranchName checks a candidate name through Git's own ref rules (`check-ref-format --branch`), the authority for New Branch.

func (*Runner) WithAutostash

func (r *Runner) WithAutostash(ctx context.Context, root string, action func() error) (AutostashResult, error)

WithAutostash stashes the local changes, runs action and reapplies them. A failing action restores the changes at once unless it left a merge/rebase half way; a reapply that conflicts leaves the stash in place (Kept).

func (*Runner) WorkingPatch

func (r *Runner) WorkingPatch(ctx context.Context, root string) ([]byte, error)

WorkingPatch is everything that differs from HEAD right now — staged, unstaged and untracked (ignored files stay out) — as one diff patch. It is built in a throw-away index, so the repository's own index, working tree and refs are never touched (only unreferenced blob objects may be written, which `git gc` prunes).

type SequencerKind

type SequencerKind string

SequencerKind identifies Git's active conflict-resolution transaction. Only operations explicitly supported by this package can be continued or aborted; an unknown/rebase state must not be interpreted as clean.

const (
	SequencerNone        SequencerKind = ""
	SequencerMerge       SequencerKind = "merge"
	SequencerRevert      SequencerKind = "revert"
	SequencerCherryPick  SequencerKind = "cherry-pick"
	SequencerUnsupported SequencerKind = "unsupported"
)

type SequencerStatus

type SequencerStatus struct {
	Kind     SequencerKind
	Unmerged int
	// UnmergedPaths is a bounded, sorted subset of actual unmerged index
	// entries; Unmerged remains the exact total even when the list is long.
	UnmergedPaths []string
}

SequencerStatus contains no file bodies, commit messages, or credentials.

func (SequencerStatus) Active

func (s SequencerStatus) Active() bool

type Stash

type Stash struct {
	Ref     string // e.g. stash@{0}
	Hash    string // the stash commit itself (what a review of the stash reads)
	Base    string // the commit the stash was made on (its first parent); "" if unknown
	Subject string
}

Stash is one entry of the stash list.

type StashBackend added in v0.3.0

type StashBackend interface {
	StashList(ctx context.Context, root string) ([]Stash, error)
}

StashBackend implements StashList: the entries newest first, each with its base commit (the first parent of the stash commit), as the argv path returns them.

type StashMode added in v0.3.0

type StashMode string

StashMode picks what a stash takes.

const (
	// StashStaged stashes only what is staged; the rest stays in the work tree.
	StashStaged StashMode = "staged"
	// StashKeepIndex stashes everything, tracked and untracked, and leaves the
	// staged changes in the index and the work tree as well.
	StashKeepIndex StashMode = "keep-index"
)

type Submodule

type Submodule struct {
	Path     string
	Commit   string
	State    SubmoduleState
	Describe string
}

Submodule is one submodule of the repository.

type SubmoduleState

type SubmoduleState string

SubmoduleState is `git submodule status`'s one-character state.

const (
	SubmoduleClean         SubmoduleState = "clean"
	SubmoduleUninitialized SubmoduleState = "uninitialized"
	SubmoduleModified      SubmoduleState = "modified" // checked out at another commit than recorded
	SubmoduleConflict      SubmoduleState = "conflict"
)

type SwitchResult

type SwitchResult struct {
	Branch string
	// Carried notes Git's dirty-compatible carry of working changes.
	Created bool
}

SwitchResult reports the outcome of a branch switch.

type Tag

type Tag struct{ Name string }

Tag is one lightweight tag of the repository.

type TagBackend added in v0.3.0

type TagBackend interface {
	ListTags(ctx context.Context, root string) ([]Tag, error)
}

TagBackend implements ListTags: tag names, newest creation first, at most 500, exactly as the argv path returns them.

type TreeEntry

type TreeEntry struct {
	Name string // base name
	Path string // slash path from the repository root
	Mode string // octal mode as Git prints it ("100644", "040000", "160000", …)
	// Dir marks a sub-directory; Submodule a gitlink (a commit of another
	// repository, which has no file content here).
	Dir, Submodule bool
	// Size is the blob's byte size; -1 for directories and submodules.
	Size int64
}

TreeEntry is one child of a directory as it stood at a commit.

type TreeNode

type TreeNode struct {
	Name     string // display segment
	Path     string // full repo-relative path
	Dir      bool
	File     *ChangeFile // leaf only
	Children []*TreeNode
}

TreeNode is one node of the changed-path tree: a directory aggregate or a changed file leaf (plan §11.1: tree projection is separate from parsing).

func BuildTree

func BuildTree(files []ChangeFile, compactOneChild bool) *TreeNode

BuildTree projects changed files into a dirs-first tree. compactOneChild collapses single-child directory chains ("a/b/c.txt" under one row).

func FilterTree

func FilterTree(node *TreeNode, query string) *TreeNode

FilterTree recursively keeps nodes whose own text or a descendant matches the query (case-insensitive substring). Returns nil when nothing matches.

func (*TreeNode) Additions

func (n *TreeNode) Additions() int

Additions/Deletions aggregate the subtree totals for directory rows.

func (*TreeNode) Deletions

func (n *TreeNode) Deletions() int

func (*TreeNode) FileCount

func (n *TreeNode) FileCount() int

FileCount counts leaves under the node.

type UpstreamStatus

type UpstreamStatus struct {
	Remote string // the remote the branch tracks, "" when none
	Branch string // the upstream branch name
	Ahead  int
	Behind int
	OK     bool
}

UpstreamStatus is the tracking state of the current branch.

func (UpstreamStatus) Diverged

func (u UpstreamStatus) Diverged() bool

Diverged reports history on both sides of the upstream: Git refuses a plain push and a fast-forward pull for it.

type WebRepo

type WebRepo struct {
	Host string // "github.com"
	Base string // "https://github.com/owner/repo"
}

WebRepo is a remote read as a web repository page.

func ParseWebRepo

func ParseWebRepo(address string) (WebRepo, bool)

ParseWebRepo reads a remote address (https, ssh://, git://, scp-like) as the repository's web page. Local paths and anything unparsable are refused.

func (WebRepo) CommitURL

func (w WebRepo) CommitURL(hash string) string

CommitURL is the commit's page on the hosting site.

func (WebRepo) Name

func (w WebRepo) Name() string

Name is the site's friendly name for menus ("GitHub"), else the host.

type WordRange

type WordRange struct {
	Start int
	End   int
}

WordRange is a rune-index [Start,End) span inside one line's text.

func WordDiff

func WordDiff(oldLine, newLine string) (oldRanges, newRanges []WordRange, ok bool)

WordDiff pairs one delete line with its adjacent add line and returns the changed rune ranges on each side. ok is false when the pairing is unhelpful (length caps, pathological size, or a mostly-rewritten pair).

type Worktree

type Worktree struct {
	Path     string
	Head     string
	Branch   string // "main" for refs/heads/main; "" when bare or detached
	Bare     bool
	Detached bool
}

Worktree is one checked-out work tree of the repository.

type WorktreeBackend added in v0.3.0

type WorktreeBackend interface {
	ListWorktrees(ctx context.Context, root string) ([]Worktree, error)
}

WorktreeBackend implements ListWorktrees: the main work tree first, then the linked ones in the order Git lists them; a work tree stopped in a rebase counts as detached, as `git worktree list` reports it.

type WriteBackend added in v0.3.0

type WriteBackend interface {
	// SwitchBranch checks out an existing local branch; Git's refusal to carry
	// conflicting local changes is returned, never forced.
	SwitchBranch(ctx context.Context, root, name string) error
	// CreateBranch creates a branch at base (a full ref or hash) and checks it out.
	CreateBranch(ctx context.Context, root, name, base string) error
	RenameBranch(ctx context.Context, root, name, to string) error
	// DeleteBranch is the safe delete: an unmerged branch is refused.
	DeleteBranch(ctx context.Context, root, name string) error
	// StashPush stashes with untracked files and a message (never empty).
	StashPush(ctx context.Context, root, message string) error
	StashPop(ctx context.Context, root string, index int) error
	StashApply(ctx context.Context, root string, index int) error
	StashDrop(ctx context.Context, root string, index int) error
	// CreateTag makes a lightweight tag at ref (HEAD when empty).
	CreateTag(ctx context.Context, root, name, ref string) error
	DeleteTag(ctx context.Context, root, name string) error
}

WriteBackend runs the last step of the simple write operations. Runner has validated every argument (branch names by check-ref-format, full hashes, stash references) and holds the repository's lock; a backend only executes. Each method does what the argv path's one command does, and a failure is reported like it (classified Error).

Jump to

Keyboard shortcuts

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