All 22 apps

CandyGit

Terminal Git client — staging, branching, log, diff, stash, worktrees, rebase

inspired by jesseduffield/lazygit git tui porcelain hostile-clone trust boundary

CandyGit code coverage

CandyGit is a terminal Git client on the SugarCraft stack: a three-pane TUI for staging, branching, log, diff, stash, worktrees, cherry-pick, merge and rebase. It mirrors the workflow of lazygit in native PHP rather than as a line-by-line port. Every verb shells out to your own git, so your hooks, GPG signing and credentials apply exactly as they do at the command line. Its u and Ctrl+r keys undo and redo the last mutations through a 100-entry history.

Install

composer require sugarcraft/candy-git:@dev

Requires PHP 8.3 or newer and git 2.23 or newer. The :@dev suffix is needed while the project's minimum-stability is stable: Packagist carries only the rolling dev-master branch until a stable tag is cut, so the bare requirement stops with does not match your minimum-stability.

CandyGit runs as a full-screen program. It needs an interactive terminal, and a piped stdout is refused rather than filled with escape sequences. It needs a checked-out work tree, since a bare repository has no status pane to show. At launch it checks git --version and refuses an older binary, or a missing one, with one sentence and exit status 1.

Quickstart

Run it from any git working tree:

cd path/to/your/repo
vendor/bin/candy-git

To embed the app in your own program, build the driver and the program yourself:

use SugarCraft\Core\Program;
use SugarCraft\Core\ProgramOptions;
use SugarCraft\Git\App;
use SugarCraft\Git\Git;

$git = new Git(getcwd());
(new Program(App::start($git), new ProgramOptions(useAltScreen: true)))->run();

The screen has three panes. Status is on the left, with the work-tree rows and the branch summary. Branches and log are stacked on the right. Tab cycles focus between the three, and each pane has its own verbs. The bottom line lists the keys for the focused pane.

What's in the box

Status paneParses git status --porcelain=v1 -b with per-row index and work flags and a branch-summary header.
Branches paneLists local and remote-tracking branches from git for-each-ref, with ahead and behind badges for tracked upstreams. The current branch is highlighted.
Log paneRecent commits, fetched in 20-commit pages as the cursor walks off the bottom. Each row shows the short SHA and the subject. Enter opens a read-only details view.
Stage, unstage, discards toggles staging through git add and git restore --staged. a stages all. d discards working-tree changes after a second press.
Diff viewerEnter on a status row renders the file's diff with highlighted hunks. Stage or unstage one hunk at a time.
Commit and amendc commits what you staged. A amends the last commit, with the collector pre-filled with its message. Both run through your git.
StashS creates, applies, pops and drops stash entries through git stash.
Branchesn creates a branch, Space checks one out, and D deletes one after a second press. The current branch is never deleted.
Worktreesw lists worktrees, adds one with a created branch, and removes one, all through git worktree.
Merge, rebase, cherry-pickM merges a typed ref. V cherry-picks a ref. r opens the sequencer menu (continue, abort, and skip on a rebase) while one is stopped. i previews the interactive-rebase todo; its mutating keys are parked and refuse with a notice.
Undo and redou steps back and Ctrl+r steps forward through HistoryManager, capped at MAX_HISTORY = 100 entries.
Pluggable driverThe GitDriver interface lets tests inject a fixture-backed driver, so the transition logic runs without staging a real repository.
Refresh on demandR reloads from disk. Cursors are clamped when the row count shrinks.
Localized stringsEvery user-facing string goes through Lang::t(): key hints, error labels, empty-state messages and git error text.

Concepts

The application is one immutable model. Every key returns a fresh App that owns the three lists, their cursors, the focused pane and the open overlays. The renderer is a pure function of that model, so a frame can be reproduced from a fixture. Only the Git driver and the Process runner touch the outside world.

Git calls are synchronous. Each one is a bounded subprocess with a 30-second default timeout, and it runs on the UI thread. That is deliberate for version 1: a slow remote can pause the screen while a fetch, pull or push runs. Moving git work to the event loop is the planned version 2 direction.

Every verb has one of three behaviors. It runs straight away, runs after a second press (d, f, p, P, D), or opens a prompt. History records each verb with its inverse. Where no safe inverse exists, undo refuses with a notice rather than pretending to undo.

Trust boundary

Opening a repository executes its configuration unless told otherwise, and git has several config keys that name executables. CandyGit runs every git call through a fixed argument prelude, -c core.quotepath=off -c core.fsmonitor=false, plus --no-ext-diff on diffs. That disarms the repository-controlled execution channels it can neutralize without breaking legitimate tooling. Merge drivers are enumerated on the merged config scope and each one is overridden with false before any merge-capable command. A driver shape that cannot be re-expressed makes the merge refuse outright.

Filter drivers (clean, smudge, process) are detected and announced on stderr rather than silently disarmed, because git-lfs-class tooling depends on them. Set CANDY_GIT_STRICT_FILTERS=1 to turn that announcement into a refusal. Git and other child processes start through Process::run(), which pins the environment, including GIT_TERMINAL_PROMPT=0. The one other proc_open caller is the Windows process-tree teardown in Platform, which spawns taskkill and the MSYS group-kill script under a bounded drain without that pinned environment.

A hostile clone can still reach a trusted global git-lfs driver through its .gitattributes. Operate only on repositories you trust. The full disclosure is in the README's Trust boundary section.

Tasks

Stage part of a file and commit

  1. Focus the status pane and press Enter on the file. The diff viewer shows its hunks, and the title carries a worktree or staged chip for the side you are viewing.
  2. Press [ and ] to move between hunks, and Space to stage the current one. The viewer stays open and lands on the next hunk. On the staged side, Space unstages instead, and it asks you to press twice. Each hunk goes into the index through git apply --cached.
  3. Press c, type the message, and press Enter. Tab inserts a newline; Esc cancels.

c commits only what is staged. Unstaged edits stay in the work tree.

Amend the last commit

Press A. The collector opens with the last message. Edit it and press Enter to rewrite HEAD, or submit it unchanged to keep the message. Undo refuses an amend, because the old commit cannot be restored from the history lane.

Undo the last operation

u reverses the most recent history entry. Undoing a commit moves the branch boundary back and re-arms the collector with your typed message, so no text is lost. Undoing a stage-all restores the exact prior selection, unless a file was partially staged, in which case undo refuses. Ctrl+r redoes, and a new operation clears the redo side.

