sugarcraft / sugar-cli
Opinionated CLI presentation helpers shaped after charmbracelet/fang's output layer: StatusLine (✓/✗/⚠/ℹ), Banner, Section header, Stage step, HelpText page, Frame, Logo, and stock themes (ansi/plain/charm/dracula/nord/catppuccin, plus terminal-adaptive auto).
Requires
- php: ^8.3
- ext-mbstring: *
- sugarcraft/sugar-colorprofile: dev-master
- sugarcraft/sugar-core: dev-master
- sugarcraft/sugar-style: dev-master
Requires (Dev)
- phpunit/phpunit: ^10.5
- sugarcraft/sugar-testing: dev-master
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-20 01:04:03 UTC
README
SugarCli
Formerly published as
sugarcraft/candy-kit(renamed 2026-10). Namespace changed:SugarCraft\Kit\→SugarCraft\Cli\.
composer require sugarcraft/sugar-cli "@dev"
Install note: sibling
sugarcraft/*packages trackdev-master(the same constraint sugar-cli's own manifest uses for its deps), and the monorepo setsminimum-stability: devwithprefer-stable: true. A consumer pinning stable releases only should mirror that pair in its own root manifest or install fails to resolve.
Built on two siblings only: sugarcraft/sugar-core (the ColorProfile
detection ladder and ANSI-aware width primitives) and sugarcraft/sugar-style
(Style and Border value objects). In this monorepo it is consumed in-tree
by candy-code's help page (candy-code/src/Cli/Help.php, via HelpText)
and candy-sql's terminal chrome (candy-sql/src/Terminal/BorderFrame.php,
via Frame).
sugar-cli is opinionated about pixels, silent about process: CLI presentation helpers that turn ordinary command-line output into something that matches the rest of the SugarCraft stack, for PHP 8.3+. sugar-cli is library-only — drop it into any Composer project, no Symfony Console requirement.
<?php use SugarCraft\Cli\StatusLine; use SugarCraft\Cli\Banner; echo Banner::title('MyApp', 'v0.1.0'), "\n\n"; echo StatusLine::info('connecting to https://example.com'), "\n"; echo StatusLine::success('done in 0.4s'), "\n"; echo StatusLine::warn('disk almost full'), "\n"; echo StatusLine::error('connection refused'), "\n";
Presenters
Theme— palette ofSugarCraft\Style\Styleobjects keyed by status level (success / error / warn / info / prompt / accent / muted).Theme::ansi()ships the colourful palette;Theme::plain()strips all styling (a bareStyle::new()in every slot, so bold and faint go too);Theme::charm(),dracula(),nord()andcatppuccin()are fixed presets;Theme::auto($bg)adapts to the background colour only when the app passes the parsed OSC-11 reply it requested viaCmd::requestBackgroundColor()— without a message it isansi(), soTheme::byName('auto')never adapts;Theme::byName('nord')resolves any of them case-insensitively (roster inTheme::PRESET_NAMES). Bring your own theme by passing styles to the constructor, or chainTheme::build()— the builder requires all seven slots beforebuild()succeeds.Theme::detect()is theansi()palette downgraded to what the output can show, via sugar-core'sColorProfile::detectTerminal()(detect()plus the dumb-terminal veto) — its ladder, in order:CLICOLOR_FORCE/FORCE_COLORare resolved first and outrank tty-ness andTERM=dumb, so a forced stream keeps full colour even through a pipe; otherwise a non-tty STDOUT (myapp --help | less) andTERM=dumbresolve the same way and emit no escape bytes at all — that downgrade drops the bold attribute along with the colour, unlikeNO_COLOR, which the force vars outrank, drops colour while keeping bold, and resolves to the Ascii profile; BSDCLICOLOR=0drops colour unless forced. The roster authority is sugar-core'sColorProfiledocblock — sugar-cli never re-implements the order. Every presenter called without a theme usesTheme::detect(); an explicitly passed theme is rendered as given — apply the same downgrade to any preset with$theme->withColorProfile(\SugarCraft\Core\Util\ColorProfile::detectTerminal(null, STDOUT))(detect()throws anInvalidArgumentExceptionwhen a stream you pass explicitly is not an open resource; the implicitSTDOUTsubstitute never errors). Two seeded styles bypass the downgrade because they are rendered as given and emit SGR even through a pipe:Frame::new()'s slate border (#64748b) and the tint fromLogo::withColor(). Both can opt in to honouring the theme instead:Frame::withTheme($t)routes the border through$t->muted(no argument usesTheme::detect()),->withPlainBorder()drops border styling entirely, andLogo::render(ColorProfile::detectTerminal())re-quantises the tint (NoTtyremoves it). The defaults stay the branded splash — slate seed and tint-as-given — so only callers that pass a theme or profile change. For fully plain output under every profile passTheme::plain()and, for a colourless Frame border,->withPlainBorder().StatusLine—success/error/warn/info/promptstatic helpers returning a themed glyph + space + message. Only the glyph is styled; the space and the message itself stay plain. The severity glyphs (✓ ✗ ⚠ ℹ) are single-cell Unicode and the prompt is a plain?— they survive every degraded profile, because the downgrade ladder governs escape bytes only, never characters. A status line is therefore never color-only: screen readers and log greps still see them (the UTF-8 assumption behind those characters is its own contract — see Output assumptions below). Every call takes a trailingint|AutoWidth|null $widthbudget: an over-long message is clipped with…to fit (the glyph is never clipped;nullrenders the full message). At a budget too small to fit glyph plus separator space, the line collapses to the styled glyph alone — the message is gone, but the status is still readable.Banner— render a bordered title block with optional subtitle, rounded by default (a sugar-styleBorder;Border::ascii()is the code-page-safe variant). Useful for app intros /--versionoutput. Unlike the other width-aware presenters,Banner::title()hard-cuts its lines at the box edge — no…— because the border itself is the truncation marker.Logo— Unicode box-drawing text art:Logo::sugarcraft()(66 cells wide, deliberately not clamped to the terminal) plusLogo::fromAscii($art)for custom multi-line art. All escape bytes — SGR included — and control bytes are stripped on ingress; newlines are the layout;->withColor($hex)tints the art, and a second call replaces the tint.Section— one-line themed dividers:header()label + fill rule, barerule(), and indentedsubHeader()for nesting under a parent. An explicitwidthis a hard cap: an over-long label is cut with…rather than overflowing the line. Omittedwidthdefaults to the terminal width (exportedCOLUMNS, else 80 cells).nullopts out of the cap and the fill, not of the line:header()/subHeader()render label plus a single trailing rune, andrule()renders two cells of the rule rune (default─, U+2500).Stage— per-line step renderers for progressive CLI output:step()(numbered),subStep(), andsubStepWithProgress()(bar or spinner). Messages take the same width budget asStatusLine(tree glyphs and the progress bar are never clipped — the bar's cells are reserved before the message is measured).subStepWithProgress()also takes a trailing?int $frameto pin the spinner glyph whenever bytes must be deterministic (goldens, recorded sessions); omitted, it walks the wall clock. The stage glyphs are public constants —Stage::GLYPH_ARROW,Stage::GLYPH_BULLET,Stage::GLYPH_HASH— and the spinner walksStage::SPINNER_FRAMES(ten braille frames); at a width too small to fit the prefix, bar and suffix together, the bar is dropped and the line degrades to thesubStep()shape. Both counters are clamped before any drawing — negatives floor to 0 and$currentnever exceeds$total— so a corrupt counter yields a full bar, never a broken one: the presenter does not trust caller math.HelpText—--helppage:USAGE(retitle via theusageLabelparameter), an optional description, and titled two-columnKEY descriptionsections.HelpText::render($usage, $sections, $description)takes$sectionsas anarray<string, array<string, string>>keyed by section title, then entry label, with the description as leaf value — a section title mapped to an empty array renders no block. Wraps towidth(omitted = the terminal width via exportedCOLUMNS, else 80 cells;null= never wrap): long descriptions continue at the description column, and switch to a stacked layout (description under the key) when the key column leaves fewer thanHelpText::MIN_DESCRIPTION_WIDTH(16) cells. Keys and section titles are never wrapped or cut — in stacked mode a very long key overflows the width on its own line, and in grid mode it widens the whole key column (pushing descriptions toward their one-cell wrap floor), so keep keys short either way; the stacked continuation indent isHelpText::STACKED_INDENT(6 cells). Section titles and the usage label are upper-cased withmb_strtoupper(a title can grow —ß→SS); passtitleCase: false, or a callable mapping, torender()to own the casing.renderRows()renders just the key/description grid, andrenderPage()renders a complete pre-composed page without re-wrapping it by default (null); pass anint/AutoWidthto word-wrap over-long rows.Frame— full-screen application chrome: a double-line box that fills the terminal exactly (Frame::new()->withTitle($bar) ->withStatus($bar)->render($body, $cols, $rows)), with a centred title bar, dividers, and a status bar. Normalises the body to a constant line count and pads ANSI-width-aware so it never overflows the terminal — safe for a SugarCraft app whose frame-diff renderer owns the screen. Titles, status lines and body lines may carry inline SGR styling; every other escape and control byte is stripped on ingress (the SGR-preservingSafeText::styledLine()gate), andwithTitleText()/withBorderStyle()let you style plain text without building escapes yourself. The stripping guarantee covers the strings; the border style fromwithBorderStyle()is rendered as given and a sugar-styleStylemay carry an OSC-8 hyperlink envelope — pass only styles whose bytes you want on the terminal. An unclosed SGR on width-fitting content can bleed into the surrounding padding — close your styles or pass them throughwithTitleText(). Geometry floors are part of the contract:render()throwsInvalidArgumentExceptionbelow 6 rows (the fixed chrome cost); widths under 4 are clamped up to 4, so a 1-3 column terminal sees wrapped lines; and body rows pastrows - 6are dropped, never scrolled.AutoWidth— theint|AutoWidth|null $widthsentinel shared by the presenters:AutoWidth::Autoresolves the terminal width (exportedCOLUMNS, else 80 cells; implausibly large advertised values are discarded as junk), anintmeans exactly that many cells, andnullrenders without a cap. TheAutoresolution reads the exportedCOLUMNSonly: bash keepsCOLUMNSprivate and never re-exports it on resize, so under bash a stale (or absent) value is expected — zsh and fish export and refresh it. Most presenters default toAuto; two keep anulldefault and say so differently:Banner::title()isint|AutoWidth|nulltoo — terminal sizing on request — but therenull(the default) sizes the box to its content, because a banner is not terminal-sized unless asked; andHelpText::renderPage()defaults tonull, which means never re-wrap an already-authored page.
Output assumptions
Charset. The color ladder (see Theme::detect() above) governs escape
bytes only — it says nothing about the character set. sugar-cli emits hard
UTF-8: the severity glyphs (✓ ✗ ⚠ ℹ, plus the plain ? prompt), the
─/▸/•/# rules and stage glyphs, the braille spinner frames, and
Logo's box-drawing art are fixed bytes. WHEN THIS BITES: on a legacy
code-page sink — CP437/CP850 consoles, or LANG=C/POSIX locales — those
bytes corrupt no matter which profile the ladder chose. Remedies: pass a
custom $rune to Section, pass Border::ascii() to Banner, or hand
Logo::fromAscii() plain art. Frame and StatusLine carry no ASCII
substitution: Frame's box chrome and the status glyphs stay as emitted, so
on such a terminal the degraded answer is Theme::plain() plus plain
dash-ruled Section lines instead of a frame.
Motion. sugar-cli never owns a redraw loop — the caller animates. To
honor a user's reduced-motion preference, check
\SugarCraft\ColorProfile\Probe::reducedMotion() (sugar-colorprofile) before
scheduling spinner frames, and prefer the determinate progress bar, or pin
$frame to keep output byte-stable without animation.
Overflow. The cut policy is split by design. Budgeted text that gets
wide — Section labels, StatusLine/Stage messages, Frame titles and
body rows — is clipped with a trailing …. Banner::title() is the named
exception: it hard-cuts at the box edge with no ellipsis, because the closed
border is the truncation marker.
What this is not
sugar-cli is the presentation half of a CLI: it renders strings and leaves every other decision to you.
- No argument parsing, exit codes or output routing. Every helper
returns a string; whether it goes to STDOUT or STDERR and what the
process exits with is the application's call. Feed sugar-cli from
symfony/console, a
getopt()loop, or your own argv code — it only ever renders strings. - No interaction machinery. Line editing and prompts live in
sugar-readline; scripted TUI shells incandy-scriptui. This library only decorates the text you already decided to print. - No bundled translations. sugar-cli ships no language catalog: every visible string is caller text, and the library's own characters (glyphs, rules) are structure, not words. Localize in the app and pass translated arguments in.
- No user configuration. sugar-cli reads no config file and writes no
state — fang's
fang.jsonuser-theme loading is the application's job.Themeis the persistence boundary: your chosen palette arrives as an argument and never from disk. - No shell-outs, and width never touches a device. Width comes from
the environment or an explicit parameter — see
AutoWidthabove; the library never issues a terminal ioctl to measure one. (Theme detection does ask whether the stream is a tty via PHP'sstream_isatty(), which an ioctl backs inside PHP itself — still no subprocess, and no size-probing.) - The charmbracelet/fang label describes the shape of the output, not a parity promise: sugar-cli renders the same kind of status and help pages, without cobra-style typed flag metadata (required/optional/default markers are whatever you put in your key strings).
Demos
CLI page
Examples
examples/cli-page.php— one page wiring together every presenter:Banner,Section,Stage,StatusLineandHelpText. It is exactly what thecli-pagedemo above records.examples/logo.php— theLogowordmark and tint flow.
Run either with php examples/<name>.php from this directory; both need no
arguments and exit 0. They are the quickest whole-program check of the
drop-into-your-app path.
Tests
cd sugar-cli && composer install && vendor/bin/phpunit
In a monorepo checkout, run php scripts/refresh-deps.php --mode=linked from the
repo root after the install — otherwise the bare install above resolves sibling
sugarcraft/* packages from their (stale) Packagist snapshots instead of the
working tree you are actually testing.
Snapshot tests
Presenter output is pinned via sugar-testing's assertGoldenAnsi
golden-file snapshots under tests/fixtures/. The comparison is
byte-exact and the fixtures are create-only: an existing golden is
never rewritten by a test run, so an intended change to a render must be
re-recorded deliberately — delete the fixture, run once with
UPDATE_GOLDENS=1 vendor/bin/phpunit (or SUGAR_TESTING_UPDATE_GOLDENS=1)
to mint the new canonical bytes, then re-run plain to confirm it holds.
Review the diff before committing: golden churn means every user sees a
different render.
Credits & inspiration
Originally inspired by the Go Charm ecosystem; SugarCraft is developed as a native PHP project.
