CandyScriptui
Composer-installable CLI of TUI primitives
13 presentation subcommands — choose, confirm, file, filter, format, input, join, log, pager, spin, style, table, write — plus completion and version utilities. Drop into a shell script and instantly get a Charm-quality interactive UX. Its command set and exit-code conventions follow charmbracelet/gum.
Install
composer require sugarcraft/candy-scriptui
No tagged releases ship yet — Packagist serves the dev-master branch only, so require it as sugarcraft/candy-scriptui:dev-master; on a default-stable project a bare sugarcraft/candy-scriptui request does not resolve.
Or grab the rolling latest phar — rebuilt and published for every commit that
touches this app (verify against the published .phar.sha256 sidecar
before making it executable):
curl -fsSLO https://github.com/detain/sugarcraft/releases/download/candy-scriptui/latest/candy-scriptui.phar
curl -fsSLO https://github.com/detain/sugarcraft/releases/download/candy-scriptui/latest/candy-scriptui.phar.sha256
sha256sum -c candy-scriptui.phar.sha256 && chmod +x candy-scriptui.phar
Quickstart
# Apply styling.
candy-scriptui style --foreground "#ff5f87" --bold "Hello, candy!"
# Pick one item.
choice=$(candy-scriptui choose Pizza Burger Salad)
# Read a single line.
name=$(candy-scriptui input --placeholder "Your name?")
# Confirm a destructive action.
file=old-build.log
candy-scriptui confirm "Really delete $file?" && rm "$file"
# Show a spinner while running a command.
candy-scriptui spin --title "Building..." -- make build
# Filter a list (substring by default; --fuzzy for fuzzy matching).
git branch | candy-scriptui filter
Concepts
The binary is one entry point with one subcommand per job. Each subcommand reads its input from argv or stdin, prints its result to stdout, and reports the outcome through its exit code, so the parts compose in a shell pipeline. style, format, table and join print and exit. The interactive commands draw their frame on the terminal, and when stdout is redirected the frame goes to STDERR, so the selection on stdout stays clean. Keys always come from the terminal, never from a pipe. The exit codes are the contract: 0 on success, 1 when the user aborts with Esc (2 in confirm, so an abort stays apart from a no; pager finishes with 0 instead), 130 on Ctrl+C, 124 on a --timeout deadline, and 128 plus the signal number on an OS signal.
What's in the box
API reference
Every public class, interface, trait and enum under src/, grouped by namespace, with its method table. The listing is generated from the source PHPDoc; types and methods marked @internal are left out.
Only methods declared in candy-scriptui/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\ScriptUi
Application final class
Top-level Symfony Console application registering each subcommand.
| Method | Summary |
|---|---|
__construct() | |
versionFromComposer(): string | Reads the version from this PACKAGE's composer.json manifest. |
static versionString(): string | The version this install reports, phar-aware (archive metadata first). |
static hostArchive(): string | The real-filesystem path of the phar archive hosting this install, or '' when this code is not running from an archive (same measured 3-arm law as the bin guards: Phar::running() inside the archive, a phar:// __FILE__ prefix, a self-naming .phar __FILE__; composer mode is always ''). |
run(?InputInterface $input = null, ?OutputInterface $output = null): int | |
doRun(InputInterface $input, OutputInterface $output): int | |
static gumEnvVar(string $commandName, InputOption $option): string | gum's variable shape: GUM_<COMMAND>_<OPTION>, upper-cased, - as _. |
scan(string $namespace): array | Scan a namespace for classes bearing the #[Command] attribute and register them into this application. |
find(string $name): Command | Resolve a command by EXACT name only. Symfony's inherited find() additionally accepts unique prefixes, which made typo'd invocations silently EXECUTE a different command — choos Pizza Burger ran choose, confir ran confirm. On an exit-code-gating CLI that is a safety defect, not a convenience. Unknown names now fail closed with a did-you-mean that lists every plausible candidate (prefix matches first), so the suggestion also stops misdirecting. |
addEnumConstraint(string $commandName, string $option, string $enumClass): void | Register a value constraint discovered by the CommandScanner from #[Flag(enum: SomeType::class)]. The seam existed as documentation only at first, and --format=pineapple sailed right through it. |
CompletionCommand final class
Mirrors charmbracelet/gum.completion. Built-in command that emits shell completion scripts for bash, zsh, and fish.
Lang final class
Per-library translation facade for candy-scriptui.
| Method | Summary |
|---|---|
static t(string $key, array $params = []): string | Interpolated parameters are attacker-shaped argv on most refusal paths: a crafted option value must never paint the terminal with live SGR bytes or forge extra diagnostic lines with embedded newlines. Folding every string param through the shared control-byte stand-in mapper at THIS chokepoint keeps every Lang::t site honest without repeating the sanitize by hand. |
SugarCraft\ScriptUi\Attribute
Alias final class
Registers an alias for a CLI command.
| Method | Summary |
|---|---|
__construct(public readonly string $name) |
Command final class
Marks a class as a CLI command for auto-discovery.
| Method | Summary |
|---|---|
__construct(public readonly string $name, public readonly string $description = '', public readonly string $descriptionSection = '') |
Example final class
Marks a command with an example usage string shown in help output.
| Method | Summary |
|---|---|
__construct(public readonly string $usage, public readonly string $description = '') |
Flag final class
Declarative CLI option for a command.
| Method | Summary |
|---|---|
__construct(public readonly string $name, public readonly string $short = '', public readonly string $description = '', public readonly bool $required = false, public readonly bool $isFlag = false, public readonly ?string $enum = null, public readonly mixed $default = null) |
ValueEnum final class
Marks a backed enum as a constrained-value set for CLI options.
| Method | Summary |
|---|---|
__construct(public readonly array $values) | |
static validate(mixed $value, self $attribute, string $optionName): string |
SugarCraft\ScriptUi\Command
ChooseCommand final class
Mirrors charmbracelet/gum.choose. Pick a single item from an interactive list. Prints the chosen text on stdout; exits 1 when the user aborts.
| Method | Summary |
|---|---|
static renderResult(ChooseModel $final, OutputInterface $output, string $delim, ?string $noSelectedMessage): int | Map the finished model to process output + exit code. Static and separate from execute() so the contract is unit-testable without the live TTY that Program::run() needs. |
ConfirmCommand final class
Mirrors charmbracelet/gum.confirm. Confirmation prompt. Exit code reflects the answer: 0 for yes, 1 for no, 2 for an Esc abort, 130 for a Ctrl+C cancellation (typed or kill -INT), 124 when a --timeout deadline elapses, and 128+signum for an OS signal that stopped the loop (e.g. SIGTERM -> 143).
FileCommand final class
Mirrors charmbracelet/gum.file. Browse the filesystem and print the chosen file path. ↑/↓ navigate; Enter descends into directories or selects files; Backspace ascends to the parent. Esc aborts with exit 1; Ctrl-C exits 130 and a --timeout deadline exits 124.
FilterCommand final class
Mirrors charmbracelet/gum.filter. Pick one line from stdin via incremental fuzzy filter. Designed for pipelines:
| Method | Summary |
|---|---|
static renderResult(FilterModel $final, OutputInterface $output, string $delim, bool $printQuery): int | Map the finished model to process output + exit code. Static and separate from execute() so the contract is unit-testable without the live TTY that Program::run() needs. |
FormatCommand final class
Mirrors charmbracelet/gum.format. Render a Markdown file (or stdin) as styled ANSI text using \SugarCraft\Markdown\Renderer. Non-interactive — produces output straight to stdout so it pipelines naturally:
| Method | Summary |
|---|---|
static pickTheme(string $name): Theme |
InputCommand final class
Mirrors charmbracelet/gum.input. Read a single line from the user. Prints the entered value on stdout; exits 1 when aborted (Esc), 130 on Ctrl+C cancellation, 124 when a --timeout deadline elapses, and 128+signum on an OS signal.
JoinCommand final class
Mirrors charmbracelet/gum.join. Concatenate every argument with a separator, optionally with horizontal (per-line) joining. Lipgloss's JoinHorizontal / JoinVertical ship here as --horizontal / --vertical modes. Reads from stdin when no positional arguments are given.
| Method | Summary |
|---|---|
static joinHorizontal(array $parts, string $separator = '', string $valign = 'top'): string | Stitch each $parts string into the same row layout, padding shorter blocks to the tallest one and joining each row with $separator. |
static joinVertical(array $parts, string $separator = "\n", string $halign = 'left'): string | Vertical join with optional horizontal alignment of each block's lines against the widest line across all blocks. |
LogCommand final class
Mirrors charmbracelet/gum.log. Print a styled log line. The level badge (DEBUG / INFO / WARN / ERROR / FATAL) is rendered in a colour matching the level; the message text follows verbatim. Useful for shell scripts that want consistent log output without pulling in a logging framework.
| Method | Summary |
|---|---|
static format(LogLevel $level, string $message): string | Render BADGE message with the level's style applied to the badge. |
static formatLine(LogLevel $level, string $message, string $prefix = '', string $timeFormat = '', string $formatter = 'text'): string | Format a line with optional prefix / timestamp / structured shape. Mirrors the gum log surface: text (default), json, logfmt. |
static resolveTimeFormat(string $alias): string | Resolve a Go-style time-constant alias (rfc822, rfc3339, kitchen, stamp, datetime, dateonly, timeonly, ansic, unixdate) to its corresponding PHP date() format string. Anything else is treated as an explicit date() format and passed through. |
PagerCommand final class
Mirrors charmbracelet/gum.pager. Scroll long input. Reads from stdin or --file and lets the user navigate with the standard pager keys (↑/↓ / PgUp / PgDn / Home / End / q to quit). Quitting with q or Esc exits 0; Ctrl+C exits 130, a --timeout deadline exits 124, and an OS signal exits 128+signum.
| Method | Summary |
|---|---|
static prewrapSoftWrap(string $raw, int $width): string | scriptui-21: --soft-wrap must only change line breaks, never styling. Width::wrap begins with Ansi::strip, so colourised input (ls --color, git diff) arrived at the viewport unstyled while the non-wrap clip path is ANSI-aware. Width::wrapAnsi keeps every CSI sequence intact and holds the visible width contract; an active SGR simply continues across the break. |
SpinCommand final class
Mirrors charmbracelet/gum.spin. Run a command while showing a spinner.
| Method | Summary |
|---|---|
__construct(?\Closure $processFactory = null, ?\Closure $programFactory = null) | The class is final, so the child-process spawn and the Program construction are injected as optional factory closures rather than exposed as overridable methods. Production leaves both null (real RealProcess + a TTY Program); tests pass a \SugarCraft\ScriptUi\Process\FakeProcess that never exits plus a headless Program so the --timeout path can be driven deterministically. The zero-arg default keeps new SpinCommand() working for \SugarCraft\ScriptUi\Application auto-registration. |
static pickStyle(string $name): SpinStyle |
StyleCommand final class
Mirrors charmbracelet/gum.style. Apply ANSI styling to its argument text (or stdin when no arguments are given) and print the result.
TableCommand final class
Mirrors charmbracelet/gum.table. Render CSV / TSV from a file or stdin as a styled \SugarCraft\Style\Table\Table.
| Method | Summary |
|---|---|
static parseRows(string $raw, string $separator): array | Parse a CSV/TSV blob into rows. |
static parseBorder(string $name): ?Border |
VersionCommand final class
Prints the version of this tool as its own subcommand.
WriteCommand final class
Mirrors charmbracelet/gum.write. Multi-line text editor. Press Ctrl+D to submit; Esc aborts (exit 1), Ctrl+C cancels (exit 130), a --timeout deadline exits 124, and an OS signal exits 128+signum. Submitted text is printed verbatim on stdout.
SugarCraft\ScriptUi\Completion
BashCompletion final class
Mirrors charmbracelet/gum.completion (the bash emitter). Generates Bash completion script for a Symfony Console application. Dynamically inspects the application to produce completions for all registered commands and their flags.
| Method | Summary |
|---|---|
static isSupportedShell(string $shell): bool | |
static validShells(): array | |
generate(Application $application): string |
CompletionEscaper final class
Escapes names intended for shell completion scripts, preventing injection of arbitrary shell code via malicious command/option names registered through \SugarCraft\ScriptUi\Discovery\CommandScanner.
| Method | Summary |
|---|---|
static safeName(string $name): ?string | Returns the name unchanged if it is safe for shell interpolation; returns null if the name could contain shell metacharacters and must not be emitted into a completion script. |
static filterSafeList(array $names): array | Like safeName() but filters an entire list, returning only the safe elements in their original order. |
FishCompletion final class
Mirrors charmbracelet/gum.completion (the fish emitter). Generates Fish completion script for a Symfony Console application. Dynamically inspects the application to produce completions for all registered commands and their flags.
| Method | Summary |
|---|---|
static isSupportedShell(string $shell): bool | |
static validShells(): array | |
generate(Application $application): string |
ZshCompletion final class
Mirrors charmbracelet/gum.completion (the zsh emitter). Generates Zsh completion script for a Symfony Console application. Dynamically inspects the application to produce completions for all registered commands and their flags.
| Method | Summary |
|---|---|
static isSupportedShell(string $shell): bool | |
static validShells(): array | |
generate(Application $application): string |
SugarCraft\ScriptUi\Discovery
CommandScanner final class
Scans a namespace for classes bearing the Command attribute and registers them into a Symfony Console Application.
| Method | Summary |
|---|---|
skipped(): array | Commands that were discovered but could NOT be registered (their constructors require a dependency the scanner cannot inject). Call it right after scan(); scan() resets it on each run. |
scan(string $namespace, Application $application): array |
SugarCraft\ScriptUi\Help
HelpCatalog final class
The help surface's i18n plumbing (scriptui-59): command descriptions, option / argument texts, #[Example] captions and the Aliases / Examples / Help labels resolve through lang/<locale>.php like every other user-facing string.
| Method | Summary |
|---|---|
static derive(\Symfony\Component\Console\Application $app): array | The catalog rows the current command classes call for, as key => English. Source of both tools/gen-help-catalog.php and HelpDriftTest. A text shared by several commands for the same option becomes ONE help.opt.<option> row; commands that word it differently get their own help.opt.<command>.<option> row. |
static lookup(string $key): ?string | Resolve $key, or null when the active catalogs carry no row for it. |
static owns(Command $command): bool | True for commands this package ships (scanned third-party ones have no rows). |
static optionKeys(string $command, string $option): array | Candidate keys for an option, most specific first. |
static localize(Command $command): void | Swap every translatable string on $command for its catalog row, leaving anything without one on the English literal. |
static exampleCaption(Command $command, int $index, Example $example): string | Localized caption of the n-th example of $command (English fallback). |
static label(string $name, string $english): string | Section label with an English fallback. |
HelpFormatter final class
| Method | Summary |
|---|---|
format(SymfonyCommand $command): string | |
write(OutputInterface $output, SymfonyCommand $command): void |
TypoSuggester final class
| Method | Summary |
|---|---|
__construct(private readonly array $commandNames) | |
suggestAll(string $input): array | Return every plausible command for a mistyped name: truncated prefixes first (the common fat-finger class), then close spellings within Levenshtein distance 2. Sorted by distance, then name; capped. |
suggest(string $input): ?string | Return a suggested command name if Levenshtein distance to any known command is ≤ 2, otherwise null. |
SugarCraft\ScriptUi\Log
LogLevel enum
Severity levels for \SugarCraft\ScriptUi\Command\LogCommand, with the styled badge each one emits.
Cases: Debug · Info · Warn · Error · Fatal
PHP also provides cases(), from() and tryFrom().
| Method | Summary |
|---|---|
static fromString(string $name): self | |
badge(): string | |
order(): int | Numeric ordering used by the --min-level filter: Debug=0, Info=1, Warn=2, Error=3, Fatal=4. |
style(): Style |
SugarCraft\ScriptUi\Model
ChooseModel final class
Mirrors charmbracelet/gum.choose (the interactive list). Selection chooser used by \SugarCraft\ScriptUi\Command\ChooseCommand.
| Method | Summary |
|---|---|
static fromOptions(array $options, int $height = 10, int $limit = 1, bool $noLimit = false, string $header = '', array $preselected = [], bool $ordered = false, ?string $cursorPrefix = null, ?string $unselectedPrefix = null, int $width = 0, bool $typeToFilter = true, array $cursorCycle = [], string $selectedPrefix = ''): self | |
init(): ?\Closure | |
update(Msg $msg): array | |
view(): string | |
selected(): ?string | Selected option's title once submitted (single mode). |
selectedAll(): array | Multi-select payload — every ticked option's title in original (input) order, or in selection order when --ordered is set. |
selectedCount(): int | |
isSubmitted(): bool | |
isAborted(): bool | |
isInterrupted(): bool | |
isMulti(): bool | |
isRefusedEmpty(): bool | |
subscriptions(): ?\SugarCraft\Core\Subscriptions |
ConfirmModel final class
Mirrors charmbracelet/gum.confirm (the answer model). Yes/no prompt used by \SugarCraft\ScriptUi\Command\ConfirmCommand. Wraps Confirm; Enter / y / n commit, Esc/Ctrl-C aborts.
| Method | Summary |
|---|---|
static newPrompt(string $title = '', bool $default = false, string $affirmative = 'Yes', string $negative = 'No', string $pointer = ''): self | |
init(): ?\Closure | |
update(Msg $msg): array | |
view(): string | |
answer(): bool | |
isSubmitted(): bool | |
isAborted(): bool | |
isInterrupted(): bool | |
subscriptions(): ?\SugarCraft\Core\Subscriptions |
FileModel final class
Mirrors charmbracelet/gum.file (the directory browser). Filesystem picker used by \SugarCraft\ScriptUi\Command\FileCommand. Wraps FilePicker; the picker handles Enter/Backspace internally for navigation; we add Esc/Ctrl-C abort and short-circuit when a path is selected.
| Method | Summary |
|---|---|
static newPrompt(?string $cwd = null, int $height = 10, bool $allowDirs = false, bool $allowFiles = true, bool $showHidden = false, bool $showSize = false, array $allowedExtensions = []): self | |
init(): ?\Closure | |
update(Msg $msg): array | |
view(): string | |
selected(): ?string | |
isAborted(): bool | |
isInterrupted(): bool | |
isSubmitted(): bool | |
subscriptions(): ?\SugarCraft\Core\Subscriptions |
FilterModel final class
Mirrors charmbracelet/gum.filter (the query-over-lines view). Variant of ChooseModel that opens directly in filter mode and sends every keystroke to the inner ItemList's filter buffer. Enter on the highlighted result submits; Esc / Ctrl-C aborts.
| Method | Summary |
|---|---|
static fromOptions(array $options, int $height = 10, int $limit = 1, bool $noLimit = false, string $header = '', array $preselected = [], bool $reverse = false, string $value = '', ?string $cursorPrefix = null, ?string $unselectedPrefix = null, bool $fuzzy = false, ?FuzzyMatcher $matcher = null, int $width = 0, string $placeholder = '', string $prompt = '', int $tail = 0): self | |
init(): ?\Closure | |
update(Msg $msg): array | |
fuzzyVisibleItems(): array | |
view(): string | |
selected(): ?string | |
selectedAll(): array | |
isSubmitted(): bool | |
isAborted(): bool | |
isInterrupted(): bool | |
isMulti(): bool | |
highlightIndices(): array | Returns the highlight indices for the currently selected item. |
subscriptions(): ?\SugarCraft\Core\Subscriptions |
InputModel final class
Mirrors charmbracelet/gum.input (the single-line editor). Single-line prompt used by \SugarCraft\ScriptUi\Command\InputCommand. Wraps TextInput; Enter submits, Esc/Ctrl-C aborts.
| Method | Summary |
|---|---|
static newPrompt(string $placeholder = '', bool $password = false, string $prompt = '> ', string $value = '', int $charLimit = 0, int $width = 0, string $header = ''): self | |
init(): ?\Closure | |
update(Msg $msg): array | |
view(): string | |
value(): string | |
isSubmitted(): bool | |
isAborted(): bool | |
isInterrupted(): bool | |
subscriptions(): ?\SugarCraft\Core\Subscriptions |
PagerModel final class
Mirrors charmbracelet/gum.pager (the scrollback model). Read-only pager used by \SugarCraft\ScriptUi\Command\PagerCommand. Wraps a Viewport; Esc / q / Ctrl-C exit. Standard navigation keys (↑/↓/jk, PgUp/PgDn/space/b/f, Home/g/End/G, Ctrl-U/D) come from Viewport's own update().
| Method | Summary |
|---|---|
static fromContent(string $content, int $width = 0, int $height = 0, bool $showLineNumbers = false, string $match = '', int $frameRows = 0, int $fade = 0): self | |
init(): ?\Closure | |
update(Msg $msg): array | |
view(): string | |
static hardWrap(string $raw, int $width): string | Break every line at exactly $width cells, mid-word if need be (the strict sibling of \SugarCraft\ScriptUi\Command\PagerCommand::prewrapSoftWrap(), which breaks on word boundaries). ANSI-aware: escape bytes never count toward the width. |
isExited(): bool | |
isInterrupted(): bool | |
subscriptions(): ?\SugarCraft\Core\Subscriptions |
SpinModel final class
Mirrors charmbracelet/gum.spin (the spinner view). Run a child Process while a Spinner animates beside an optional status title. Each spinner tick polls the process; when the child exits, the model captures its code and stops the loop. Pressing Esc or Ctrl+C terminates the child early; the run then reports SignalExit::EXIT_INTERRUPTED (130), the conventional cancellation code — never a negative value, which exit() would wrap to 255.
| Method | Summary |
|---|---|
static spawn(Process $process, string $title = '', ?SpinStyle $style = null, string $align = 'left'): self | |
init(): ?\Closure | |
update(Msg $msg): array | |
view(): string | |
isDone(): bool | |
exitCode(): ?int | |
subscriptions(): ?\SugarCraft\Core\Subscriptions |
WriteModel final class
Mirrors charmbracelet/gum.write (the multi-line editor). Multi-line editor used by \SugarCraft\ScriptUi\Command\WriteCommand. Wraps TextArea; **Ctrl+D** submits (Enter inserts a newline, matching most multi-line editors), **Esc / Ctrl+C** abort.
| Method | Summary |
|---|---|
static newPrompt(string $placeholder = '', int $width = 0, int $height = 0, string $value = '', int $charLimit = 0, int $maxLines = 0, string $prompt = '', bool $showLineNumbers = false, string $header = '', ?string $endOfBufferCharacter = null): self | |
init(): ?\Closure | |
update(Msg $msg): array | |
view(): string | |
value(): string | |
isSubmitted(): bool | |
isAborted(): bool | |
isInterrupted(): bool | |
subscriptions(): ?\SugarCraft\Core\Subscriptions |
SugarCraft\ScriptUi\Process
FakeProcess final class
Test double for Process. Holds a mutable $exitCode (null while running) plus flags recording whether terminate() or close() have been called.
| Method | Summary |
|---|---|
recordSpawn(array $argv, bool $captureStdout, bool $captureStderr): void | Test harnesses register this from their processFactory so a command building the WRONG argv (or dropping the capture flags) goes red — the factory previously discarded its arguments, which made every spawn-shape assertion vacuous. |
drain(): void | |
attachPump(\React\EventLoop\LoopInterface $loop): void | |
detachPump(): void | |
pid(): int | |
exited(): bool | |
wait(): int | |
kill(int $signal): void | |
exitCode(): ?int | |
terminate(): void | |
close(): int | |
stdout(): string | |
stderr(): string | |
stdoutBytes(): string | |
stderrBytes(): string | |
stdoutDropped(): int | |
stderrDropped(): int | |
finish(int $code = 0): void | Convenience: simulate the child finishing with the given code. |
Process interface
candy-scriptui re-export of the sugar-pty process contract, widened with the lifecycle surface the spin chain actually calls, so \SugarCraft\ScriptUi\Model\SpinModel, \SugarCraft\ScriptUi\Command\SpinCommand and every test double type against ONE pinned interface.
| Method | Summary |
|---|---|
drain(): void | Pump both capture pipes right now, bounded and non-blocking. Cheap to call per tick: appends new bytes only. |
attachPump(\React\EventLoop\LoopInterface $loop): void | Register the capture pipes on $loop so bytes move while the run loop is alive (scriptui-02: the cure for a child blocking at the ~64KiB OS pipe buffer with nobody reading). Idempotent per loop. |
detachPump(): void | Unregister the read-stream pump. No-op when not attached; every settle path calls it so watchers never outlive the loop. |
terminate(): void | Signal the child (SIGTERM); does NOT reap. close() reaps. |
close(): int | Reap the child, bounded (TERM→grace→KILL ladder). Idempotent: every call after the first returns the same code. |
stdout(): string | Captured stdout bytes (drains first). |
stderr(): string | Captured stderr bytes (drains first). |
stdoutDropped(): int | scriptui-03: bytes seen past the capture cap for stdout (0 when every drained byte was retained). Non-zero means the post-run print shows the head only. |
stderrDropped(): int | scriptui-03: bytes seen past the capture cap for stderr. |
RealProcess final class
The canonical non-PTY child handle for candy-scriptui: one copy owns the whole lifecycle (spawn → drain → signal → reap) so every fix in the spin process chain lands exactly once.
| Method | Summary |
|---|---|
static spawn(array $command, bool $captureStdout = false, bool $captureStderr = false): self | Spawn a non-PTY child. $captureStdout/$captureStderr decide whether stdout/stderr land in our capture pipes (drained by drain()/stdoutBytes()) or are inherited from the parent's STDOUT/STDERR. |
groupManaged(): bool | Whether the tracked pid leads the child's process group (the detach wrapper was armed). True ⇒ signals go to the whole tree; false ⇒ direct-child only (the pre-scriptui-04 shape, still correct when no wrapper exists — signalling our own group would be self-harm). |
pid(): int | |
drain(): void | Bounded non-blocking pump of both capture pipes. This is the run-loop drain vocabulary: call it per tick (or per read-stream event) and a child writing past the ~64KiB OS pipe buffer never blocks waiting for a reader that only shows up after the loop ends. |
stdoutDropped(): int | Bytes of captured stdout dropped past the capture cap (scriptui-03). |
stderrDropped(): int | Bytes of captured stderr dropped past the capture cap (scriptui-03). |
attachPump(LoopInterface $loop): void | Register both open capture pipes on the event loop (scriptui-02, the 64KiB cure). The run loop used to poll only the exit verdict, so a child writing past the ~64KiB OS pipe buffer blocked forever while the spinner painted: nobody drained until after the loop ended. With the pump attached, every loop wakeup that sees readable pipe bytes runs drain() — the child never stalls, the parents poll keeps ticking, and EOF retires the watcher. |
detachPump(): void | Unregister the read-stream pump (no-op when not attached). Called by the command right after the run loop returns and by every wait() settle path, so capture fds never outlive the loop watching them. |
exited(): bool | Non-blocking exit probe: reads live status while the handle is open, caches the verdict once the child is gone. Never drains or reaps — that is drain()/wait()/close()'s job. |
exitCode(): ?int | |
kill(int $signal): void | Signal the child — its whole process GROUP when the detach wrapper armed the tree (scriptui-04), the bare pid otherwise. Libc::kill() (sugar-pty's FFI route), not bare posix_kill(): ext-posix is optional on this fleet. The exited() guard before AND after the failed call is the pid-reuse guard — signalling a reaped (possibly recycled) PID risks an unrelated process, so a post-exit kill is silently dropped instead. While the group leader (our tracked pid) lives, the group exists, so a running handle never ESRCHs. |
terminate(): void | Signal the child with SIGTERM. Lifecycle split: terminate() only *signals*; close() is the sole *reaping* path and it bounds the wait (grace + SIGKILL escalation), so close-after-terminate neither double-kills nor hangs. Idempotence guards: skip when the handle was already reaped ($closed), when a SIGTERM was already sent ($terminated), or when the child already exited on its own. |
close(): int | Reap the child, bounded. If terminate() asked the child to stop and it is still running, give it TERM_GRACE_SECONDS to honour SIGTERM, then escalate to SIGKILL — the fleet-standard TERM→grace→ KILL ladder. The grace poll drains the capture pipes as it goes: a dying child that is still writing must not wedge the window. |
wait(): int | Block until the child exits, pumping the capture pipes every poll iteration, then settle the handles: final drain, close pipes, proc_close. A cached or already-reaped verdict still settles (bytes produced before the reap stay readable); a handle the closer never saw returns the cached code or -1 — NEVER a fabricated success. |
stdout(): string | Captured stdout bytes (drains first). |
stderr(): string | Captured stderr bytes (drains first). |
stdoutBytes(): string | |
bufferedPeek(): string | Zero-IO view of the buffered stdout — for pump-proof instrumentation that must observe bytes WITHOUT draining (a peek that drains would hide a broken pump behind its own polling). |
stderrBytes(): string | |
descendantPids(): array | The process tree rooted at the tracked pid (direct+transient children, breadth-first), EXCLUDING the tracked pid itself and this runner. Linux reads /proc/<pid>/task/<pid>/children per level; elsewhere one ps -A -o ppid=,pid= helper per level does the job. A process that raced away between levels simply contributes no children — the walk must never signal pids it did not verify. |
__destruct() | scriptui-05 (candy-scriptui-035): the zombie-reaper safety net, mirroring sugar-pty's PosixChild::pollDestruct policy — an already exited child gets its zombie reaped and its handles let go when the object dies without close(); a still-running child is NOT signalled from a destructor (destructors must not throw, and killing a live tree during GC could fire long after the owner stopped intending it). The command-level finally ladder is the real guarantee; this only cleans the process-table residue of abandoned handles. |
SugarCraft\ScriptUi\Runtime
ColourGate final class
Resolves the colour capability for non-interactive output from the standard negotiation family (NO_COLOR / CLICOLOR / CLICOLOR_FORCE / FORCE_COLOR / TERM=dumb) plus the global --ansi / --no-ansi flags, and pins it as sugar-style's ambient profile so every Style minted afterwards — flag-built styles, log badges, and the sugar-markdown theme styles used by format — renders inside the resolved tier instead of emitting escapes the terminal would ignore.
| Method | Summary |
|---|---|
static cap(?InputInterface $input = null): ColorProfile | The narrowest colour capability in force for this invocation. ColorProfile::TrueColor means "no restriction". |
static ladder(): ColorProfile | scriptui-35 (finding 055): when no gate variable decides, believe the terminal's own advertisement instead of assuming TrueColor — TERM=screen / vt100 used to receive CSI 38;2;… they ignore. Delegates to sugar-core's TERM/COLORTERM ladder with NO tty probe: a pipe still carries styled bytes (see the class note), it is only the terminal FAMILY that narrows the tier. |
static termIsDumb(): bool | scriptui-36 (finding 111): ONE shared dumb-terminal predicate over TERM — unset, set-but-empty, or literally dumb. termenv treats all three as dumb-equivalent; the old two sites each eyeballed === 'dumb', so a TERM='' session skipped both the colour route and the MODE posture and shipped DEC-private bytes into an environment that never advertised them. Both the colour ladder above and InteractiveRuntime::programOptions() now consume this. |
static install(?InputInterface $input = null): ColorProfile | Resolve the capability and pin it as the process-ambient profile for every Style::new() created afterwards. Returns the resolved cap so callers (tests) can assert it. |
static clamp(ColorProfile $requested, ?ColorProfile $ambient = null): ColorProfile | Clamp a requested profile to the ambient capability: styles that pin their own (higher) tier — e.g. a parsed 0-15 index claiming Ansi — must not re-widen colour past a gate that says Ascii. |
static resetAmbient(): void | Restore the unrestricted ambient (test isolation helper). |
CursorMode final class
The --cursor-mode vocabulary shared by the interactive text commands (input, write). gum accepts exactly blink | static | hidden and distinguishes all three: the two visible arms set the DECSCUSR cursor style (blink = blinking block ESC[1 q, static = steady block ESC[2 q, mirroring charmbracelet's cursor.Blink/cursor.Steady which program the same pair), while hidden asks the Program to hide the cursor via \SugarCraft\Core\ProgramOptions::$hideCursor (DEC private ?25l — a different mechanism, so the arms never collide). scriptui-73 (finding 099): before this row blink and static painted byte-identical frames and the documented distinction was hollow. Emission and the ESC[0 q exit reset live in InteractiveRuntime::emitCursorStyle(), gated on dumb TERM like every other DEC byte this app paints.
| Method | Summary |
|---|---|
static isKnown(string $mode): bool | |
static hidesCursor(string $mode): bool | |
static styleSequence(string $mode): ?string | The DECSCUSR start-up sequence that gives the mode its visible meaning, or null when the arm needs no style byte: hidden is owned by the hide mechanism, and an unknown mode must not paint. |
static resetSequence(): string | Terminal-default restore, emitted on exit whenever a style sequence was painted: a scripted blink/steady cursor must not outlive the program into the user's shell. |
Diagnostics final class
Single funnel for library diagnostics on the error stream.
| Method | Summary |
|---|---|
static emit(string $bytes): void | Write bytes verbatim to the error stream — no newline is added. |
Emphasis final class
The single decoration door for hand-composed SGR inside interactive frames.
| Method | Summary |
|---|---|
static sgr(int ...$codes): string | The SGR sequence for the requested codes, or '' when decoration is suppressed. Ascii keeps decoration (it drops COLOUR only — same contract sugar-style's tier docs state); NoTty strips to plain bytes so a frame painted under it is escape-free. |
static reset(): string | The reset terminator matching sgr()'s opener. |
static stripDecor(string $text): string | Under a NoTty capability, remove SGR sequences a delegate rendered — sugar-forms' ItemList forges its own cursor reverse-video with raw escapes (foreign rider: the gate belongs there too), while the README's --no-ansi promise covers the WHOLE frame, not just the parts candy-scriptui paints itself. Every non-NoTty tier passes the text through byte-identical. |
Geometry final class
Best-effort terminal geometry for start-up sizing decisions.
| Method | Summary |
|---|---|
static override(?array $size): void | Pin the reported size for the current process (null clears it). |
static columnsOrNull(): ?int | |
static rowsOrNull(): ?int | |
static size(): array |
IntakeReader final class
Reads a piped data channel under the same wall-clock deadline TimeoutGuard arms around a prompt.
| Method | Summary |
|---|---|
static read($stream, float $seconds): string |
IntakeTimedOut final class
Raised by IntakeReader when the data channel stayed silent past the caller's --timeout; commands map it to TimeoutGuard::EXIT_TIMEOUT.
InteractiveRuntime final class
Single launch chokepoint for every interactive \SugarCraft\Core\Program run in this CLI. It owns the two pipeline contract halves gum upholds:
| Method | Summary |
|---|---|
static programOptions(bool $useAltScreen, bool $hideCursor, LoopInterface $loop): ?ProgramOptions | Program options for an interactive run, or null when NO usable input terminal exists (pipes on both ends and no /dev/tty) — callers must then refuse with a diagnostic on stderr rather than start a Program that can only deadlock or consume piped bytes as keystrokes. |
static emitCursorStyle(string $cursorMode, ProgramOptions $options): bool | scriptui-73 (finding 099): paint the DECSCUSR style the chosen --cursor-mode word actually promises (blink ESC[1 q, static ESC[2 q) onto the same stream the Program will render to. Dumb TERM suppresses it — DECSCUSR is a CSI sequence a dumb terminal echoes instead of obeying, so it rides the same posture as the DEC-private modes above. hidden answers null here: the cursor hiding is ProgramOptions::$hideCursor's own DEC-private arm. |
static emitCursorReset(ProgramOptions $options): void | Restore the terminal's own cursor style on exit (scriptui-73). Called unconditionally when emitCursorStyle() painted — a scripted blinking/steady cursor must not outlive the program. |
static signalNotice(?bool $pcntlLoaded = null): ?string | scriptui-07 (candy-scriptui-036): the options above request signal-mapped cancellation (catchInterrupts: true), but sugar-core can only install the handler when ext-pcntl is loaded — without it SIGINT/SIGTERM take the default disposition (instant death: no 130/143 mapping, no teardown unwind). Surface that once on the diagnostic channel instead of letting the documented promise silently vanish. The returned sentence is the notice to print, or null when there is nothing to say (pcntl present, or already warned this run). |
static resetPcntlWarningLatch(): void | F13-W (CI-watch 2026-11-13): reopen the once-per-process pcntl warning latch. The latch is deliberate in production — one notice per run — but it is PROCESS-wide state: on a pcntl-less host (the Windows CI arms) any earlier in-process call through warnIfPcntlAbsent() consumes it before the honesty test runs, so the test can no longer observe its own first-notice contract. This seam lets the suite start from a known latch state without weakening production: callers in src/ are held to the once-per-run guarantee exactly as before. |
static isHeadless(): bool | scriptui-06 (candy-scriptui-002/-005): true exactly when programOptions() would refuse — no stdout terminal, no /dev/tty, no stdin terminal — i.e. the only honest spin shape is the direct-run arm (no key reader, no renderer, no DEC-mode writer). Callers must not paper over this null with a raw-STDIN Program fallback: that is how one 0x1B byte in the child's DATA stream once became a forged ESC cancellation, and how 38 bytes of ?25l/?2027h chrome once corrupted a redirected data channel. |
static paintsToStderr(): bool | True when the UI frame will be painted somewhere OTHER than stdout — used to route pre-launch chrome (headers, prompts) onto the same stream the Program paints to. |
static paint(string $text): void | Write UI text (never result data) to the stream the interactive frame belongs on, per the paintStream() ladder. When nothing can display (every stream redirected, no /dev/tty) the text is dropped — corrupting a captured data file with chrome is worse than silence, and callers refuse the whole run in that shape anyway. |
static setTerminalProbesForTesting(?array $probes): void | Test seam (scriptui-34): fabricate the terminal-shape census without a real controlling terminal — keys setTerminalProbesForTesting() to null restores the honest probes. |
static stdoutIsTerminal(): bool | |
static stderrIsTerminal(): bool | |
static stdinIsTerminal(): bool |
ItemSource final class
Shared item-source intake for choose and filter (scriptui-46, finding 064).
| Method | Summary |
|---|---|
static collect(array $positionals, array $itemFlags, ?callable $stdinReader): array |
OptionList final class
Expands repeatable list options: each occurrence may itself carry a comma-separated list, mirroring how scripts pass --selected="a,b". Items keep their exact bytes — no trimming, so a name with a leading space stays addressable via a repeated flag.
| Method | Summary |
|---|---|
static expand(array $raw): array |
PositiveInt final class
The strict numeric door for every int-ish flag.
| Method | Summary |
|---|---|
static parse(string $flag, mixed $raw): int | Parse a numeric flag value, refusing anything that is not a non-negative whole number with a localized diagnostic. |
static optional(string $flag, mixed $raw): ?int | Door for optional numeric flags: an unset/null value means "not specified" and passes through as null; anything present must still be a non-negative whole number. |
SignalExit final class
POSIX exit-code mapping for a Program run that ended because the OS delivered a signal to the process (Ctrl-C / SIGINT, SIGTERM, …).
| Method | Summary |
|---|---|
static code(?int $stopSignal): ?int |
StyleOptions final class
The lipgloss style surface gum embeds in EVERY interactive command.
| Method | Summary |
|---|---|
static register(Command $command, array $skip = []): void | Register the shared style options on a command. Callers that already own one of these names for other semantics must opt out via $skip. |
static flags(InputInterface $input): array | Collect the registered flags into the StyleBuilder vocabulary. |
static active(array $flags): bool | |
static frame(array $flags): ?Style | The frame style for a run, or null when no style flag was given — the untouched legacy path (byte-identical frames, zero overhead). |
StyledFrame final class
A model decorator that paints the lipgloss frame around an inner model.
| Method | Summary |
|---|---|
__construct(public readonly Model $inner, private readonly Style $frame) | |
init(): ?\Closure | |
update(Msg $msg): array | |
view(): string|View | |
subscriptions(): ?Subscriptions |
TimeoutGuard final class
Wall-clock deadline for an interactive \SugarCraft\Core\Program run.
| Method | Summary |
|---|---|
static arm(LoopInterface $loop, float $seconds, \Closure $onFire): self | Schedule a one-shot deadline on $loop. When $seconds > 0 the timer flips fired() and invokes $onFire (typically fn () => $program->kill()) exactly once. When $seconds <= 0 the guard is inert — no timer is registered and the run is never interrupted. |
fired(): bool | True once the deadline elapsed and $onFire ran. |
static tryParseSeconds(mixed $raw, float &$seconds): bool | Strict parse of a --timeout option value into armable seconds. |
disarm(): void | Cancel a still-pending deadline. Safe (and cheap) to call after the timer already fired, when the guard was never armed, or more than once — the guard forgets its timer either way, so this is idempotent. |
SugarCraft\ScriptUi\Style
StyleBuilder final class
Builds a \SugarCraft\Style\Style from CLI flag values. Pure (no IO) so commands can unit-test the mapping.
| Method | Summary |
|---|---|
static fromFlags(array $flags): Style | |
static parseColor(string $v): Color | Accept hex (#ff8000 / #f80), 0-15 ANSI palette indices, 0-255 256-colour palette indices, or the 16 canonical palette names (red, bright-blue, …). |
static parseColorWithProfile(string $v): array | Like parseColor() but also returns the narrowest ColorProfile the input requires: - hex / 6-digit / 3-digit → TrueColor - palette index 16-255 → Ansi256 - palette index 0-15 or a name → Ansi |
static parseHexColor(string $v): Color | Parse a hex colour (#ff8000, ff8000, #f80, f80), expanding the 3-digit CSS shorthand to 6 digits. Any other digit count is rejected with a message naming the offending value — before this existed, inputs like #1234 fell through to a generic "unrecognised color" error. |
static frameRows(array $flags): int | Vertical chrome rows a flag-set adds OUTSIDE the content: border top+bottom (a configured border occupies rows even when hidden — that vocabulary is a placeholder posture, not an absence), plus the vertical margin and padding sides. scriptui-26: the pager subtracts this from its auto height so a themed frame never grows past the screen (the --height/--width contract stays CONTENT dimensions). |
static parseSides(string $raw): array |
SubStyleParser final class
Parses gum-style per-element style sub-flags into a map of element name → Style.
| Method | Summary |
|---|---|
static parse(array $flags): array | Parse the array of <elem>.<prop>=<value> strings (or <prop>=<value> for the global element) into element-keyed styles. |
static get(array $map, string $element): Style | Look up the style for $element, falling back to the global * style and finally an empty Style if neither was set. |
Keys and input
Every interactive command is keyboard-driven — the README carries the full
key map (arrows and Enter navigate; j/k and
g/G move and jump in lists, the vim style applies
except in filter where they are typed into the query; Esc aborts
with exit 1 (exit 2 in confirm, so an abort stays apart from a no) except in pager, where it finishes like
q; Ctrl+C aborts with 130). There is no mouse.
Color follows one contract everywhere: --no-ansi is final,
--ansi outranks every environment rule, and
FORCE_COLOR, CLICOLOR_FORCE, NO_COLOR,
CLICOLOR, and TERM=dumb resolve in that order —
the README's Environment section carries the full ladder.
Auto-discovery
candy-scriptui uses PHP attributes to auto-discover commands at runtime. Mark any class extending Symfony\Component\Console\Command\Command with #[Command] (add class-level #[Flag] attributes to declare options — additive, never required) and Application::scan() registers it once the class is loaded:
namespace My\Commands;
use SugarCraft\ScriptUi\Attribute\{Command, Flag};
use Symfony\Component\Console\Command\Command as SymfonyCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
#[Command(name: 'mycmd', description: 'Does something useful.', descriptionSection: 'Longer help text.')]
#[Flag(name: 'format', short: 'f', description: 'Output format.', default: 'json')]
final class MyCommand extends SymfonyCommand
{
protected function execute(InputInterface $input, OutputInterface $output): int
{
$output->writeln('format=' . $input->getOption('format'));
return self::SUCCESS;
}
}
use SugarCraft\ScriptUi\Application;
// scan() registers the #[Command] classes that are already loaded under the
// namespace, so load them first.
class_exists(\My\Commands\MyCommand::class);
$app = new Application();
$app->scan('My\Commands');
$app->run(); // mycmd --format yaml → format=yaml
Tasks
Branch on an abort. A cancelled choose exits 1, so the script can tell a pick from a cancel.
if ! choice=$(candy-scriptui choose Pizza Burger Salad); then
echo "nothing selected" >&2
exit 1
fi
Bound a pipeline with a timeout. --timeout aborts after N seconds with exit 124, so an unattended run cannot wait forever.
git branch | candy-scriptui filter --fuzzy --timeout 30
Run a build under a spinner and keep its exit code. spin forwards the child's own exit code.
candy-scriptui spin --title "Building..." -- make build
echo "make exited $?"
Render a CSV report as a bordered table. --has-header treats the first row as the header.
candy-scriptui table --has-header < report.csv
API reference: attributes and discovery
| Type | Namespace | Role |
|---|---|---|
Command | SugarCraft\ScriptUi\Attribute\Command | #[Attribute] for auto-registering commands |
Flag | SugarCraft\ScriptUi\Attribute\Flag | #[Attribute] for declarative CLI options |
ValueEnum | SugarCraft\ScriptUi\Attribute\ValueEnum | Constrained enum for flag values |
CommandScanner | SugarCraft\ScriptUi\Discovery\CommandScanner | Namespace scanner for #[Command] classes |
Application::scan() | SugarCraft\ScriptUi\Application | Opt-in discovery method |
ChooseCommand | SugarCraft\ScriptUi\Command\ChooseCommand | The choose subcommand; prints the pick and exits 1 on abort |
ChooseModel | SugarCraft\ScriptUi\Model\ChooseModel | Single and multi-select list state behind choose |
FilterCommand | SugarCraft\ScriptUi\Command\FilterCommand | The filter subcommand; reads stdin lines and submits the highlighted match |
FilterModel | SugarCraft\ScriptUi\Model\FilterModel | Filter-mode state; substring matching, or Smith-Waterman scoring with --fuzzy |
SpinCommand | SugarCraft\ScriptUi\Command\SpinCommand | The spin subcommand; runs a child under a spinner and forwards its exit code |
FormatCommand | SugarCraft\ScriptUi\Command\FormatCommand | The format subcommand; renders Markdown through SugarMarkdown |
TableCommand | SugarCraft\ScriptUi\Command\TableCommand | The table subcommand; renders CSV or TSV with a border |
RealProcess | SugarCraft\ScriptUi\Process\RealProcess | Non-PTY child handle; owns spawn, drain, signal and reap |
InteractiveRuntime | SugarCraft\ScriptUi\Runtime\InteractiveRuntime | Single launch point for every interactive run; keys stay on the terminal |
Enhanced help
| Type | Namespace | Role |
|---|---|---|
Alias | SugarCraft\ScriptUi\Attribute\Alias | #[Attribute] registering CLI command aliases |
Example | SugarCraft\ScriptUi\Attribute\Example | #[Attribute] adding example usage to help output |
HelpFormatter | SugarCraft\ScriptUi\Help\HelpFormatter | Renders enhanced help from #[Alias]/#[Example] attributes |
TypoSuggester | SugarCraft\ScriptUi\Help\TypoSuggester | Typo suggestions for unknown commands — prefix hits or Levenshtein distance ≤ 2, capped at five |
Output channels & environment
Data (chosen value, rendered table, completion script) goes to STDOUT raw and byte-exact; diagnostics go to STDERR; the interactive frame is painted to the controlling tty (or STDERR when that is the terminal), never into the capture stream. Because STDOUT is raw, quote every capture and never eval it when the input is third-party.
Recent additions: cursor mode has a default; pager gains --hard-wrap and --fade; confirm gains --pointer; format gains --code, --foreground, and --background, and its refusals are localized like every other command's; the color tier is derived from TERM; CANDY_SCRIPTUI_NO_DECORATION strips decoration; an intake read that times out exits 124; a read-only allow-listed GUM_<COMMAND>_<OPTION> mirror eases migration from gum (the README carries the disclosed table and the warning that names are not command-scoped); and the whole help surface (descriptions, option text, Aliases/Examples labels) is localized through the catalogs.
Shell completions + version
| Type | Namespace | Role |
|---|---|---|
BashCompletion | SugarCraft\ScriptUi\Completion\BashCompletion | Bash completion script generator |
ZshCompletion | SugarCraft\ScriptUi\Completion\ZshCompletion | Zsh completion script generator |
FishCompletion | SugarCraft\ScriptUi\Completion\FishCompletion | Fish completion script generator |
CompletionCommand | SugarCraft\ScriptUi\CompletionCommand | Built-in completion [--shell=bash|zsh|fish] subcommand |
Application::versionFromComposer() | SugarCraft\ScriptUi\Application | Version ladder: phar metadata first, then the nearest ancestor composer.json with a non-empty version, else a dev fallback |
candy-scriptui also reads CANDY_SCRIPTUI_* env fallbacks through a fail-closed allow-list of eighteen presentation option names — CANDY_SCRIPTUI_<OPTION> in uppercase arms that option when no explicit CLI flag is given, and names outside the list are ignored. Every option that answers for the user, grants capability, or redirects data is excluded by construction — allow-env, default, file, out, value, selected, type, shell, password — so a hostile environment can never retarget a sink or weaken a fail-closed flag. The roster is pinned in EnvVarFallbackTest. That exclusion is the lesson of the old universal option↔env mapping, where CANDY_SCRIPTUI_ALLOW_ENV='*' could arm format --type template to exfiltrate the whole environment and CANDY_SCRIPTUI_DEFAULT=yes silently answered confirm; both names now sit outside the allow-list and are ignored with no notice.
Configuration and options
Each subcommand takes its own flags, and candy-scriptui <command> --help lists them. These are the options that shape every command.
| Option or variable | Scope | Effect |
|---|---|---|
--ansi / --no-ansi | Every command | --no-ansi is final. --ansi outranks every environment rule. |
--timeout | Interactive commands, spin | Gives up after the deadline and exits 124. A malformed value exits 1; it is never read as "no deadline". |
--show-output / --show-error | spin | Flushes the child's captured output, including after a timeout. |
FORCE_COLOR, CLICOLOR_FORCE, NO_COLOR, CLICOLOR, TERM=dumb | Every command | Color ladder, resolved in that order. The README's Environment section has the full table. |
CANDY_SCRIPTUI_<OPTION> | Presentation options | Fallback for one of eighteen allow-listed options. It applies only when no CLI flag is given. Names outside the list are ignored, and options that grant capability or redirect data are never read from the environment. |
CANDY_SCRIPTUI_NO_DECORATION | Every command | Strips decoration from the output. |
GUM_<COMMAND>_<OPTION> | Mirror for gum scripts | A read-only, allow-listed mirror that lets an existing gum script keep its theming. |
Theming and styling
style applies ANSI attributes to its arguments or to stdin, and takes --foreground, --background and --bold. format accepts the same color flags, and also --code. The color tier is derived from TERM, so the palette follows the depth the terminal advertises. CANDY_SCRIPTUI_NO_DECORATION strips the decoration when a script needs plain output. The color contract above applies to every command.
Examples
examples/cli.phpbuilds anApplicationin-process, adds one customstatuscommand, and runs the argv through it.php examples/cli.php statusprintsOKand exits0.php examples/cli.php statexits1with the typo suggestionDid you mean "status"?.examples/setup-script.shis an interactive shell script. It chooses a shell flavor, confirms it, and branches on the confirm exit code. It uses acandy-scriptuion thePATHwhen one is present, and otherwise this checkout'sbin/. Run it from a terminal.
php examples/cli.php status
./examples/setup-script.sh
Testing
composer install
vendor/bin/phpunit
The suite covers the commands, the model logic and the runtime. BinExitCodeTest pins the exit codes through the real binary, and GumEnvMirrorTest covers the GUM_* mirror. EnvVarFallbackTest covers the CANDY_SCRIPTUI_* allow-list. PharBuildScriptTest checks the phar build, and LocaleParityTest checks the catalogs.
Troubleshooting and FAQ
An interactive command exits 1 with a notice on STDERR
It has no usable controlling terminal. choose, confirm, filter, input, write, file and pager refuse up front rather than paint a fake session. Run them from a terminal, or give them input and output that a terminal can reach.
The captured output contains the interactive frame
It should not. When stdout is redirected, painting goes to STDERR, and only the answer goes to stdout. Quote every capture, and never eval the output of a third-party script.
A script cannot tell a timeout from the child's own exit code
spin forwards the child's exit code verbatim, the same as gum. A child that exits 2, 124, 130 or 143 looks the same as a timeout or an interrupt. Gate on the child's success (0) rather than on a specific non-zero code.
A discovered command is not found
Application::scan() registers only the classes that are already loaded. Call class_exists() on each class first, as the auto-discovery example does.
An environment fallback has no effect
The fallback applies only to allow-listed options, and only when no CLI flag is given for that option. Check the name against the eighteen-option list, and check that the flag is absent from the command line.
Upstream mapping
candy-scriptui follows the command set and the exit-code conventions of gum. SugarCraft is developed as a native PHP project, so the mapping is a port of behavior, not of Go code.
| gum | candy-scriptui | Notes |
|---|---|---|
| choose, confirm, file, filter, input, write | Same subcommands | Interactive. They refuse without a terminal, and they keep keys off the data stream. |
| format, join, log, pager, style, table | Same subcommands | Format adds --code. Pager adds --hard-wrap and --fade. |
| spin | spin | Forwards the child's exit code. Runs the child through the RealProcess wrapper. |
GUM_* environment | GUM_<COMMAND>_<OPTION> mirror | Read-only and allow-listed. |
Exit code 124 on --timeout | Same | Matches GNU timeout(1). |
Architecture
Application is the Symfony Console shell. It adds scan(), add() and the version ladder. Each subcommand is one class in Command/. The interactive commands build a model from Model/, which holds the state of one screen, and they hand it to Runtime/InteractiveRuntime. That class is the single launch point for every interactive run. It keeps keys on the terminal and sends the frame to STDERR when stdout is redirected. Process/RealProcess runs the child for spin. Discovery/CommandScanner finds the #[Command] classes, and Style/StyleBuilder builds the styles. Help/ and Completion/ hold the help and completion generators, and Lang is the i18n facade.
Changelog and versioning
The version comes from the phar metadata first, then from the nearest composer.json with a version, and finally from a dev fallback. The rolling phar is rebuilt for every commit that touches the app, so pin a sha256 sidecar if a script must stay on one build. The README's compatibility section covers the gum invocations.
Source & demos
- Source on GitHub
- Full README
- Runnable examples
- Originally inspired by gum (Go); SugarCraft is developed as a native PHP project.
Related
- sugar-forms is the form-primitives base the interactive subcommands are built on.
- sugar-core supplies the Model, Msg and Cmd runtime types the interactive screens run on.
- sugar-style supplies the
Styletype behind the styled output.
Demos.
VHS-recorded GIFs — thirteen demos, one per presentation subcommand. Regenerated automatically on every push that touches the source.
choose
Pick one or many items from a list.
confirm
Yes/no with exit-code semantics.
input
Read a single line.
write
Multi-line text editor.
file
Pick a file path.
filter
Filter stdin lines (substring by default).
format
Render Markdown via SugarMarkdown.
style
Apply foreground / bold to argv.
table
Render CSV with rounded borders.
pager
Scroll long input.
log
Leveled logging output.
spin
Spinner while running a command.