Stash work in progress

Press S to open the stash overlay. Press u inside it to include untracked files. Apply keeps the entry and leaves the overlay open. Pop and drop ask once more before they run. A drop is undoable from the main view.

Work across worktrees

Press w on the branches pane to open the worktree manager. It lists worktrees, adds one, and removes one. A new worktree always gets a created branch: type a name with -b, or let git name the branch from the path's basename. CandyGit never creates a detached worktree.

Cherry-pick or merge a ref

Press V to cherry-pick. In a log view the cursor's commit fills in as the default ref. Press M to merge a typed branch or ref into the current branch. If a rebase, cherry-pick or conflicted merge stops, press r to continue, abort, or, on a rebase, skip.

Create a branch at a commit

Move the cursor to the commit in the log pane and press n. The collector reads new branch from <sha>:, and the branch starts at that commit.

API reference

The public surface is small: a driver, the immutable model, and the pure state objects the model carries. Tests replace the driver with a fixture, so the same model drives both the real program and the test suite.

ClassMethodDescription
Git__construct(cwd, timeout = 30.0)The shell-out driver. It runs every git call from cwd with the fixed prelude.
Gitstatus(), branches(), log(limit = 25)Read the status rows, the branch list, and a page of commits.
Gitstage(path), unstage(path), stageAll(), unstageAll()Stage and unstage whole files.
GitstagePatch(path, hunk), unstagePatch(path, hunk)Stage or unstage one hunk through git apply --cached.
Gitpush()Push the current branch. It refuses on a detached HEAD.
GitDriverinterfaceThe contract that App consumes. Tests inject a fixture-backed implementation.
Appstart(GitDriver): selfBuilds the app model for a driver.
DiffViewercurrentHunkPatch(): string, hunkCount(): intThe selected hunk as a patch, and the number of hunks. The patch is empty when the diff has no hunks.
StashManagerfuzzyFilter(query): selfRanks stash entries by message and branch through sugar-fuzzy. The stash overlay's / search calls it when Enter commits the query.
HistoryManagerpush(HistoryEntry): selfAdds an undoable entry and clears the redo lane. The cap is MAX_HISTORY = 100.
PaneStatus, Branches, Log; next()The pane enum, with next() for Tab cycling.
Langt(key, params)Translation lookup in the git namespace. See Internationalization.

Only methods declared in candy-git/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.

SugarCraft\Git

App final class

Three-pane git TUI: status (left), branches (top right), log (bottom right). Tab cycles focus; up/down moves the cursor in the active pane; s stages / unstages the highlighted status entry; a stages all files; Space (branches pane) checks out the selected branch; c opens inline commit message collection; ? shows the help overlay; R refreshes from disk. u / Ctrl+r for undo/redo. f / p / P fetch, pull and push the tracked remote (each behind the same armed confirm as the destructive verbs).

MethodSummary
__construct(public readonly GitDriver $git, public readonly array $status = [], public readonly array $branches = [], public readonly array $log = [], public readonly string $branchSummary = '', public readonly Pane $pane = Pane::Status, public readonly int $statusCursor = 0, public readonly int $branchesCursor = 0, public readonly int $logCursor = 0, public readonly int $logDepth = self::LOG_CHUNK, public readonly ?string $error = null, public readonly bool $showHelp = false, public readonly int $helpScroll = 0, public readonly bool $collectingCommit = false, public readonly bool $commitGpgSigns = false, public readonly bool $hooksAnnounced = false, public readonly string $commitMessage = '', public readonly bool $commitAmend = false, public readonly ?DiffViewer $diffViewer = null, public readonly bool $collectingBranchName = false, public readonly string $branchName = '', public readonly ?string $successMessage = null, public readonly ?string $notice = null, public readonly bool $collectingMergeTarget = false, public readonly string $mergeTarget = '', public readonly bool $showRebaseMenu = false, public readonly string $rebaseMenuKind = 'rebase', public readonly ?string $pendingConfirm = null, public readonly ?HistoryManager $history = null, public readonly ?StashManager $stashManager = null, public readonly bool $collectingStash = false, public readonly string $stashMessage = '', public readonly bool $stashUntracked = false, public readonly bool $stashFiltering = false, public readonly string $stashFilterQuery = '', public readonly ?CherryPick $cherryPick = null, public readonly ?Worktrees $worktrees = null, public readonly ?InteractiveRebase $interactiveRebase = null, public readonly ?string $pendingBranchBase = null, public readonly ?int $width = null, public readonly ?int $height = null)
static start(GitDriver $git): self
init(): ?\Closure
update(Msg $msg): array
view(): string
paneWidth(): intWidth of each of the two side-by-side pane columns. Derived from the terminal width reported via WindowSizeMsg — the two columns split the width minus the border/padding/gutter overhead — and falls back to the historical constant until a size arrives so first-frame output stays byte-stable.
listRows(): ?intRows available for the pane/overlay area after fixed chrome (header row, help line, trailing row) and any notice or prompt bars. null until the terminal reports its size — callers then treat lists as unbounded, which is the historical byte-stable first-frame output (the height was stored but never read, so every list and overlay rendered in full and appended below each other off the bottom of the screen).
hintRows(): intRows the key-hint strip gets (candy-git-032). The monolithic sentence put the rarest verbs first, so q and ? — the two affordances the strip exists for — never survived truncation at any realistic width. The contextual rebuild uses a second row when the screen can pay it (>= 16 rows: a laptop frame still has six pane rows); short frames keep one row, and essentials-first ordering guarantees that row ends with the verbs the pane actually answers to, not with 'quit'.
overlayOpen(): boolWhether a full overlay is open and must share the screen with the lists.
rightColumnBodyRows(): intBody rows shared by the right-column pair after both frames pay their two border rows. The pair used to floor independently at 1 each, so the stack demanded branches(3)+log(3)=6 rows from a 5-row area on an h=8 terminal — the log body vanished behind the hard ceiling while the frame still claimed it was rendered (candy-git-033). Deriving the budget from the enforced minimums keeps demand ≤ supply at every height: a pane appears only when its borders plus one body row fit.
statusBodyRows(): intVisible status-list rows (frame borders excluded; 0 = no room for the pane).
branchesBodyRows(): intVisible branch-list rows: the right column stacks branches over log.
logBodyRows(): intVisible log rows: the right-column remainder below branches.
overlayBodyRows(): intRows an open overlay gets; a tiny floor so short screens still show a frame.
cursorTarget(): ?stringThe plain-text cursor modeline: what the keyboard currently acts on.
barWidth(): intHorizontal budget for full-width prompt/notice bars.
statusPathWidth(): intStatus-pane path budget: pane width minus padding (2) and the 3-col "XY " marker.
branchNameWidth(): intBranch-name budget: pane width minus padding (2) and the 2-col current-branch marker.
logSubjectWidth(): intLog-subject budget: pane width minus padding (2) and the short-sha + 2-space gap (8).
isTyping(): boolWhether a text-collection buffer currently owns the keyboard: in these states printable keys belong to the buffer, and global quit keys that collide with letters (q) must not fire. Escape/Ctrl+C still cancel via the global chain — only the letter collision is gated.
refresh(): self
subscriptions(): ?\SugarCraft\Core\Subscriptions

