Skip to main content

Crate tinsel

Crate tinsel 

Source
Expand description

Clean terminal output for Rust CLIs, with a little sparkle.

use tinsel::prelude::*;

let live = Live::new("deploy", "my-app → production");
let build = live.step("Build package");
let upload = live.step("Upload bundle");

build.start();
build.detail("bundling 412 files");
build.done();

upload.start();
upload.progress(0.5, "17 / 34 MB");
upload.done();

live.finish_with_card(Card::success("deployed").kv("url", "https://my-app.example.com"));

§What’s here

live workLive step lists with sub-steps, parallel steps and Live::log; a Region redrawing any block; commands run as steps (Step::run, Step::command) and Step::retry; a Live::timeline of where the time went; spin / try_spin around one task; a standalone Progress bar or ProgressIterator around any loop, drawn as a line or a BarStyle::Waveform; seven Spinners
messagessuccess, info, warn, error, hint, counter, title, rule, callout, Report
dataTable (sorting, borders, wrapping, footers), Tree, pairs, columns
chartssparkline, bars, meter, histogram, heatmap, bar, waveform
codediff, Code excerpts with syntax colouring (Lang, whose Lang::highlight colours one line) and carets under the problem
documentsmarkdown (and markdown::wrapped to a width), json, Help (with an entrance), and Block::page for anything long
inlinebadge, link, Card, paint, paint_on, paint_bg, bold and friends, Line for text built up in colours
colourpalette, Rgb, mix; style for gradients, blinking and the rest; anim for the shimmer, twinkle and moving bars tinsel animates with, and anim::Glide and anim::Glider for values that ease into place
appsapp: full-screen dashboards and tools, with app::Panels, app::Lists, app::ScrollViews, app::Tabs, app::Plots, app::Stats, app::Loading, app::Scrollbars and app::big text laid out in app::Rects, drawn only when something changes or a frame asks; app::Job for work on another thread; app::snapshot to test them
command lineCli reads flags, options, arguments and subcommands into Args, draws --help from the same description, and reports mistakes with what was probably meant
questionsprompt: confirm, input (validation, suggestions, path completion), password, number, date, select and multiselect (filter as you type, headings, disabled options), a dropdown for long lists, editor, confirm by typing; .back() to go back a question, and prompt::Form to ask several as one
helperstext (width-aware pad, truncate from either end, wrap, widths with tabs, fuzzy matching and highlighting what matched) and format (bytes, durations, ago, thousands marked off, the local time of day); clipboard to copy and paste; terminal_width
setupinstall_panic_hook, set_output for --json and --quiet, set_target to draw on stderr, set_accent, set_theme, set_color_mode, set_fps, set_focus, set_history and set_ctrl_c, timings, doctor

§How the pieces fit

  • One-liners print. success, warn and the rest print straight away. Use a Tone when you want the line as a string instead.
  • Everything bigger is a Block. Tables, trees, cards, callouts, diffs: you can .print() them, println!("{}") them, or call .plain() for unstyled text.
  • Builders for anything with options. Table, Tree, Card, Report and Code are built up with chained methods, so call sites read like what they draw.
  • Questions return a prompt::Result, whose prompt::Error tells cancelling apart from having no terminal.

§Output for programs, and quiet output

set_output switches everything at once: Output::Json turns every message, step, report and block into one JSON object per line, for tools reading your output, and Output::Quiet keeps only what needs attention (warnings, errors, failures and anything printed explicitly). TINSEL_OUTPUT=json or quiet does the same from outside.

§Colour, terminals and tests

tinsel draws in truecolor when COLORTERM says the terminal supports it, in the 16 basic colours when TERM names one without 256color (or FORCE_COLOR=1), and otherwise in 256 colours. It respects NO_COLOR, and when stdout isn’t a terminal (CI, a pipe, a log file) it drops colour and animation and writes plain lines like [ok] Build (1.2s).

Everything is drawn on stdout unless set_target (or TINSEL_TARGET=stderr) moves it to stderr, for tools whose stdout carries something else; then it’s stderr that has to be a terminal.

