gitworkbench

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 22 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 (
	// 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 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 MaxPatchFileBytes = 8 << 20

MaxPatchFileBytes bounds a patch file Solco will apply.

View Source
const MaxPushRefs = 200

MaxPushRefs bounds one multi-ref push.

View Source
const MaxRebaseCommits = 100

MaxRebaseCommits bounds a plan.

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 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 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.

Types

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 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 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 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
}

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 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 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 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"
)

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 (*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 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 LineKind

type LineKind uint8

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

const (
	KindContext LineKind = iota
	KindAdd
	KindDelete
)

type OpClass

type OpClass string

OpClass separates read policy from mutation policy.

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

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.

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 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
	// 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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 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 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.

Jump to

Keyboard shortcuts

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