CherryPick final readonly class

Cherry-pick state — tracks whether we're collecting a commit ref and any in-progress cherry-pick result.

MethodSummary
__construct(public bool $collecting = false, public string $commitRef = '')
static collecting(): selfEnter commit-ref collection mode.
withCommitRef(string $ref): selfReturn a new CherryPick with the given commit ref.

DiffHighlighter final class

Parse-side of the diff-view syntax highlighting: answers which language a file is and which tokens a diff line contains.

MethodSummary
static languageForPath(string $path): stringLanguage id for a repo-relative file path, '' when unrecognized.
static tokenizeLine(string $line, string $language): ?arrayTokenise the CONTENT of one diff body line, or null when the line must render exactly as the plain whole-line path does.

DiffViewer final readonly class

Immutable value object representing a file's unified diff with an interactive hunk cursor.

MethodSummary
__construct(public array $lines, public int $hunkCursor, public string $path, public array $hunkStarts, public array $header, public bool $cached = false, public int $scrollOffset = 0, public bool $readOnly = false, public string $commitSha = '', public bool $partialTail = false)
static fromCommitDetails(string $sha, array $lines): selfBuild the read-only commit display from git show --stat --format=full --patch --no-color output (candy-git-015). The @@ scan still runs: the patch half of the blob carries hunks, and j/k navigation stays honest about what is on screen — but readOnly locks the staging lane shut.
static fromRawDiff(string $path, array $lines, bool $cached = false): selfBuild a DiffViewer from raw git diff --no-color -- <path> output.
currentHunkLines(): arrayReturns the hunk lines around hunkCursor, for rendering and staging.
currentHunkPatch(): stringThe raw patch for just the current hunk (for git apply --cached).
hunkIndex(): int0-based position of the selected hunk within $hunkStarts.
currentHunkLine(): intLine index in $lines where the selected hunk starts.
withHunkIndex(int $index): selfSelect the hunk at 0-based position $index in $hunkStarts (clamped). candy-git-059: this parameter is a HUNK INDEX; the stored cursor stays the line index it selects, which is what the windowing needs.
withScrollOffset(int $offset): selfFirst visible line of the window (clamped to the diff body). candy-git-045.
scrollBy(int $delta): selfScroll the window by $delta lines without touching hunk selection.
hunkCount(): intNumber of hunks in this diff.

Git final class

Thin wrapper around git invocations. Everything that mutates a repo shells out — no libgit2 binding, no in-PHP plumbing-command reimplementation. The wrapper is split out so tests can swap in a fixture-backed Git (or its parent interface, GitDriver) without touching the runtime.

