All 48 libraries

SugarCli

CLI presentation helpers

inspired by charmbracelet/fang cli presentation library-only

SugarCli code coverage

sugar-cli renders CLI output that matches the rest of the SugarCraft stack: StatusLine, Banner, Section, Stage, HelpText, Frame and Logo, all sharing one width budget and one theme. It is a library, not a framework: each presenter takes data and returns a string, so it drops into any Composer project without a Symfony Console dependency; CommandSpec adds an optional argv parser that returns values or usage errors instead of exiting. The output shape follows charmbracelet/fang (Go); the code is original PHP.

Install

composer require sugarcraft/sugar-cli "@dev"

Requires PHP 8.3 or newer and ext-mbstring. Install note: sugarcraft/* packages track dev-master, and the monorepo sets minimum-stability: dev with prefer-stable: true. Mirror that pair in your own root manifest, or a stable-only install fails to resolve.

Quickstart

Every presenter returns a string with a trailing newline left to the caller. Without an explicit theme, each one uses Theme::detect(), so the same script prints plain text when its output is piped. The runnable version of a full page is examples/cli-page.php (see Examples below).

Concepts

Each presenter is a static method that returns one rendered block. Nothing is written to a stream, so the caller decides where the output goes and tests can compare the returned bytes directly. The shared pieces are a theme (a palette of styles keyed by status level), a width budget (an int, AutoWidth::Auto or null), and a color profile that decides how much of the palette reaches the output.

The width budget resolves through the exported COLUMNS variable, falling back to 80 cells. Values that are not a plausible width are discarded. An over-long message is clipped with …, and the status glyph or tree glyph is never clipped. Banner is the exception: it cuts its lines at the box edge, because the border is the truncation marker.

Tasks

echo Banner::title('myapp', 'v1.2.3', Theme::charm()), "\n";

Pass a preset when the app should look the same on every terminal. Leave the theme out to use the auto-detected palette.

Show numbered steps with sub-steps

echo Stage::step('Reading config', 1, 3), "\n";
echo Stage::subStep('checking PATH', isLast: false), "\n";
echo Stage::subStep('checking composer cache', isLast: true), "\n";
echo Stage::subStepWithProgress('downloading', 40, 100, frame: 0), "\n";

step() takes the message first, then the current and total counts, and prints the counts as text. Both counters are clamped to the total before drawing, so a negative counter prints 0 and a counter above the total prints the total. step() draws no bar. subStepWithProgress() draws the bar and clamps its counters the same way: a negative counter gives an empty bar and a counter above the total gives a full one. Pass frame: to subStepWithProgress() when the output must be byte-stable, such as in a golden test. Without it the spinner walks the wall clock.

Render a --help page

echo HelpText::render(
    usage: 'myapp [flags] ',
    sections: [
        'Commands' => ['setup' => 'configure your environment', 'serve' => 'start the dev server'],
        'Flags'    => ['-v, --verbose' => 'enable verbose logging'],
    ],
    description: 'A demo of the help page.',
    width: 80,
), "\n";

$sections is keyed by section title, then by entry label, with the description as the value. A section whose array is empty renders no block. width: null disables wrapping. A width below 1 throws \InvalidArgumentException.

Draw a full-screen frame

$frame = Frame::new()
    ->withTitle('dashboard')
    ->withStatus('q quit · r refresh')
    ->withTheme(Theme::nord());

echo $frame->render($body, cols: 100, rows: 30);

render() returns exactly rows lines. It throws below 6 rows, which is the chrome overhead. Body rows past rows - 6 are dropped, so the frame never overflows the terminal.

Tint a logo and fall back to plain text

use SugarCraft\Core\Util\ColorProfile;

$logo = Logo::sugarcraftNarrow()->withColor('#ff5fd2');
echo $logo->render(ColorProfile::detectTerminal(null, STDOUT));

The wordmark is 66 cells wide, and sugarcraftNarrow() is the same wordmark without the box border for terminals narrower than that. Passing a detected profile to render() re-quantises the tint, and a profile without color support removes it.

API reference

ClassMethodDescription
StatusLinesuccess(msg, ?theme, width = Auto)Render a success line (error, warn, info and prompt have the same shape)
Bannertitle(title, subtitle = '', ?theme, ?border, ?width)Bordered title banner. Embedded escapes, control bytes and newlines are stripped, so the title is a single display line
Sectionheader(label, ?theme, leftPad = 2, width = Auto, rune = '─')Label plus fill rule. A non-null width is a hard cap, and an over-long label ends in …
Sectionrule(?theme, width = Auto, rune = '─') / subHeader(label, ?theme, indent = 4, width = Auto, rune = '·')Bare divider / indented nested heading
Stagestep(message, current, total, ?theme, glyph = '▸', width = Auto)Numbered step line. Counters are clamped to 0 and to the total
StagesubStep(message, ?theme, isLast = false, indent = 2, width = Auto)Tree-style sub-step. isLast switches the branch glyph
StagesubStepWithProgress(message, current, total, ?theme, isLast = false, indent = 2, width = Auto, ?frame)Sub-step with a progress bar when total is above 0, or a spinner when it is 0. frame pins the spinner glyph
HelpTextrender(usage, sections, description = '', ?theme, width = Auto, usageLabel = 'USAGE', titleCase = true)Full --help page. Wraps to width. null never wraps. A width below 1 throws
HelpTextrenderRows(rows, ?theme, width = Auto) / renderPage(page, width = null)One two-column block, stacked below MIN_DESCRIPTION_WIDTH (16 cells) / a pre-composed page. renderPage() does not re-wrap unless a width is passed
Themeansi() / plain() / detect(?env, ?stream) / auto(?bg) / detectFor(stream)Colorful palette / no styling / palette downgraded to the stream's color profile / palette that follows the OSC 11 reply the app requested (without a message it is ansi()) / detection for a given stream
Themecharm() / dracula() / nord() / catppuccin() / byName(name) / PRESET_NAMESFixed color presets, the case-insensitive name resolver, and its roster
Themebuild() / withColorProfile(ColorProfile $profile)Fluent ThemeBuilder (all seven slots required before build()) / downgrade any theme to a color profile
Framenew() → withTitle(t) / withTitleText(t, style) / withStatus(s) / withBorderStyle(style) / withTheme(?theme) / withPlainBorder() → render(body, cols, rows)Exactly-rows full-screen box with SGR-preserving ingress sanitation. Throws below 6 rows, and the width floors at 4
Logosugarcraft() / sugarcraftNarrow() / fromAscii(art) / withColor(color) / fits(cols) / render(?profile)Box-drawing wordmark (66 cells) / the same wordmark without the box / custom art, where newlines are the layout / replaceable tint / whether the art fits a width / styled render
AutoWidthAuto (enum case)The shared width sentinel. Auto resolves COLUMNS, an int is exact, and null means no cap

Only methods declared in sugar-cli/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\Cli

AutoWidth enum

The $width argument value that means "size this to the terminal".

Cases: Auto

PHP also provides cases().

Banner final class

Render a bordered title banner. The title is rendered with the theme's accent style; the optional subtitle picks up the muted style. Borders default to Border::rounded() but can be overridden by passing a custom Border instance.

MethodSummary
static title(string $title, string $subtitle = '', ?Theme $theme = null, ?Border $border = null, int|AutoWidth|null $width = null): string

CommandSpec final class

Declarative description of a command: its options, subcommands, the rules between options (requires, conflicts) and how many positional arguments it takes. parse() turns an argv list into ParsedArgs or a UsageError. It is the single input the generators read too: HelpText::fromSpec() for the help page, Completion::script() for bash, zsh and fish completions, and Manpage::render() for the man page.

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
static new(string $name): self
withDescription(string $description): selfOne-line summary for help and completion output.
withOption(Option $option): selfDeclare an option. Long and short names must be unique on this command.
withSubcommand(CommandSpec $subcommand): selfDeclare a subcommand, selected by its name as the first positional.
conflicts(string ...$options): selfAt most one of these options may be given. Options supplied on argv also silence the environment fallback of the others in the set, so an exported variable never makes an explicit command line invalid.
requires(string $option, string ...$required): selfWhen $option is given (argv or env), each of $required must be too. Repeated calls for one option add to its list.
withMinArguments(int $min): selfFewest positional arguments accepted.
withMaxArguments(?int $max): selfMost positional arguments accepted; null is unbounded. When never called, a command with subcommands accepts none, so a mistyped subcommand is reported as one instead of being taken as an argument; an explicit null keeps such a command unbounded.
name(): string
description(): string
options(): arrayDeclared options, keyed by long name, in declaration order. PHP turns an all-digit name such as 5 into an int key; read the name from Option::name() when a string is needed.
option(string $name): ?OptionThe option with this long name, or null.
subcommands(): arrayDeclared subcommands, keyed by name, in declaration order. An all-digit name comes back as an int key; read the name from CommandSpec::name() when a string is needed.
subcommand(string $name): ?CommandSpecThe subcommand with this name, or null.
groups(): arrayOptions grouped for help output: group name => options, groups in order of first appearance; the ungrouped options sit under ''. PHP turns an all-digit group name such as 2024 into an int key; cast the key with (string) or read Option::group() when a string is needed.
conflictSets(): array
requirements(): array
minArguments(): int
maxArguments(): ?intThe configured maximum, or null when unbounded or never set (see effectiveMaxArguments()).
effectiveMaxArguments(): ?intThe maximum parse() enforces: the configured one, else 0 with subcommands, else unbounded (null).
parse(array $argv, ?array $env = null, ?ParseOptions $options = null): ParsedArgs|UsageErrorParse an argument list against this spec.

Completion final class

Shell completion scripts generated from a CommandSpec.

MethodSummary
static script(CommandSpec $spec, Shell $shell): stringThe completion script for $spec's command in $shell.

Frame final class

Full-screen application chrome: a double-line box that fills the terminal exactly, with a centred title bar, top/bottom dividers, and a status bar.

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
static new(): selfDefault root — a slate box border (rgb 100,116,139 = #64748b).
withTitle(string $title): selfThe (pre-rendered) title-bar string, centred on the top row.
withTitleText(string $text, Style $style): selfTheme-aware title rendering — applies $style to $text and sets the result as the title bar. This is a convenience over withTitle() for callers that already have a Style rather than a pre-rendered string.
withStatus(string $status): selfThe (pre-rendered) status-bar string, left-aligned on the bottom row.
withBorderStyle(Style $style): selfOverride the box-drawing border colour (defaults to slate).
withTheme(?Theme $theme = null): selfAdopt the theme's muted style for the border.
withPlainBorder(): selfDrop the border styling entirely (identity Style::new()).
render(string $body, int $cols, int $rows): stringRender the framed body at exactly $cols × $rows cells.

HelpPage final class

The help page of one command in a CommandSpec, built by HelpText::fromSpec() and laid out by HelpText::render(), so spec-driven help and hand-written help share one renderer.

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
static new(CommandSpec $root, string ...$names): selfThe page of $root, or of the subcommand that $names walks down to. HelpText::fromSpec() is the same call.
withTheme(?Theme $theme): selfTheme for the headings and option keys; null (the default) detects one.
withWidth(int|AutoWidth|null $width): selfCell width to wrap to, as HelpText::render() takes it: an int, AutoWidth::Auto (the default, the terminal width) or null (never wrap).
withLabels(array $labels): selfReplace some of the page's own words, keyed as in DEFAULT_LABELS. Keys not given keep their current text.
withTitleCase(bool|\Closure $titleCase): selfTitle styling of the headings, as HelpText::render() takes it: true uppercases (the default), false prints them as given, a closure maps each one.
command(): CommandSpecThe documented command.
usage(): stringThe full usage synopsis, e.g. candy-code run [options] <arg>.
sections(): arrayThe page's sections as HelpText::render() takes them: title => row key => description. Sections with no rows are left out.
render(): stringRender the page through HelpText::render().

HelpText final class

Build a fang-style --help page from structured input. Each supplied section becomes a labelled block of two-column KEY description rows (like git's --help output).

MethodSummary
static fromSpec(CommandSpec $spec, string ...$names): HelpPageThe help page of a CommandSpec: of the root command, or of the subcommand that $names walks down to (fromSpec($spec, 'run')). Call ->render() on the result; the page is laid out by render(), so spec-driven and hand-written help look the same.
static render(string $usage, array $sections, string $description = '', ?Theme $theme = null, int|AutoWidth|null $width = AutoWidth::Auto, string $usageLabel = 'USAGE', bool|callable $titleCase = true): stringRender the full help screen.
static renderPage(string $page, int|AutoWidth|null $width = null): stringSanitize — and optionally re-wrap — an already-laid-out multi-line page.
static renderRows(array $rows, ?Theme $theme = null, int|AutoWidth|null $width = AutoWidth::Auto): stringRender a single two-column block.

Render text-art logos with optional color theming.

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
static fromAscii(string $ascii): selfBuild a Logo from a raw text-art page.
static sugarcraft(): selfBuilt-in SugarCraft logo in box-drawing characters.
static sugarcraftNarrow(): selfBuilt-in SugarCraft logo in narrow figlet art, for tight terminals.
fits(int $cols): boolTrue when every art line fits within $cols display cells.
withColor(string|Color $color): selfRender the logo with a foreground color.
render(?ColorProfile $profile = null): stringRender the logo as a string, applying the chosen color (if any) once.

Manpage final class

A man page in roff (man(7) macros) generated from a CommandSpec.

MethodSummary
static render(CommandSpec $spec, int $section = 1, string $date = ''): string

Option final class

One declared command-line option of a CommandSpec: a flag (--verbose) or a value option (--model gpt), with its short alias, environment fallback, value type, allowed values, default and help group.

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
static flag(string $name): selfA switch with no value: --name (or -x once withShort() is set).
static value(string $name): selfAn option that takes one value: --name value or --name=value.
withShort(string $short): selfSingle-character alias, used as -x. Letters and digits only.
withEnv(string $env): selfEnvironment variable read when the option is absent from argv. An empty variable counts as unset.
withDescription(string $description): selfOne-line help text.
withType(ValueType $type): selfConvert the raw value into an int or float; a value that does not convert is a usage error. Only meaningful on a value option.
withChoices(array $choices): selfRestrict the value to a fixed set of strings (compared exactly). Replaces any withEnum() binding.
withEnum(string $enum): selfRestrict the value to the backing values of a backed enum; the parsed value is the enum case, not the string.
withRepeatable(bool $repeatable = true): selfAccept the option more than once. A repeatable value option collects a list; a repeatable flag counts its occurrences (-vvv is 3). A non-repeatable option given twice keeps the last value.
withRequired(bool $required = true): selfFail with a usage error when neither argv nor the env variable supplies the option. A default never satisfies it, so CommandSpec::withOption() rejects an option with both.
withDefault(mixed $default): selfValue reported when neither argv nor env supplies the option. Taken as given: it is not converted or checked against the choices. On a repeatable value option a non-array default is wrapped in a list, and on a repeatable flag a bool default becomes a count (true is 1). Not allowed on a required option (withRequired()).
withGroup(string $group): selfHelp-page section this option is listed under; '' is the ungrouped section.
withValueName(string $valueName): selfPlaceholder for the value in help output, e.g. --model <MODEL>.
withPersistent(bool $persistent = true): selfAlso accept this option after any subcommand of the command that declares it.
withOptionalValue(bool $optional = true): selfOptional value (a per-option parse mode): the value may be absent. Bare at the end of argv, or followed by an option-shaped token, the option is still given (ParsedArgs::has() is true) with the value null; a following plain token is its value, and --name= passes the empty string as the value: a string option without choices gets '', while a typed or choice-restricted option validates it as it would any empty value (and rejects it). Only meaningful on a value option.
withNonEmpty(bool $nonEmpty = true): selfReject empty values (a per-option parse mode): --name= or --name '' on argv is a UsageErrorKind::EmptyValue error instead of the empty string. An empty env variable already counts as unset, and a default is taken as given. Only meaningful on a value option.
withSwitchValues(bool $switchValues = true): selfBoolean switch values (a per-option parse mode): --name=true|yes|1 sets the flag and --name=false|no|0 (any letter case) sets it off, an explicit off that still counts as given but triggers no CommandSpec::requires() and joins no conflict; any other word is an UsageErrorKind::InvalidValue error. Without it a flag rejects =value as UsageErrorKind::UnexpectedValue. A repeatable flag counts only its true occurrences. Only meaningful on a flag.
name(): stringLong name, without the leading --.
kind(): OptionKind
takesValue(): boolTrue for a value option, false for a flag.
short(): ?stringShort alias without the -, or null.
env(): ?stringFallback environment variable, or null.
description(): string
type(): ValueType
choices(): arrayAllowed raw values; empty means any value.
enum(): ?stringBacked enum the value maps to, or null.
repeatable(): bool
required(): bool
default(): mixedThe configured default, or null when none was set.
group(): string
valueName(): stringValue placeholder for help output; defaults to the upper-cased name.
persistent(): bool
optionalValue(): boolTrue when the value may be absent (withOptionalValue()).
nonEmpty(): boolTrue when an empty argv value is an error (withNonEmpty()).
switchValues(): boolTrue when the flag accepts =true/=false words (withSwitchValues()).
display(): string--name, the spelling used in usage errors and help.

OptionKind enum

Whether an Option is a bare switch or carries a value.

Cases: Flag · Value

PHP also provides cases().

ParseOptions final class

Opt-in parser modes for CommandSpec::parse(). ParseOptions::new() has every mode off, and a parse given it (or given no options at all) behaves exactly as the default rules in the CommandSpec docblock. Each with*() turns on one mode:

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
static new(): selfEvery mode off: the default parse rules.
withCollectErrors(bool $on = true): selfCollect errors: keep parsing after an error and report every one.
withDashValuesAsOptions(bool $on = true): selfOption-like values are not values: a dash-leading token, a negative number included, is never a value (a lone - still is).
withVerbsAnywhere(bool $on = true): selfVerbs anywhere: a subcommand is recognized after other positionals.
withShortGroupingOff(bool $on = true): selfShort grouping off: -pv is one unknown option, not -p -v.
withKeptSpellings(bool $on = true): selfShort spelling kept: record the spelling argv typed for each option.
withTypedErrors(bool $on = true): selfTyped error kinds: every error carries the option's long name and typed spelling.
withContinueAfterMissingValue(bool $on = true): selfContinue after a missing value: with collect errors, judge the token after a missing value.
collectErrors(): bool
dashValuesAsOptions(): bool
verbsAnywhere(): bool
shortGroupingOff(): bool
keptSpellings(): bool
typedErrors(): bool
continueAfterMissingValue(): bool

ParsedArgs final class

The successful result of CommandSpec::parse(): the selected command path, the resolved value and source of every option in that command's parse, and the positional arguments.

MethodSummary
static new(array $command, array $values, array $sources, array $arguments, array $spellings = []): self
command(): arraySelected command path, root first (['git', 'remote', 'add']).
has(string $name): boolTrue when the option came from argv or its env variable (a default does not count).
value(string $name): mixedResolved value of an option by long name.
source(string $name): ?ValueSourceWhere the value came from, or null when nothing (not even a default) supplied one.
values(): arrayResolved value of every option in this command's parse (see the class docblock), keyed by long name. PHP turns an all-digit name such as 5 into an int key; cast it with (string) before passing it on as a name.
arguments(): arrayPositional arguments in order, including everything after --.
spellings(): arrayThe spellings argv typed, recorded only under ParseOptions::withKeptSpellings() (empty otherwise): typed spelling (-n, --dry-run) => the values it gave, in argv order (a flag records true, or its switch word's bool; an optional value given bare records null). Two spellings of one option stay distinct keys. Only options in this command's parse are listed. PHP turns a digit short spelling such as -5 into an int key; cast it with (string).

Section final class

Render a section header — a label sandwiched between two horizontal rules: ── LABEL ──────────────. Common in CLI output where you want to break long stretches of stdout into named groups.

MethodSummary
static header(string $label, ?Theme $theme = null, int $leftPad = 2, int|AutoWidth|null $width = AutoWidth::Auto, string $rune = '─'): string
static rule(?Theme $theme = null, int|AutoWidth|null $width = AutoWidth::Auto, string $rune = '─'): stringRender a horizontal rule — the fill of header('') without its lead/label logic. Pass width: null for a fixed 2-cell dash. The rule is styled with the theme's muted style and accepts a custom fill rune (measured in cells for multi-cell glyphs).
static subHeader(string $label, ?Theme $theme = null, int $indent = 4, int|AutoWidth|null $width = AutoWidth::Auto, string $rune = '·'): stringRender an indented section divider for sub-sections.

Shell enum

A shell Completion::script() can write a completion script for. The backing value is the shell's usual name, so Shell::tryFrom($argv[2]) maps a completion <shell> argument.

Cases: Bash · Zsh · Fish

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

Stage final class

Render a numbered "stage" line — an arrow / marker glyph + step number + message. Designed for build-script style output where each major action gets its own line:

MethodSummary
static step(string $message, int $current, int $total, ?Theme $theme = null, string $glyph = self::GLYPH_ARROW, int|AutoWidth|null $width = AutoWidth::Auto): stringRender a stage line. Pass total = 0 to omit the /total suffix. Counts are clamped to the range [0, total] (i.e. negative values become 0, and current > total is capped at total).
static subStep(string $message, ?Theme $theme = null, bool $isLast = false, int $indent = 2, int|AutoWidth|null $width = AutoWidth::Auto): stringRender a tree-style sub-step that visually nests under the preceding step() line.
static subStepWithProgress(string $message, int $current, int $total, ?Theme $theme = null, bool $isLast = false, int $indent = 2, int|AutoWidth|null $width = AutoWidth::Auto, ?int $frame = null, int $segments = self::BAR_SEGMENTS): stringRender a sub-step with an inline progress bar.

StatusLine final class

Render a single styled "status line" — a glyph + space + message. Shaped after the success / error / warn / info lines common in Go CLI tooling so the four severities (plus the prompt) all look consistent within one program.

MethodSummary
static success(string $message, ?Theme $theme = null, int|AutoWidth|null $width = AutoWidth::Auto): string
static error(string $message, ?Theme $theme = null, int|AutoWidth|null $width = AutoWidth::Auto): string
static warn(string $message, ?Theme $theme = null, int|AutoWidth|null $width = AutoWidth::Auto): string
static info(string $message, ?Theme $theme = null, int|AutoWidth|null $width = AutoWidth::Auto): string
static prompt(string $message, ?Theme $theme = null, int|AutoWidth|null $width = AutoWidth::Auto): string

Terminal final class

What a CLI can learn about the terminal it writes to.

MethodSummary
static columns(mixed $stream = null): ?intThe column count to lay output for $stream out at, or null when nothing credible answers.

Theme final class

Per-status palette for the presenters that take one — StatusLine, Banner, Section, Stage and HelpText (every one of them falls back to detect() when handed no theme, per below). Themes are immutable; ansi() ships the default colourful palette, plain() produces a no-op palette ideal for snapshot tests, and the named presets in PRESET_NAMES (charm, dracula, nord, catppuccin, plus auto) cover the most-requested branded palettes.

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
__construct(public readonly Style $success, public readonly Style $error, public readonly Style $warn, public readonly Style $info, public readonly Style $prompt, public readonly Style $accent, public readonly Style $muted)All seven slots are non-nullable: a theme without a style for a level is an illegal state, so the type system enforces it at the boundary (strict_types turns a null argument into a TypeError) instead of a hand-rolled constructor loop.
static ansi(): self
static detect(?array $env = null, mixed $stream = null): selfThe ansi() palette downgraded to the colour capability of the output stream — the fallback every presenter uses when no theme is passed.
withColorProfile(ColorProfile $profile): selfDowngrade every style in this theme to $profile.
static plain(): self
static auto(?BackgroundColorMsg $bg = null): selfTerminal-adaptive factory — picks a dark or light theme by checking the terminal background colour.
static build(): ThemeBuilderBegin building a custom theme with a fluent interface.
static charm(): selfCharm-brand pink + cyan accent set.
static dracula(): selfDracula palette — hex literals re-sourced from sugar-core's Palettes::DRACULA single-source-of-truth so they no longer drift as they are hand-copied around the monorepo.
static nord(): selfNord palette — cool blues and frost tones.
static catppuccin(): selfCatppuccin Mocha — pastel set.
static byName(string $name): selfResolve a theme by name. Presets: 'ansi', 'plain', 'charm', 'dracula', 'nord', 'catppuccin', and 'auto' (the adaptive factory with no background msg — the ansi() fallback). Case-insensitive.
static detectFor(mixed $stream): selfDetect for one named stream — the entry point for callers that already know their destination (a file handle, a pty master) and want the detect() downgrade without going through the default-stream substitution.

UsageError final class

The result of a CommandSpec::parse() that broke a rule: which rule (kind()), the values involved (params()), the command path it was raised in, and a ready English message().

MethodSummary
static new(UsageErrorKind $kind, array $params, array $command): self
static collected(array $errors, ParsedArgs $partial): selfThe result of a collect-errors parse (ParseOptions::withCollectErrors()): the first error, carrying every error and the values that did parse.
kind(): UsageErrorKind
params(): array
command(): arrayCommand path the error was raised in, root first (['git', 'remote']).
option(): ?stringThe option the error is about as --name (an unknown short option keeps its -x spelling), or null for a command or argument error.
optionName(): ?stringThe option's long name without dashes, or null when the error is about no declared option. Set only under ParseOptions::withTypedErrors().
spelling(): ?stringThe option as argv typed it (-m, --model), or null when argv did not type it. Set only under ParseOptions::withTypedErrors().
errors(): arrayEvery error of the parse, this one first. A default parse stops at the first error, so this is [$this]; a collect-errors parse (ParseOptions::withCollectErrors()) lists all of them in the order found.
partial(): ?ParsedArgsWhat a collect-errors parse resolved despite its errors: the command path, the options that parsed and the positionals. Null for a default parse, which stops at the first error.
suggestion(): ?stringThe did-you-mean candidate, or null when nothing was close enough.
message(): stringOne-line English description of the error, without a trailing period.

UsageErrorKind enum

Which parse rule a UsageError broke. Callers that localize their CLI switch on this and UsageError::params() instead of the English UsageError::message(). Under ParseOptions::withTypedErrors() every kind's params also carry name (the option's long name, or null when the error is about no declared option) and spelling (the option as argv typed it, or null when argv did not type it).

Cases: UnknownOption · UnknownCommand · MissingValue · EmptyValue · UnexpectedValue · InvalidValue · InvalidChoice · MissingOption · MissingRequirement · ConflictingOptions · TooFewArguments · TooManyArguments

PHP also provides cases().

ValueSource enum

Where a resolved option value in ParsedArgs came from.

Cases: Argv · Env · Default

PHP also provides cases().

ValueType enum

The PHP type a value Option converts its raw string into.

Cases: String · Int · Float

PHP also provides cases().

Configuration

sugar-cli has no config file and no options object. Its behavior is set by the theme, color profile and width arguments you pass, and by these environment variables, which the default theme and width resolution read.

VariableTypeDefaultEffect
COLUMNSint (exported)80Width used by AutoWidth::Auto. Must be exported to be seen by PHP. Values outside 1 to 10000 are discarded
NO_COLORany non-empty valueunsetOn a terminal, drops color and keeps bold and faint, resolving to the Ascii profile. On a pipe or redirect, the non-tty profile drops every SGR attribute, bold and faint included. An empty value counts as unset
CLICOLOR_FORCE / FORCE_COLORCLICOLOR_FORCE: any non-empty value except 0, so false forces. FORCE_COLOR: true, yes or on, or a level of 1 or more. 0, an empty value and other words do not forceunsetForces color on, even through a pipe or with TERM=dumb
CLICOLOR0 or otherunsetBSD convention. 0 drops color unless forced
TERMstringunsetdumb emits no escape bytes unless color is forced

The full list of variables that Theme::detect() reads is NO_COLOR, CLICOLOR, CLICOLOR_FORCE, FORCE_COLOR, TERM, COLORTERM, TERM_PROGRAM, WT_SESSION, TMUX, STY, GOOGLE_CLOUD_SHELL, CI, GITHUB_ACTIONS, GITLAB_CI and BUILDKITE. Pass your own array as Theme::detect($env) to test a case without touching the process environment.

Keys and input

sugar-cli reads no keyboard input and handles no key bindings. It is output-only. An interactive program that needs keys should use sugar-core for its event loop and call sugar-cli for the rendering.

Theme and color

A theme is a Theme value with seven slots: success, error, warn, info, prompt, accent and muted. Each slot holds a SugarCraft\Style\Style. Theme::ansi() is the default palette. Theme::plain() gives every slot a bare Style::new(), so bold and faint are removed as well.

The presets are charm(), dracula(), nord() and catppuccin(). Theme::byName() resolves any of them, plus ansi, plain and auto, case-insensitively. Theme::auto($bg) adapts to the background only when the app passes the parsed OSC 11 reply it asked for with Cmd::requestBackgroundColor(). Without a message it returns ansi(), so byName('auto') never adapts by itself.

Theme::detect() downgrades the palette to what the output can show, through sugar-core's ColorProfile ladder. CLICOLOR_FORCE and FORCE_COLOR are resolved first and outrank a non-tty pipe and TERM=dumb. Otherwise a non-tty stream or TERM=dumb emits no escape bytes. Every presenter called without a theme uses detect(). An explicit theme renders exactly as given, so apply the downgrade yourself with $theme->withColorProfile(ColorProfile::detectTerminal(null, STDOUT)).

Two seeded styles bypass the downgrade and emit SGR even through a pipe: the slate border on Frame::new() (#64748b) and the tint from Logo::withColor(). Call Frame::withTheme() to route the border through the theme's muted slot, or withPlainBorder() to drop the border styling.

Examples

  • examples/cli-page.php builds one fang-style page with every presenter: a Banner, two Section headers, Stage steps and sub-steps, StatusLine rows and a HelpText page. It uses the Dracula theme, downgraded to what STDOUT can show. Run it with php examples/cli-page.php.
  • examples/logo.php prints the built-in SugarCraft logo, a custom ASCII logo built with Logo::fromAscii(), and a tinted custom logo. The tint is applied only when the profile supports 256 colors.

Both scripts read vendor/autoload.php, so run them from the library root after composer install.

Testing

cd sugar-cli
composer install
vendor/bin/phpunit

The suite covers each presenter with golden ANSI snapshots (sugar-testing's assertGoldenAnsi), the theme resolution order including the dumb-terminal veto, the width resolution rules, and a smoke run of both examples as child processes. Golden files are create-only: delete a fixture and re-record it to accept an intended render change.

Troubleshooting

The output has no color when I expect it

Check whether the stream is a terminal. A piped or redirected STDOUT gets no escape bytes, and TERM=dumb does the same. Set CLICOLOR_FORCE=1 to keep color through a pipe, or pass an explicit theme, which renders as given without the downgrade.

The width ignores my terminal size

sugar-cli reads COLUMNS only when it is exported. A bash-private COLUMNS is invisible to PHP. Run export COLUMNS in your shell profile, or pass an int width explicitly. Values outside 1 to 10000 are ignored, and the 80-cell fallback applies.

A status line is cut with an ellipsis

The message is clipped to the width budget, and the glyph is kept. Pass width: null to render the full message with no cap, or a wider int. At a budget too small for the glyph and separator, only the glyph remains.

Frame::render() throws

The frame needs at least 6 rows for its border, title, divider and status chrome. A smaller $rows throws \InvalidArgumentException. Check the rows argument against the terminal height before rendering.

A preset name throws

Theme::byName() matches case-insensitively against Theme::PRESET_NAMES. An unknown name throws \InvalidArgumentException and lists the valid names in the message. Catch it at the boundary if the name comes from user input.

Architecture

Every presenter follows the same pipeline. The width argument resolves through WidthProbe, which applies the AutoWidth sentinel. Caller text passes through SafeText at ingress, which strips escape and control bytes except for the SGR sequences a styled title is allowed to carry. The remaining text is measured in display cells, not bytes, and then clipped by Clip. The glyph and the bar are reserved before the message is measured, so they are never clipped.

Themes are immutable: withColorProfile() returns a new Theme, and ThemeBuilder collects the seven slots before building one. Theme::detect() memoizes its result per environment snapshot, so a test that changes NO_COLOR sees the new value rather than a stale answer.

Upstream mapping

charmbracelet/fang (Go)sugar-cli (PHP)
Help screen layout (usage, flag groups, description)HelpText::render(), renderRows(), renderPage()
Color profile detection (colorprofile.Detect)Theme::detect(), backed by sugar-core's ColorProfile
Styled title and status outputBanner, StatusLine, Section
Command, flag and argument parsing (cobra and pflag)CommandSpec::parse(), returning ParsedArgs or UsageError. Not ported: cobra itself, so sugar-cli does not run commands

The surface inventory is in the README. The port mapping is in docs/MATCHUPS.md.

Changelog and versioning

sugar-cli has no separate changelog file. Its history is the commit log of the sugar-cli/ directory in the monorepo, and the Composer package tracks dev-master, so consumers pin to a commit rather than a tagged release. Read the commit history for what changed and when.

Try the quickstart →

Demos.

The library's CLI page example rendered as a VHS-recorded GIF. Regenerated automatically on every push that touches the source.

CLI page

StatusLine + Banner + Section + Stage + HelpText forming a cohesive CLI page.