Search by

sugarcraft / sugar-cli

detain

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

dev-master 2026-11-18 21:47 UTC

This package is auto-updated.

Last update: 2026-11-20 01:04:03 UTC


README

sugar-cli

SugarCli

Formerly published as sugarcraft/candy-kit (renamed 2026-10). Namespace changed: SugarCraft\Kit\ → SugarCraft\Cli\.

CI codecov Packagist Version License PHP

composer require sugarcraft/sugar-cli "@dev"

Install note: sibling sugarcraft/* packages track dev-master (the same constraint sugar-cli's own manifest uses for its deps), and the monorepo sets minimum-stability: dev with prefer-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 of SugarCraft\Style\Style objects keyed by status level (success / error / warn / info / prompt / accent / muted). Theme::ansi() ships the colourful palette; Theme::plain() strips all styling (a bare Style::new() in every slot, so bold and faint go too); Theme::charm(), dracula(), nord() and catppuccin() are fixed presets; Theme::auto($bg) adapts to the background colour only when the app passes the parsed OSC-11 reply it requested via Cmd::requestBackgroundColor() — without a message it is ansi(), so Theme::byName('auto') never adapts; Theme::byName('nord') resolves any of them case-insensitively (roster in Theme::PRESET_NAMES). Bring your own theme by passing styles to the constructor, or chain Theme::build() — the builder requires all seven slots before build() succeeds. Theme::detect() is the ansi() palette downgraded to what the output can show, via sugar-core's ColorProfile::detectTerminal() (detect() plus the dumb-terminal veto) — its ladder, in order: CLICOLOR_FORCE / FORCE_COLOR are resolved first and outrank tty-ness and TERM=dumb, so a forced stream keeps full colour even through a pipe; otherwise a non-tty STDOUT (myapp --help | less) and TERM=dumb resolve the same way and emit no escape bytes at all — that downgrade drops the bold attribute along with the colour, unlike NO_COLOR, which the force vars outrank, drops colour while keeping bold, and resolves to the Ascii profile; BSD CLICOLOR=0 drops colour unless forced. The roster authority is sugar-core's ColorProfile docblock — sugar-cli never re-implements the order. Every presenter called without a theme uses Theme::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 an InvalidArgumentException when a stream you pass explicitly is not an open resource; the implicit STDOUT substitute 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 from Logo::withColor(). Both can opt in to honouring the theme instead: Frame::withTheme($t) routes the border through $t->muted (no argument uses Theme::detect()), ->withPlainBorder() drops border styling entirely, and Logo::render(ColorProfile::detectTerminal()) re-quantises the tint (NoTty removes 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 pass Theme::plain() and, for a colourless Frame border, ->withPlainBorder().
  • StatusLine — success / error / warn / info / prompt static 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 trailing int|AutoWidth|null $width budget: an over-long message is clipped with … to fit (the glyph is never clipped; null renders 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-style Border; Border::ascii() is the code-page-safe variant). Useful for app intros / --version output. 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) plus Logo::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, bare rule(), and indented subHeader() for nesting under a parent. An explicit width is a hard cap: an over-long label is cut with … rather than overflowing the line. Omitted width defaults to the terminal width (exported COLUMNS, else 80 cells). null opts out of the cap and the fill, not of the line: header()/subHeader() render label plus a single trailing rune, and rule() renders two cells of the rule rune (default ─, U+2500).
  • Stage — per-line step renderers for progressive CLI output: step() (numbered), subStep(), and subStepWithProgress() (bar or spinner). Messages take the same width budget as StatusLine (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 $frame to 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 walks Stage::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 the subStep() shape. Both counters are clamped before any drawing — negatives floor to 0 and $current never exceeds $total — so a corrupt counter yields a full bar, never a broken one: the presenter does not trust caller math.
  • HelpText — --help page: USAGE (retitle via the usageLabel parameter), an optional description, and titled two-column KEY description sections. HelpText::render($usage, $sections, $description) takes $sections as an array<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 to width (omitted = the terminal width via exported COLUMNS, 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 than HelpText::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 is HelpText::STACKED_INDENT (6 cells). Section titles and the usage label are upper-cased with mb_strtoupper (a title can grow — ß → SS); pass titleCase: false, or a callable mapping, to render() to own the casing. renderRows() renders just the key/description grid, and renderPage() renders a complete pre-composed page without re-wrapping it by default (null); pass an int/AutoWidth to 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-preserving SafeText::styledLine() gate), and withTitleText() / withBorderStyle() let you style plain text without building escapes yourself. The stripping guarantee covers the strings; the border style from withBorderStyle() is rendered as given and a sugar-style Style may 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 through withTitleText(). Geometry floors are part of the contract: render() throws InvalidArgumentException below 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 past rows - 6 are dropped, never scrolled.
  • AutoWidth — the int|AutoWidth|null $width sentinel shared by the presenters: AutoWidth::Auto resolves the terminal width (exported COLUMNS, else 80 cells; implausibly large advertised values are discarded as junk), an int means exactly that many cells, and null renders without a cap. The Auto resolution reads the exported COLUMNS only: bash keeps COLUMNS private 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 to Auto; two keep a null default and say so differently: Banner::title() is int|AutoWidth|null too — terminal sizing on request — but there null (the default) sizes the box to its content, because a banner is not terminal-sized unless asked; and HelpText::renderPage() defaults to null, 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 in candy-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.json user-theme loading is the application's job. Theme is 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 AutoWidth above; the library never issues a terminal ioctl to measure one. (Theme detection does ask whether the stream is a tty via PHP's stream_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

cli-page

Examples

  • examples/cli-page.php — one page wiring together every presenter: Banner, Section, Stage, StatusLine and HelpText. It is exactly what the cli-page demo above records.
  • examples/logo.php — the Logo wordmark 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.