MethodSummary
__construct(public readonly string $cwd, public readonly float $timeout = self::DEFAULT_TIMEOUT, public readonly float $mutateTimeout = self::MUTATE_TIMEOUT, ?bool $strictFilters = null)
withStrictFilters(bool $strict = true): selfImmutable derive: the same instance in strict (or relaxed) filter mode.
static verbOf(array $args): stringThe git verb of an argv: the first non-flag argument (candy-git-091 - global flags like --no-optional-locks may now precede it). '' when the invocation carries no verb at all.
static isMutatingVerb(string $verb): bool
budgetFor(array $args): floatWall-clock budget for this argv (candy-git-121): reads vs mutators.
static timeoutMessage(bool $mutator, float $budget): stringTimeout copy for a lane (candy-git-121): the mutator warns about repair.
status(): array
static isRepository(string $cwd): boolProbe whether $cwd sits inside a git working tree, including a LINKED worktree where .git is a FILE (a gitdir: pointer), not a directory. is_dir("$cwd/.git") wrongly rejects linked worktrees; asking git to resolve --absolute-git-dir succeeds in both layouts, so a zero exit with a non-empty git dir is the authoritative "yes, this is a repo".
static isBareRepository(string $cwd): boolBare repos answer rev-parse --is-bare-repository with true. They have no work tree, so every status-pane verb (stage, discard, stash) is meaningless here — the launcher refuses one instead of booting a TUI whose whole first pane would error.
branches(): array
log(int $limit = 25): array
commitGpgSigns(): boolDoes committing here go through GPG (and therefore gpg-agent's pinentry)? True when commit.gpgsign resolves true and gpg.format is not ssh: SSH-format signing rides the ssh-agent socket the user already unlocked, while classic GPG prompts on /dev/tty - an input channel candy-git's stdin isolation cannot fence (candy-git-054). Exit-code probes, never run(): "key not set" is the common case.
stage(string $path): void
unstage(string $path): void
checkout(string $branch): void
checkoutRemote(string $remoteBranch): voidDWIM checkout of a remote-tracking branch: --track origin/feature creates (or re-attaches) the local feature with origin/feature as its upstream, instead of the detached HEAD a plain checkout of a remote ref would give (candy-git-037).
commit(string $message): void
stageAll(): void
conflictedPathsCarryingMarkers(): arrayPaths git still reports as unmerged whose FILE BYTES carry conflict markers. git add -A is marker-blind (it stages whatever is on disk, candy-git-090) - so staging-all during a conflicted merge can commit the literal <<<<<<< machinery as resolved content. The App arms a named confirm for exactly this list.
localHooksPresent(): boolDoes this repository ship live hooks that git will run for us? .git/hooks is not cloned, but a supplied or dev-image repo can carry executable hooks, and every other repo-controlled execution channel candy-git either disarms or announces (candy-git-144) - hooks ride the all-verbs posture, so they get the same honesty: probe here, announce in-app, document in the trust boundary. Linked worktrees share the MAIN git dir, which is where the live hooks actually sit.
unstageAll(): void
unstagePatch(string $path, string $hunk): void
diff(string $path, bool $cached = false): arrayUnified diff lines for one file.
discard(string $path): void
untrackedDiff(string $path): arrayThe diff of an untracked path: every line as an addition. Plain git diff emits nothing for ?? rows, so the routine "what is this new file" action opened an empty box (candy-git-035). The shape is git's own new-file patch (byte-verified against git diff --no-index -- /dev/null <path>), built from a file read - not a spawn - so hosts without /dev/null are unaffected and the spawn census does not move.
deleteUntracked(string $path): voidDelete an untracked file from disk. git has no restore verb for ?? paths (git restore answers pathspec-did-not-match), so an armed d on an untracked row is a true unlink - unrecoverable, which is why the UI asks twice (candy-git-035).
amend(): void
amendWith(string $message): voidRewrite the last commit with a new message in one step — what editing the pre-filled collector submits (candy-git-013: amend was a blind --no-edit keypress because there was no way to author a message here).
lastCommitMessage(): stringThe raw message of the last commit, body included (%B), used to pre-fill the amend collector. The trailing newline git appends after the body is trimmed; blank lines inside the message are kept whole.
stagePatch(string $path, string $hunk): void
createBranch(string $name, ?string $from = null): void
commitDetails(string $ref): arrayFull commit display: headers, message, stat summary and the patch in one stdout slice (show --stat --format=full --patch). Feeds the log pane's read-only details overlay (candy-git-015). --no-color keeps the ANSI channel ours alone.
revert(string $ref): voidInvert a commit onto HEAD as a new commit (revert --no-edit — the message is git's own, no editor is ever asked for).
resetHard(string $ref): voidMove HEAD to a ref and make the worktree match, discarding uncommitted bytes (reset --hard). Destructive by definition — the UI arms it.
deleteBranch(string $name): void
restoreBranch(string $name, string $sha): voidRe-point a branch name at a recorded commit (undo of a deletion).
merge(string $branch): void
mergeAbort(): voidAbandon a stopped merge: git restores the pre-merge index and worktree. Called from the sequencer menu while sequenceState() reports 'merge'; on a clean repo git exits nonzero and the refusal surfaces as an error.
mergeContinue(): voidCommit the resolution of a conflicted merge.
fetch(): void
pull(): void
push(): void
rebaseContinue(): void
rebaseAbort(): void
rebaseSkip(): void
reset(): void
stashList(): array
stashApply(string $stashRef): void
stashDrop(string $stashRef): void
stashPush(?string $message, bool $keepIndex = false, bool $includeUntracked = false): void
stashPop(string $stashRef): void
stashSha(string $stashRef): stringResolve a stash ref to its commit sha (candy-git-120). One rev-parse away was all it took to make drop recoverable: the entry object in the overlay cannot be trusted for this because git's named-message decoration ('On <branch>: <msg>') carries no sha at all.
stashSubject(string $stashRef): stringThe entry's reflog subject ('On <branch>: <msg>' / 'WIP on ...') - the exact text git stash list displays (candy-git-120). Capture it BEFORE the drop: a restored entry without it reads 'Created via "git stash store".' and the user's message silently dies.
stashRestore(string $sha, string $subject = ''): voidRe-insert a dropped stash entry at the TOP of the stash list (candy-git-120). The entry is its own commit - parents intact - so git stash store recreates the ref; only the POSITION is lost, and the arm copy says so. The -m carries the captured subject because stash list displays it; without it the entry returns anonymous. The worktree and index are not touched by this lane at all.
cherryPick(string $commit): void
cherryPickContinue(): void
cherryPickAbort(): void
worktreeList(): array
worktreeAdd(string $path, string $branch): void
worktreeRemove(string $path): void
sequenceState(): stringWhich sequencer (if any) is stopped mid-flight waiting for attention.

GitDriver interface

Pluggable git backend. Production is Git (shells out to the git binary). Tests inject a fixture closure-driven implementation so transition correctness can be asserted without staging real repos in tmp dirs.

MethodSummary
status(): arrayParse git status --porcelain=v1 -b.
branches(): array
log(int $limit = 25): array
stage(string $path): void
unstage(string $path): void
checkout(string $branch): void
checkoutRemote(string $remoteBranch): voidCheck out a remote-tracking branch (origin/feature) as a local branch tracking it — the DWIM leg of the branches-pane Space key (candy-git-037).
commit(string $message): void
stageAll(): void
diff(string $path, bool $cached = false): array
discard(string $path): voidDiscard working-tree changes for a file (git restore --worktree <path>).
untrackedDiff(string $path): arrayThe all-additions diff of an untracked path (candy-git-035: a plain diff is empty for ?? rows, so the review action opened a blank box). Read from the file, never spawned.
deleteUntracked(string $path): voidRemove an untracked file from disk - the armed d on a ?? row. git restore cannot touch untracked paths, so this is a true, unrecoverable unlink (candy-git-035).
amend(): voidAmend the last commit without changing its message (--no-edit).
amendWith(string $message): voidRewrite the last commit with a new message (candy-git-013: the pre-filled amend collector submits through here).
lastCommitMessage(): stringThe last commit's raw message (body included), used to pre-fill the amend collector. Throws when there is no HEAD yet.
commitGpgSigns(): boolWhether a commit here will be GPG-signed through gpg-agent's pinentry on /dev/tty (candy-git-054) — the commit collector's hint lane uses this to warn before the signing step can paint over the frame.
conflictedPathsCarryingMarkers(): arrayRepo-relative paths git still reports as unmerged whose file bytes carry conflict markers (candy-git-090) - the App arms a named confirm for staging all when this list is non-empty, because git add -A is marker-blind.
localHooksPresent(): boolWhether the repository ships executable hooks that our own commit verbs will run unannounced (candy-git-144) - the collector warns once per session when this is true.
stagePatch(string $path, string $hunk): voidStage a single hunk via git apply --cached.
unstageAll(): voidUnstage all staged changes (inverse of stageAll).
unstagePatch(string $path, string $hunk): voidUnstage a single hunk by applying the patch in reverse.
createBranch(string $name, ?string $from = null): voidCreate and switch to a new branch.
commitDetails(string $ref): arrayFull commit display — headers, message, stat summary and patch. Feeds the log pane's read-only details overlay (candy-git-015).
revert(string $ref): voidInvert a commit onto HEAD as a new commit (revert --no-edit).
resetHard(string $ref): voidMove HEAD to a ref and overwrite the worktree (reset --hard). Destructive by definition — the UI arms it.
deleteBranch(string $name): voidDelete a branch (safe, -d flag).
restoreBranch(string $name, string $sha): voidRestore a deleted branch pointing at a previously recorded sha.
merge(string $branch): voidMerge a branch into the current branch.
mergeAbort(): voidAbandon a stopped (conflicted) merge, restoring the pre-merge state.
mergeContinue(): voidCommit the resolution of a conflicted merge (continue leg).
fetch(): voidFetch from the default remote: updates tracking refs, never the worktree.
pull(): voidPull the tracked remote branch into the current one (merge back-end, non-interactive).
push(): voidPush the current branch. A branch without an upstream goes to origin with --set-upstream recorded; a detached HEAD has no branch to push and throws.
rebaseContinue(): voidContinue an in-progress rebase.
rebaseAbort(): voidAbort an in-progress rebase.
rebaseSkip(): voidSkip the current rebase commit.
reset(): voidReset HEAD to the parent of the last commit (undo last commit, keep changes staged).
stashList(): arrayList stashes (parse git stash list).
stashApply(string $stashRef): voidApply a stash by its ref (e.g. "stash@{0}").
stashDrop(string $stashRef): voidDrop (delete) a stash by its ref.
stashPush(?string $message, bool $keepIndex = false, bool $includeUntracked = false): voidCreate a stash from the current worktree/index (git stash push).
stashPop(string $stashRef): voidPop a stash: apply then drop (candy-git-014). Composed from the two guarded verbs rather than spawning git stash pop — a conflicted apply throws before the drop, so the entry survives for a retry, and the merge-capable dispatch guard already verifies the apply shape without needing a new argv lane in its tables.
stashSha(string $stashRef): stringResolve a stash ref to its commit sha (candy-git-120).
stashSubject(string $stashRef): stringRe-insert a dropped stash entry at the top of the stash list (candy-git-120).
stashRestore(string $sha, string $subject = ''): void
cherryPick(string $commit): voidCherry-pick a commit.
cherryPickContinue(): voidContinue an in-progress cherry-pick.
cherryPickAbort(): voidAbort an in-progress cherry-pick.
worktreeList(): arrayList worktrees (parse git worktree list --porcelain).
worktreeAdd(string $path, string $branch): voidAdd a new worktree at $path. A non-empty $branch is CREATED from HEAD (-b); an empty one lets git name the branch from the path basename. Neither leg detaches (CG-24).
worktreeRemove(string $path): voidRemove an existing worktree at $path.
sequenceState(): stringSequencer stop state: 'rebase' | 'cherry' | 'merge' | '' (none).

HistoryEntry final readonly class

Immutable value object representing a single entry in the undo/redo history.

MethodSummary
__construct(public string $op, public array $args, public string $inverseOp, public array $inverseArgs)
static stage(string $path): selfConvenience factory for stage operations.
static unstage(string $path): selfConvenience factory for unstage operations.
static discard(string $path): selfConvenience factory for discard operations.
static deleteUntracked(string $path): selfDeleting an untracked file destroyed bytes no git object ever held - the inverse would need a backup that does not exist (candy-git-035), so it joins the refuse-undo lane with discard.
static checkout(string $from, string $to): selfConvenience factory for checkout (branch switch) operations.
static commit(string $message): selfConvenience factory for commit operations.
static amend(): selfConvenience factory for amend operations.
static createBranch(string $name, string $from, string $base = ''): selfConvenience factory for branch creation.
static revert(string $sha): selfConvenience factory for reverting a commit (candy-git-015).
static resetHard(string $sha): selfConvenience factory for resetting HEAD hard (candy-git-015).
static stageAll(array $stagedPaths = [], bool $partial = false): selfConvenience factory for stage-all, carrying what the index looked like BEFORE the sweep (candy-git-042).
static stagePatch(string $path, string $hunk): selfConvenience factory for stage patch (hunk).
static unstagePatch(string $path, string $hunk): selfConvenience factory for unstage patch (hunk) — the cached-side gesture of the diff viewer (candy-git-034). Its forward arm was already routed; the missing piece was an entry that remembers the side it came from, so undo stages the hunk back.
static merge(string $branch): selfConvenience factory for merge.
static stashDrop(string $ref, string $sha, string $subject = ''): selfA dropped stash is recoverable while its commit survives the reflog/GC grace (candy-git-120): the inverse re-inserts the entry at the top of the stash list via update-ref. The position it had is NOT preserved - the API says so instead of pretending. Without a captured sha (a capture that failed, fixture rows) the entry refuses undo.
static deleteBranch(string $name, string $sha): self

HistoryManager final readonly class

Manages undo/redo stacks for command history.

MethodSummary
__construct(public array $undoStack = [], public array $redoStack = [])
push(HistoryEntry $entry): selfPush a new entry onto the history. Clears the redo stack. Returns a NEW HistoryManager with the entry added, oldest-dropped once the lane exceeds MAX_HISTORY.
undo(): arrayPop and return the most recent entry for undo, or null if empty. The popped entry is moved to the redo stack. Returns BOTH the popped entry AND the new manager.
redo(): arrayPop and return the most recent entry for redo, or null if empty. The popped entry is moved back to the undo stack. Returns BOTH the popped entry AND the new manager.
canUndo(): boolReturns true if there is at least one entry on the undo stack.
canRedo(): boolReturns true if there is at least one entry on the redo stack.

InteractiveRebase final readonly class

Interactive rebase todo state — a READ-ONLY preview list built from the recent commits. Action cycling and dropping were preview theatre (candy-git-011): the todo is discarded on Esc and nothing is ever executed. Parked per gate G1 (2026-11-14): the App refuses the mutating keys with the preview-only notice; the model methods below stay as the building blocks for the wire arm (temp todo + GIT_SEQUENCE_EDITOR) should the owner commission it. Wiring it needs a GitDriver execution method and an Enter arm; the completion, error and cancel plumbing that anticipated them is deleted as speculation (candy-git-029 part 3).

MethodSummary
__construct(public array $commits, public int $cursor = 0, public bool $selectingN = true, public string $countInput = '', public ?string $error = null)
static buildFromLog(array $commits): arrayBuild the todo list from recent commits.
static selectingN(): selfStart interactive rebase by selecting number of commits.
withCountDigit(string $digit): selfReturn a new InteractiveRebase with an added digit to the count.
confirmCount(array $logCommits): selfFinalize count selection and build the todo list from log.
withCursor(int $dir): selfMove cursor up/down through the commit list.
cycleAction(): selfCycle the action for the current commit.
dropCurrent(): selfRemove (drop) the current commit from the list.

Lang final class

Per-library translation facade for candy-git.

Pane enum

Which pane has focus. The Tab key cycles forward through them. Every pane carries the row cursor and viewport movement; the status pane is the one that takes file-line actions (stage/unstage/discard/diff) and the branches pane the one that takes branch actions (Space checkout, D delete, w worktrees overlay), while the log pane opens commit details and acts on the commit under the cursor (candy-git-015). Repo-wide verbs — commit, amend, new branch, merge, cherry-pick, rebase, undo/redo — dispatch regardless of which pane holds focus.

Cases: Status · Branches · Log

PHP also provides cases(), from() and tryFrom().

MethodSummary
next(): self

Platform final class

The OS seam under Process: every place the subprocess runner differs between POSIX and Windows is answered here, and nowhere else.

MethodSummary
static new(): selfThe host platform.
static posix(): self
static windows(): self
isWindows(): bool
nullDevice(): stringPath whose read end is an immediate EOF (the child's stdin when no payload is given).
withNullDevice(string $path): self
withKillTree(\Closure $killTree): self
findExecutable(string $name, ?string $path = null): ?stringResolves a program on PATH the way the OS would (PATHEXT suffixes on Windows), or null. Lets the CLI tell "git is not installed" apart from "git is installed but could not be launched".
resolveSpawnProgram(array $argv, ?string $path = null): arrayRewrite a bare argv[0] to its OS-resolved path, the way cmd.exe would. CreateProcess appends only .exe to a bare program name, so a git that ships as git.cmd - a shim, or a PATH wrapper - dies with error 2 at spawn time on the very hosts where it IS installed. Resolving through findExecutable walks the same PATHEXT family. Best-effort by contract: tokens that already spell a path, and names nothing resolves, are handed back untouched so spawnFailure's reason stays honest.
killTree(int $pid): voidForce-stop the process tree rooted at $pid (Windows ladder only).

Process final class

Runs an external command with a wall-clock timeout.

MethodSummary
static childEnv(?array $inherit = null): arrayEnvironment handed to every child: the parent's environment plus git-specific overrides. Each override closes a real way a repo- or user-controlled setting could block or hijack a synchronous git call made from inside the TUI:
static run(array $argv, ?string $stdin = null, float $timeout = 30.0, ?Platform $platform = null): array

RebaseAction enum

Represents a single action in an interactive rebase todo list.

Cases: Pick · Reword · Edit · Squash · Drop

PHP also provides cases(), from() and tryFrom().

RebaseCommit final readonly class

A commit entry in the interactive rebase todo list.

MethodSummary
__construct(public readonly string $sha, public readonly string $subject, public readonly RebaseAction $action = RebaseAction::Pick)
withAction(RebaseAction $action): selfReturn a new RebaseCommit with a different action.

Renderer final class

Pure view function. Renders three panes side-by-side; the focused pane gets a brighter border accent plus a self::FOCUS_MARKER text prefix on its title, so focus never rides the color channel alone.

MethodSummary
static render(App $a): string

StashEntry final readonly class

Represents a single stash entry.

MethodSummary
__construct(public readonly int $index, public readonly string $sha, public readonly string $branch, public readonly string $message)
displayLine(): stringFormat for display in the stash list.
stashRef(): stringThe stash ref for git commands (e.g. "stash@{0}").

StashManager final readonly class

Immutable stash manager state — tracks the stash list and its selection cursor.

MethodSummary
__construct(public array $stashes, public int $cursor = 0)
static fromGitOutput(array $lines): arrayBuild a StashManager from raw git stash list output.
withCursor(int $dir): selfReturn a new StashManager with the cursor moved by $dir (clamped).
withStashes(array $stashes): selfReturn a new StashManager with updated stash list.
fuzzyFilter(string $query): selfFilter stashes using fuzzy search on message and branch fields.
current(): ?StashEntryThe currently selected stash entry, or null if list is empty.
count(): intNumber of stashes in the list.

TerminalGate final class

The launcher's terminal-access decision, as one pure truth table.

MethodSummary
static decide(bool $outTty, bool $inTty, bool $isWindows, callable $openTty): array

WorktreeEntry final readonly class

Represents a single git worktree.

MethodSummary
__construct(public readonly string $path, public readonly string $branch, public readonly bool $detached = false)
static fromGitOutput(array $lines): arrayParse git worktree list --porcelain output into WorktreeEntry list.

Worktrees final readonly class

Immutable worktree manager state — the list of worktrees and its cursor.

MethodSummary
__construct(public array $worktrees, public int $cursor = 0, public bool $adding = false, public string $newPath = '', public string $newBranch = '', public string $addField = 'path', public bool $removing = false)
static fromGitOutput(array $lines): arrayParse git worktree list --porcelain output into WorktreeEntry list.
withCursor(int $dir): selfMove cursor up/down.
startAdding(): selfEnter "add new worktree" mode.
withNewPath(string $path): selfUpdate new worktree path being typed.
withNewBranch(string $branch): selfUpdate new worktree branch being typed.
toggleAddField(): selfFlip which add-form field the keyboard edits (CG-24: the branch slot existed in the model but no surface could ever fill it).
activeText(): stringThe buffer of the field currently being edited.
withActiveText(string $text): selfReplace the buffer of the field currently being edited.
appendActive(string $text): selfAppend to the buffer of the field currently being edited (pastes).
cancelAdding(): selfCancel add mode.
startRemoving(): selfEnter remove-confirm mode for current worktree.
cancelRemoving(): selfCancel remove mode.
current(): ?WorktreeEntryCurrent worktree entry, or null.
count(): intCount of worktrees.

SugarCraft\Git\Support

GitRequirement final class

The git-version floor candy-git relies on, kept as pure string math so the launcher and the tests share one authority.

MethodSummary
static parse(string $banner): ?stringExtract "major.minor" from a git --version banner.
static satisfies(string $version): boolDoes a "major.minor" string clear MINIMUM?

Version final class

The version string this tool reports on --version.

MethodSummary
static line(): stringThe --version line: plain text, newline-terminated, produced by no state and no host probe — the flag must answer anywhere.
static current(): stringThe version this process reports: the archive stamp when running from a stamped phar, self::CURRENT everywhere else.
static fromPharMetadata(string $path): ?stringThe version a phar archive at $path was built to carry, or null when it names none (unreadable archive, wrong metadata shape, the dev-build sentinel, or an empty stamp). Every refusal is a null, never an exception — --version must answer on a machine whose phar cannot be opened.
static versionFromMetadata(mixed $metadata): ?stringThe judgement on the stamp itself, split out because the archive-open leg is unreachable from a suite that must not build phars: the release namespace strip, the dev-build refusal, and the wrong-type nulls are a pure function over what getMetadata() answers.
static hostArchive(): stringThe filesystem path of the phar this process was launched from, or '' when it was not launched from one — the two-identity law measured on candy-code's real builds and pinned by the bin autoload guard: inside archive-loaded code Phar::running(false) answers the archive path, while the stub context answers '' and there a '.phar'-suffixed __DIR__ is the enclosing archive.

Configuration

CandyGit has no configuration file. Its behavior comes from the command line, the environment, and the repository's own git configuration.

Command-line flags

FlagEffect
--versionPrints the version line and the phar build stamp, then exits 0. Works outside a repository.
--help, -hPrints usage, then exits 0. Works outside a repository.
any other argumentRefused. The program exits 2 and names the argument, pointing at --help.

Environment

VariableDefaultEffect
CANDY_GIT_STRICT_FILTERSunsetSet to 1, true or yes to refuse repositories whose filter drivers would run. Unset, filter drivers are announced on stderr and allowed to run.
NO_COLOR, TERM, COLORTERMdetectedRead at launch through the color-profile detection. NO_COLOR strips color. TERM=dumb turns color off, but the full-screen alternate screen and cursor addressing are still used, so the terminal has to accept those sequences.
PATHsystemLocates the git binary. A launch failure that is not a missing git prints the OS reason.

Fixed limits

LimitValue
Git call timeout30 seconds per read call; 120 seconds per mutating call (fetch, pull, push, commit, merge, rebase and the other verbs in Git::MUTATING_VERBS)
Log page size20 commits per fetch
Undo and redo history100 entries (HistoryManager::MAX_HISTORY)
Minimum git version2.23 (GitRequirement::MINIMUM)

Keys

Keys work in the pane where they are listed. The ? overlay shows the verbs for the focused pane.

KeyAction
TabCycle focus between the status, branches and log panes
↑/↓ or k/jMove the cursor in the focused pane
PageUp / PageDownMove the cursor one page
Home / EndMove to the first or last entry
s (status)Stage or unstage the highlighted file
a (status)Stage all files
d (status)Discard changes to the highlighted file (press twice). On an untracked file it deletes the file from disk, which cannot be undone
Enter (status)Open the diff viewer for the highlighted file. In the viewer, Space stages or unstages the current hunk, [ and ] move between hunks, and Esc or d closes it
Enter (log)Open the commit's read-only details view
f, p, PFetch, pull, or push (each press twice); P refuses on a detached HEAD
Space (branches)Check out the branch. On a remote-tracking branch it creates a local branch of that name, or checks out the existing one
cCommit what you staged through the message collector
AAmend the last commit, with the collector pre-filled
nCreate and switch to a new branch
D (branches)Delete the selected local branch (press twice). Never the current one
MMerge a typed branch or ref into the current branch
rSequencer menu. It appears only while a rebase, cherry-pick or conflicted merge is stopped
SStash manager: create, apply, pop, drop
VCherry-pick a commit ref
w (branches)Worktree manager: list, add, remove
iInteractive-rebase todo list, as a preview only
u, Ctrl+rUndo the last operation; redo it
RRefresh from disk
?Context-sensitive help
qQuit. It closes the innermost overlay first
EscCancel the innermost overlay or collection. Quits when nothing is open
Ctrl+CActs like q while idle, and like Esc while typing, where it drops the half-typed draft

Inside a text buffer every printable key is typed, so q is just a letter. Ctrl+W and Ctrl+U delete a word or the line, and a bracketed paste inserts the whole sanitized blob with its line structure. Remote-tracking branches appear with divergence badges such as [↑2 ↓1], or [!] when the upstream has vanished. Those are read-only for D.

Theme, styling and accessibility

Every state the interface needs you to know is carried by text, not by color alone. Status rows show git's porcelain XY codes, and diff lines keep their leading + and -. The rebase todo spells its actions as words: pick, reword, edit, squash, drop. The ahead-and-behind summary is git's own header. The panes stay readable under NO_COLOR, under TERM=dumb, or with an ASCII-only palette.

The focused pane shows two signals: the accent border and a ▸ text marker before its title. The selected row uses reverse video on styling terminals. The frame also carries a plain-text cursor: line that names the selected file, branch, commit or overlay entry. It has no styling, so it stays visible under every palette, including TERM=dumb.

The palette is not tuned for WCAG conformance, and it does not promise a measured contrast ratio for the hint strip or the unfocused border. Actual contrast depends on your terminal palette, so check the colors against your own background.

Internationalization

User-facing strings use SugarCraft\Git\Lang::t(). The catalog is lang/en.php, and the other locales are under lang/, 16 files in all. Only the twelve git.* keys carry a git. prefix inside the file, and you pass those as written: Lang::t('git.timeout'). Every other key has no prefix and is passed as written too: Lang::t('status.clean') and Lang::t('cli.not_a_repo'). The facade adds the library namespace on lookup, so the shared registry sees git.git.timeout and git.status.clean. Lang::t('timeout') does not resolve. It returns the prefixed key git.timeout rather than a message, so always call through SugarCraft\Git\Lang.

KeyDefault textParameters
git.spawn_failedgit: failed to spawn: {reason}reason
git.errorgit: {stderr}stderr
git.timeoutgit: command timed out after {seconds}sseconds
cli.not_a_repocandy-git: not a git repository: {cwd}cwd
ui.error_prefixerror: none
status.cleanclean working treenone
branches.empty(no branches)none
log.empty(empty log)none

To localize, copy lang/en.php to lang/<code>.php and translate the values. The cli.not_a_repo refusal fires when git rev-parse --absolute-git-dir fails in the working directory. Linked worktrees, where .git is a file, are accepted.

Examples

Both examples are hermetic. They render a fixture-backed driver, so they need no repository. Each one is interactive. In a terminal it runs until you quit it. When stdin reaches end of file, it renders one frame and exits 0.

  • examples/play.php is the pane tour, with status, branches and log. Run it in a terminal with php examples/play.php, and press q to quit. Non-interactively, printf 'q' | php examples/play.php renders one frame and exits 0. With stdin at /dev/null it also renders one frame and exits 0, so it never blocks a script or CI job. It keeps running only while stdin is an open pipe or terminal, so write a key to an open stream to drive it.
  • examples/stage.php is the staging demo, where s stages and unstages rows that visibly change. Run it with php examples/stage.php. Piping sq into it exits 0, and so does stdin at /dev/null.

The VHS tapes drive these examples, not the live binary, so the recorded output does not depend on the state of a repository. tests/ExamplesSmokeTest.php compiles each example against the live driver interface and boots the app, so a driver change that breaks an example fails the suite.

Testing

Run the suite from the package root after composer install:

vendor/bin/phpunit

Most tests drive the model with a fixture-backed GitDriver, so they need no repository. The *IntegrationTest files create real repositories in a temporary directory and run the real git. Those need git 2.23 or newer on PATH. The ExamplesSmokeTest keeps both examples booting.

Troubleshooting

candy-git: cannot find composer autoload.php

You are running from a clone that has no vendor/ directory. Run composer install inside candy-git/. The directory is gitignored, so a fresh clone never has it.

It refuses to start: git is too old or missing

CandyGit needs git 2.23 or newer, because it uses git restore for unstage and discard. The refusal is one sentence with exit status 1. Upgrade git, or make sure the git on PATH is the one you expect.

It refuses: not a git repository

Run it inside a checked-out work tree. Bare repositories are refused because they have no status to show. Linked worktrees work.

It refuses to run with output piped

The interface is a full-screen program, so stdout must be a terminal. Run it directly in a terminal, not through a pipe or a capturing wrapper.

Undo refuses an operation

That is by design. Undo refuses where the inverse would lie: discard, untracked-file delete, amend, merge, revert, reset --hard, a checkout with no origin to return to, and a branch delete whose prior SHA was never recorded. Undo also refuses a stage-all when a file was partly staged. The status line says why.

A deleted untracked file is gone

d on an untracked file deletes it from disk, and undo does not restore it. The press-twice guard is the only confirmation. Stage or move files you want to keep before you press d.

Push refuses on a detached HEAD

There is no branch to push. Check out a branch with Space on the branches pane, or create one with n, then push with P.

A filter driver prints a notice on stderr

The repository configures a clean, smudge or process filter, such as git-lfs. CandyGit announces it rather than disabling it, because those tools need their filters to work. Set CANDY_GIT_STRICT_FILTERS=1 to refuse such repositories instead.

git: command timed out after 30s

A read git call ran past its 30-second budget, usually a slow remote or a fetch waiting on credentials. Git calls run on the UI thread, so the screen pauses until the call returns or times out. Check the network or the remote, then retry. The timed-out child is stopped with TERM, then KILL.

git: mutator timed out after 120s

A mutating call such as fetch, pull, push, commit or merge ran past its 120-second budget. The repository may be mid-operation, most often a stale .git/index.lock or a half-applied checkout. Run git status outside CandyGit, clear a lock you know is dead, then retry.

Upstream mapping

lazygit is the design antecedent. CandyGit mirrors its three-pane workflow and its single-key verbs, and it is native PHP rather than a port, so there is no class-for-class table. Each verb maps to a git subcommand, which is why the git documentation is the reference for behavior. The table in the API reference lists the classes that carry it.

Architecture

The model is pure. Every key returns a fresh App, and the git work happens in the driver. The main classes are below.

ClassRole
AppThe TEA model. Owns the lists, cursors, focus and overlays. Each key returns a fresh instance.
Git, GitDriverThe concrete shell-out driver, and the interface every operation goes through. Tests inject a fixture-backed driver.
ProcessThe main proc_open site. It runs a bounded drain loop, pins the child environment, isolates stdin from the terminal, and tears down with TERM, a grace period, then KILL. The private runBounded helper in Platform is the other caller (Windows teardown only) and does not pin the environment.
PlatformThe OS seam: the null device, PATH lookup, and process-tree kill on Windows. Both branches are unit-tested on any host.
HistoryEntry, HistoryManagerOne undoable operation with its inverse or a refusal marker, and the bounded undo and redo stacks.
DiffViewer, DiffHighlighterThe immutable diff overlay state with hunk navigation, and the per-line highlight spans.
StashManager, StashEntryThe immutable stash list and its entries.
CherryPick, Worktrees, WorktreeEntryThe cherry-pick collector, and the worktree list with its add and remove modes.
InteractiveRebase, RebaseCommit, RebaseActionThe rebase todo preview, its entries, and the action enum: Pick, Reword, Edit, Squash, Drop.
RendererA pure view function. It draws the three bordered panes and the focus marker.
LangThe git-namespaced translation facade over the shared registry.
Support\Version, Support\GitRequirementThe version and build-stamp reader, and the git version floor.

Changelog and versioning

CandyGit was published as sugarcraft/sugar-stash until a rename in 2026-10, when the namespace changed from SugarCraft\Stash\ to SugarCraft\Git\. The Composer channel tracks dev-master. The GitHub release channel has two tags. candy-git/latest is the rolling prerelease phar, and candy-git/v* tags are stable cuts. Until a stable tag is cut, the prerelease phar is the only release artifact. Each release ships candy-git.phar.sha256 and candy-git.phar.commit, which names the tested commit the bytes were built at.

  • sugar-core provides the program loop, the key messages and the cell-width math.
  • sugar-fuzzy provides the scored matcher behind StashManager::fuzzyFilter().
  • candy-files is the dual-pane file manager on the same stack.

Source & demos

Try the quickstart →

Demos.

VHS-recorded GIF demos. play.tape drives examples/play.php — a hermetic, fixture-backed build of the TUI that renders identically on every machine — while stage.tape drives examples/stage.php through the same fixture.

Play

Play

Pane tour — status / branches / log, cursor movement, stage / unstage.
Stage

Staging workflow

s key stages and unstages files — watch the status update.