Animations draw 60 frames a second. set_fps (or TINSEL_FPS) changes that for the whole program, and a display can choose its own: Live::fps, Progress::fps, App::fps. A full-screen app is drawn only when something happens or a frame asks for another, so it rests while nothing moves.

set_color_mode overrides all of that, for a --color flag or to get predictable text in tests:

tinsel::set_color_mode(tinsel::ColorMode::None);
let table = tinsel::Table::new(["app", "size"]).row(["core", "34 MB"]);
assert_eq!(table.lines().plain().lines().last(), Some("  core   34 MB"));

Live::headless gives you a display on a clock you move yourself, so you can check exactly what a run looks like at each point with Live::snapshot.

To test your own program’s output, capture returns everything a closure prints through tinsel, as it would come out into a pipe, and with_color_mode picks a colour mode for one closure on one thread, so a test that checks colour codes doesn’t change them for the tests running beside it. with_theme, with_accent, with_output and with_target do the same for the rest of the settings, so a library can scope them too without touching the program’s.

The environment variables tinsel reads (TINSEL_OUTPUT, TINSEL_TARGET, TINSEL_THEME, TINSEL_ACCENT, TINSEL_FPS) ignore case and surrounding spaces.

Re-exports§

pub use highlight::Lang;
pub use markdown::markdown;
pub use style::Accent;
pub use style::ColorMode;
pub use style::Line;
pub use style::Rgb;
pub use style::Theme;
pub use style::bold;
pub use style::color_mode;
pub use style::dim;
pub use style::italic;
pub use style::mix;
pub use style::paint;
pub use style::paint_bg;
pub use style::paint_on;
pub use style::palette;
pub use style::set_accent;
pub use style::set_color_mode;
pub use style::set_theme;
pub use style::theme;
pub use style::underline;
pub use style::with_accent;
pub use style::with_color_mode;
pub use style::with_theme;

Modules§

anim
The pieces tinsel animates with, for drawing your own: a light passing over a label, the twinkle a finished step shows, and bars still on the move. Each takes the seconds since the animation started, so it can be drawn at any moment, as often as you like.
app
Full-screen terminal apps: dashboards, pickers, little toys, in the same pink as everything else.
clipboard
The system clipboard: copying text to it and pasting from it, by whatever this computer offers.
format
Numbers and times the way people say them.
highlight
Just enough syntax colouring for code excerpts: keywords, strings, numbers, comments, and keys in config files. One line at a time, so a string or comment that spans lines is only coloured on its first.
markdown
Markdown drawn for the terminal, in tinsel’s colours: for changelogs, long help text and what’s-new notes. markdown wraps it to the terminal, and wrapped to a width of your own.
prelude
The things most CLIs reach for, in one import: use tinsel::prelude::*;
prompt
Questions: yes/no, a line of text, a password, a number, a date, one of a list, several of a list, or a longer answer in the user’s editor.
style
Colour and type: the palette, painting text, gradients, and how colour is chosen (the terminal’s colour support, a light or dark theme, an accent). The everyday parts are at the crate root too: paint, bold, palette, Rgb and friends.
text
Measuring and shaping text by what the terminal shows, not by bytes or chars: escape codes count for nothing, CJK and emoji count for two columns, and a character with the marks, variation selectors and joiners that build on it counts as one.

Structs§

Args
The arguments a program was given, from Cli::parse. Flags, options and arguments are looked up by name: a flag or option by its long or short name (quiet, --quiet or q), an argument by the name in its spec (app for <APP>).
Block
Several lines of output that travel together.
Card
A rounded box with a thin border, for summing up a run: a headline, then details.
Cli
A program’s command line: its flags, options, arguments and subcommands, described once. parse reads the arguments the program was started with, and the same description draws --help as a Help.
CliError
Why the arguments couldn’t be read, or that someone asked for --help or --version. exit prints whichever it is and exits the way programs do.
Code
Source lines with numbers in a gutter, and optionally one line marked, with a caret under the part that matters: the shape compilers use for errors.
Help
A program’s help: name, what it does, usage, then groups of commands, options and examples, all aligned and wrapped to the terminal.
JsonError
Why json couldn’t read its input, and where.
Label
Text for a card’s border, from a &str, a String or a Line. Plain text takes the border’s usual style; a Line keeps its own.
Live
A list of steps redrawn in place as they run.
Progress
A single progress line with rate and time left, for work that isn’t part of a crate::Live list.
Region
Any Block (a table, a tree, a few lines of status) redrawn in place at a steady rate while work goes on, for displays a Live step list doesn’t fit. The view is a closure that builds the block afresh each time from whatever state it shares.
Report
An error, what caused it (outermost first), and a hint at the fix.
RunError
Why a command run as a step didn’t succeed. Shows as cargo exited with status 101.
Step
A handle to one step of a Live display. Cheap to clone and safe to move to other threads.
StepCommand
A command to run as a Step, from Step::command: set a timeout, retries or what it reads, then run it.
Table
Rows under a header, columns sized to their widest cell. Columns of numbers right-align on their own; cells can be styled (badges, coloured text) and still line up.
Tree
A hierarchy drawn with thin guides. Branches are brighter than leaves.
WithProgress
An iterator with a progress line: see ProgressIterator.

Enums§

Align
Which side of a column cells hug.
BarStyle
How a progress bar is drawn, for Live::bar and Progress::bar.
Border
How a Table is framed.
Callout
The tone of a callout block, which sets its colour.
CliErrorKind
What Cli::try_parse_from ran into.
CtrlC
What Ctrl-C does while tinsel draws something live: a spinner, progress bar, steps, a Region or the help pager. Set with set_ctrl_c.
Output
What shape tinsel’s output takes. Set it from a --json or --quiet flag with set_output, or with TINSEL_OUTPUT=json|quiet.
RunErrorKind
What went wrong running a command, from RunError::kind.
Spinner
How a step looks while it’s running. Every style keeps to the pink palette and eases its brightness rather than snapping, so none of them feel mechanical.
Target
Where tinsel draws: stdout (the default) or stderr. Choose stderr when stdout belongs to something else, like the output of a command your tool runs or data piped to another program. Set it with set_target or TINSEL_TARGET=stderr.
Tone
The kind of a one-line message. The free functions (success, info, …) print straight away; use a Tone when you want the line as a string instead.

Traits§

ProgressIterator
.progress("label") on any iterator: a Progress line that counts items as they go by and finishes when the iterator runs out. Iterators that know their length get a bar.

Functions§

badge
A small pill: live on a soft tint of the colour, with the colour as its text.
bar
A thin line that fills berry → blush, its leading cell fading in as it fills so the line grows smoothly and never breaks.
bars
A horizontal bar per label, scaled to the largest value, with the value at the end. A value that isn’t a number gets an empty bar and –, and an infinite one a full bar.
callout
A block set off by a coloured bar on the left, with a title and a body wrapped to fit.
capture
What f prints through tinsel, instead of printing it: for testing your own program’s output, not just tinsel’s pieces. Messages, steps, spinners, printed blocks and errors are all caught, stdout and stderr together, in the order they were printed.
columns
Items laid out in as many columns as fit, filling down then across, like ls.
counter
Prints 2/5 Building, for scripts that announce steps as they go rather than drawing a live list.
diff
A line diff between two texts: removed lines in red, added in sage, unchanged dim.
doctor
What tinsel decided about the terminal it’s drawing on, and why: the colour mode, theme, size, output shape, target, accent, frame rate, focus, history and notifications, each with what decided it (stdout isn't a terminal, COLORFGBG=15;0, set in code). Then a warning for each setting in the environment it can’t use: a misspelt TINSEL_ name, or a value it doesn’t understand, which would otherwise be ignored without a word.
error
Prints ✕ msg to stderr: something went wrong.
fps
The frames a second animations draw at, as set_fps describes.
heatmap
A grid of values as shaded cells, darkest for the smallest: activity by day, load by hour. Each row is a label and its values; all rows share one scale. A value that isn’t a finite number leaves its cell empty.
hint
Prints → msg, quieter than the rest: what to do next.
histogram
How values are spread: bins columns, height rows tall, with the range underneath. Values that aren’t finite numbers are left out.
info
Prints › msg: something worth knowing.
install_panic_hook
Show panics as a tinsel Report instead of Rust’s default message, and put the terminal back first if a Live display or a Region was mid-draw: running steps are marked as interrupted, the last frame is left on screen, and the cursor comes back. That’s for a panic that ends the program (one on the main thread, or any with panic = "abort"); one on another thread, which the program may well survive, is reported above the displays and they carry on.
json
JSON text indented and coloured: keys in blush, strings in sage, numbers in amber, true/false/null in rose. Short arrays of plain values stay on one line. Key order and the exact text of strings and numbers are kept.
link
A clickable link in terminals that support them (OSC 8); just the label elsewhere.
meter
A labelled gauge that warms from rose to amber to red as it fills: disk, memory, quotas. A value that isn’t a number, or a max that isn’t a finite number above zero, leaves it empty, with – for the percentage.
notify
Send a desktop notification. tinsel’s Live does this for you when a long run finishes while you’re looking at another window; call it yourself for anything else.
output
The output shape in use. Decided once from TINSEL_OUTPUT, unless set_output has chosen one.
pairs
Keys in a muted column as wide as the longest, values beside them.
rule
A thin divider across the content width, with an optional label in it.
set_ctrl_c
Choose what Ctrl-C does while tinsel draws something live. Call it early in main.
set_focus
Turn focus awareness on or off for every Live display: calmer animation while you’re in another window, a notification when a long run finishes unseen, and a twinkle for what finished when you come back. Reading focus reports means reading stdin while a display runs, so turn it off in tests, or in a tool that hands stdin to something else. Without this, setting TINSEL_NO_FOCUS to anything but an empty value turns it off. Live::no_focus turns it off for one display.
set_fps
Set how many frames a second every animation draws: spinners, progress bars, Live displays and full-screen apps. 60 unless set, or TINSEL_FPS set; one display can still choose its own (Live::fps, Progress::fps, App::fps). Animations are timed by the clock, so this changes how smooth they look, not how fast they go. Kept between 1 and 240.
set_history
Turn remembered step timings on or off for every Live display: with it off, nothing is read from or written to the cache, and steps show no estimates. Without this, setting TINSEL_NO_HISTORY to anything but an empty value turns it off. Live::no_history turns it off for one display.
set_output
Choose the output shape, for a --json or --quiet flag.
set_target
Send everything tinsel draws to stdout or stderr: Live displays, Regions, spinners and Progress bars, messages, printed Blocks and JSON events. Whether to draw in colour and animate is then decided by whether that stream is a terminal. Errors and Reports go to stderr either way, and prompts still ask on the terminal.
sparkline
Values as a row of rising blocks, taller ones brighter: ▁▂▄▇▅▃. A value that isn’t a finite number (NaN, for a reading that’s missing) leaves a gap.
spin
Run f with a spinner beside label, then leave a ● label line with the time it took on the right, lined up with Live steps.
success
Prints ● msg: something finished.
target
Where tinsel draws. Decided once from TINSEL_TARGET (stderr or stdout), unless set_target has chosen.
terminal_width
Columns in the terminal tinsel draws on (stdout, or the Target), falling back to $COLUMNS, then 80. For the width of a piece of text, see text::width.
timings
What Live displays have learned about how long steps take, as a table per program: recent runs as a sparkline, the usual time, the last run, and whether it was unusually slow or fast. Pass a name given to Live::remember_as (or a program’s own name), or None for every program with history.
title
Prints a heading with an optional quieter subtitle beside it, with a blank line either side.
try_spin
Like spin, but an Err ends on ✕ with the error under it.
warn
Prints ▲ msg: something to look at.
waveform
Progress as an audio waveform: played columns in berry → blush, the rest dim.
with_output
Run f with an output shape on this thread alone, leaving the rest of the program as it was: for a library that wants quiet output from one call, or a test that wants JSON without turning it on for the tests beside it. Displays started inside keep the shape they started with; anything drawn on other threads meanwhile uses the program’s.
with_target
Run f drawing on target on this thread alone, as with_output does for the output shape: messages and blocks printed inside go there, and the colour mode follows that stream. Displays that draw from a thread of their own (Live, Region, spinners and Progress bars) draw where the program is set to, so set that with set_target for them.