- Rust 100%
- Shell <1%
tinsel #
Clean terminal output for Rust CLIs, with a little sparkle. Live step lists, spinners, tables, trees, prompts and error reports that all look like they belong together.
use tinsel::prelude::*;
let live = Live::new("deploy", "my-app โ production");
let build = live.step("Build");
let upload = live.step("Upload");
build.start();
build.done();
upload.start();
upload.progress(0.5, "6 / 12 MB");
upload.done();
live.finish_with_card(Card::success("deployed").kv("url", "https://my-app.example.com"));
deploy my-app โ production
โ Build 1.2s
โ Upload 1.7s
โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ โ deployed in 3.8s โ
โ โ
โ url https://my-app.example.com โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
Why tinsel? #
Most CLIs bolt together a spinner crate, a table crate, a prompt crate and a colour crate, and end up looking like four different programs. tinsel is one small library with one visual language: pink accents, quiet greys, eased animation, and a twinkle when something finishes.
- It learns: steps remember how long they took, so next run a spinner becomes a real estimate:
usually 42s ยท 18s left - It knows if you're watching: switch windows during a long run and you get a desktop notification when it ends; come back and whatever finished meanwhile twinkles
- It fits your terminal: detects light and dark backgrounds and redraws the palette to suit, or in another accent colour for your brand
- It speaks JSON too: one switch turns every step, message and error into JSON lines for tools, or quiets everything but problems
- Zero dependencies: nothing in your lockfile but tinsel
- One shape for everything: one-liners print; anything bigger is a
Blockyou can print, format, or test - Builders that read like the output:
Card::success("deployed").kv("url", โฆ) - Errors you can match on: prompts return
prompt::Error::Cancelled, not a mysteryio::Error - Behaves in CI: no colour or animation when piped,
NO_COLORrespected, plain[ok] Build (1.2s)lines in logs - Panics stay tidy: a panic mid-run leaves the last frame on screen and prints a proper report, not a scrambled terminal
- Testable:
set_color_mode(ColorMode::None)and.plain()give you exact text to assert on, andLive::headlessruns a display on a clock you control
Install #
cargo add tinsel
Quickstart #
One task with a spinner, then a message:
let files = tinsel::spin("Counting files", || count_files());
tinsel::success(&format!("found {files} files"));
A step list for anything with stages: see the example at the top. Steps can run at the same time from different threads, have sub-steps, and log lines above the display:
let build = live.step("Build");
let targets = [build.step("linux"), build.step("macos")]; // drawn indented, folded once they pass
build.start();
std::thread::scope(|s| {
for t in &targets {
s.spawn(move || { t.start(); compile(t); t.done(); });
}
});
build.done();
live.log("signed with Developer ID"); // printed above, kept on screen
Steps that don't run can say why: lint.skip("nothing changed"), upload.cancel("stopped by hand"), or release.wait("waiting for approval") until someone says go, then
release.start(). A failed step can start() again, and its timer starts over.
Progress bars can be a thin line (the default) or a waveform that lights up as it plays
through, like an audio track: Live::new(โฆ).bar(BarStyle::Waveform).
Run real commands as steps. The latest line of output shows as the step's detail; if it fails, its last lines stay under it:
use std::process::Command;
build.run(Command::new("cargo").args(["build", "--release"]))?;
push.command(Command::new("docker").args(["push", "my-app"]))
.timeout(Duration::from_secs(120))
.retries(2)
.run()?;
fetch.retry(3, || download(url))?; // any closure returning a Result
See where the time went, with live.finish_with_timeline():
Build โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 1.7s
linux โโโโโโโโโโโโโโโโโโโโโโโ 1.2s
macos โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 1.7s
Publish โโโโโโโโโโโโโ 0.7s
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
0s 2.9s
Anything else, redrawn in place: a Region calls your closure a few times a second and
draws the Block it returns, a table of services say, with lines logged above it. It's
cleared when it finishes, unless you keep() the last frame:
let region = tinsel::Region::new(move || status_table(&state.lock().unwrap())).keep();
region.log("api is up");
region.finish();
A loop with a progress bar:
use tinsel::ProgressIterator;
for file in files.iter().progress("Indexing") {
index(file);
}
Ask questions, and handle someone pressing Ctrl-C. Long lists filter as you type:
use tinsel::prompt;
match prompt::select("Deploy to", &["staging", "production"]) {
Ok(i) => deploy(i),
Err(prompt::Error::Cancelled) => std::process::exit(130),
Err(e) => tinsel::Report::from_error("couldn't ask", &e).eprint(),
}
Text questions can validate, and ask again until the answer passes:
let port = prompt::Input::new("Port")
.placeholder("8080")
.validate(|s| s.parse::<u16>().map(|_| ()).map_err(|_| "a port is 1-65535".into()))
.ask()?;
let replicas: u32 = prompt::number("Replicas", Some(3))?;
let live_on = prompt::date("Go live on", None)?; // a calendar
let notes = prompt::editor("Release notes", "## What's new\n")?; // opens $EDITOR
let region = prompt::Input::new("Region").suggestions(regions).ask()?; // Tab completes
let path = prompt::Input::new("Config").paths().ask()?; // like a shell
prompt::confirm_typing("Delete my-app?", "my-app")?; // type it to go on
Several questions can be asked as one Form: โ goes back to change an answer, and at the
end they're all shown, to change any of them before going on:
use tinsel::prompt::{Confirm, Form, Input, Select};
let answers = Form::new()
.question("name", Input::new("Project name").default("my-app"))
.question("target", Select::new("Deploy to").options(["staging", "production"]))
.question("tag", Confirm::new("Tag the release?").default(true))
.ask()?;
deploy(answers.text("name"), answers.choice("target"), answers.yes("tag"));
Lists can be grouped, and say why an option can't be picked:
let service = prompt::Select::new("Service")
.heading("Frontend").option("web").disabled("docs", "deploys paused")
.heading("Backend").options(["api", "worker"])
.back() // โ returns prompt::Error::Back
.ask()?;
let version = prompt::Dropdown::new("Roll back to")
.option("v1.2.0").note("3 days ago").badge("latest")
.option("v1.1.0").note("2 weeks ago")
.allow_custom() // or type a version that isn't listed
.ask()?;
Help that looks like the rest of your CLI, with a short entrance on a terminal: lines fade in one after another while the name shimmers:
tinsel::Help::new("deploy", "ship an app to the cloud")
.version(env!("CARGO_PKG_VERSION"))
.usage("deploy [OPTIONS] <APP>")
.command("status", "what's running where")
.flag("--region <NAME>", "where to deploy")
.example("deploy my-app --region us-east-1", "ship to the US east region")
.animate();
Read the command line from one description, which draws --help too. A mistake is a
report that says what was probably meant:
let cli = tinsel::Cli::new("deploy", "ship an app to the cloud")
.version(env!("CARGO_PKG_VERSION"))
.flag("-r, --region <NAME>", "where to deploy")
.flag("-q, --quiet", "only print problems")
.flag("-n, --replicas <N>", "how many to run")
.arg("<APP>", "what to ship")
.command(tinsel::Cli::new("status", "what's running where"));
let args = cli.parse(); // --help, --version and mistakes print and exit
let region = args.value("region").unwrap_or("eu-west-2");
let replicas: u32 = args.value_as("replicas").unwrap_or(1);
โ there's no --regon flag
โ did you mean --region?
It does what most programs need (flags, options, arguments, one level of subcommands, values parsed into types) and no more; for rules between flags or anything fancier, clap is the one to reach for.
Documents: tinsel::markdown(changelog).page() draws Markdown (headings, lists, tables,
code coloured by language) and pages it if it's long; tinsel::json(body)? indents and
colours JSON.
Show data:
use tinsel::{Border, Table, badge, palette};
Table::new(["service", "status", "p95"])
.row(["api".to_string(), badge(palette::SAGE, "healthy"), "84ms".into()])
.row(["auth".to_string(), badge(palette::AMBER, "slow"), "1.2s".into()])
.sort_by_desc(2) // by value: 1.2s before 84ms
.border(Border::Rounded)
.print();
Full-screen apps: dashboards, pickers, little toys. Write a struct, draw it in view,
change it in event; app::run takes over the screen and gives it back afterwards (even on
a panic). Panels shimmer when focused, lists scroll themselves, and numbers can be drawn big:
use tinsel::app::{self, App, Frame, Panel, Plot, Stat, Size::*};
struct Dash { latency: Vec<f64> }
impl App for Dash {
fn view(&self, frame: &mut Frame) {
let [stat, chart] = frame.area().columns_gap(1, [Fixed(20), Fill(1)]);
frame.render(stat, Panel::new("p95").body(Stat::new("latency", "84ms")));
frame.render(chart, Panel::new("latency").body(Plot::new(&self.latency)).focused(true));
}
}
app::run(Dash { latency: vec![84.0, 90.0, 120.0, 340.0, 95.0] })?; // q or Esc quits
Grid is a table with a cursor, for lists you move through: rows can sit under group
headings, a panel can say where its data came from on its top border, and tabs can carry
their own colour and a mark:
Whole programs fit too: tvim is a vim-like text editor built on tinsel's full-screen apps:
Anything tinsel draws (tables, trees, cards, any Block) goes straight into a panel, next to
List, Tabs, Plot, Stat, big text, hints and twinkling Sparkles.
app::snapshot(&app, 80, 24) draws a frame without a terminal, for tests, and
Frame::html() (or Block::html()) turns one into a web page that looks just like it, for
screenshots.
Report an error with its whole cause chain:
tinsel::Report::from_error("couldn't start", &err)
.hint("create app.toml, or pass --config <path>")
.eprint();
โ couldn't start
โฐโ couldn't read app.toml
โฐโ No such file or directory (os error 2)
โ create app.toml, or pass --config <path>
โฆand point at the problem:
Report::new("couldn't read app.toml")
.cause("port must be a number")
.code(Code::around(&config, 3, 1).path("app.toml").caret(8, 8, "not a number"))
.eprint();
โ couldn't read app.toml
โฐโ port must be a number
โญโ app.toml:3
2 โ host = "0.0.0.0"
3 โบ port = "eighty"
โ ^^^^^^^^ not a number
4 โ workers = 4
Panics, drawn the same way, with the terminal put back first:
fn main() {
tinsel::install_panic_hook();
// โฆ
}
For scripts and tools, one switch from a --json or --quiet flag:
tinsel::set_output(tinsel::Output::Json); // or TINSEL_OUTPUT=json
{"event":"step","title":"deploy","step":"Build","path":["Build"],"state":"done","secs":1.204}
{"event":"error","title":"couldn't start","causes":["couldn't read app.toml"],"code":[],"hint":"โฆ"}
When stdout isn't yours, because it carries a command's output or data for another program, draw on stderr instead:
tinsel::set_target(tinsel::Target::Stderr); // or TINSEL_TARGET=stderr
See it #
cargo run -- showcase # every component, then a live deploy
cargo run -- showcase table # one section
cargo run -- showcase --accent blue # in another accent; --theme light, --json and --quiet work too
cargo run -- demo --bar waveform # the deploy with waveform progress bars
cargo run -- help # the CLI's own help, with its entrance
cargo run -- prompts # the interactive questions
cargo run -- timings # what Live has learned about your step durations
The examples are small and meant to be copied. Run any of them with
cargo run --example <name>:
| example | what it shows |
|---|---|
hello |
the smallest useful program: a spinner around some work, then a message |
deploy |
a live step list that closes with a card; -- --fail to see a step fail |
parallel |
steps at the same time, with sub-steps, a log line and a panic hook; -- --json for the same run as JSON |
status |
a read-only status command: a table, details, a chart and a tree; pipe it to cat for plain text |
questions |
asking questions, and handling Ctrl-C partway through |
form |
questions asked as one form, going back and looking the answers over |
cli |
reading flags, arguments and subcommands, with --help from the same description; -- --help or -- stauts |
errors |
a Rust error turned into a report with its whole cause chain |
dashboard |
a live full-screen dashboard: stats, a service list, a chart that follows the selection, logs |
services |
services by group with a column per environment, a filter, dialogs and toasts |
What's in it #
| live work | Live step lists with sub-steps, parallel steps and log ยท skipped, cancelled and waiting steps ยท Region for any block ยท commands as steps with timeouts and retries ยท timeline ยท spin / try_spin ยท Progress with rate and time left, unknown or growing totals ยท .progress() on any iterator ยท bars as a line or a waveform ยท seven Spinners (sparkle twinkles, and is the default) |
| messages | success ยท info ยท warn ยท error ยท hint ยท counter ยท title ยท rule ยท callout ยท Report (with code excerpts) |
| data | Table (numbers right-align and sort by value, units and all; borders, wrapping, footers, highlighted rows) ยท Tree ยท pairs ยท columns |
| charts | sparkline ยท bars ยท meter ยท histogram ยท heatmap |
| code | diff ยท Code excerpts with syntax colouring (Rust, TOML, JSON, YAML, shell, Python, JS), a highlighted line and a caret under the problem |
| documents | markdown (and markdown::wrapped) ยท json ยท Help with an animated entrance ยท Block::page |
| inline | badge ยท link (clickable) ยท Card ยท paint, paint_on, paint_bg, bold, dim, italic, underline ยท style::gradient ยท anim for shimmering labels, moving bars and values that glide into place (Glide, Glider) |
| apps | app::run full-screen apps, drawn only when something changes or a frame asks (animate, animate_at, redraw_at) ยท Panel ยท List ยท Grid ยท ScrollView ยท TextInput (with a History and its own idea of a word) ยท TextArea ยท Scrollbar ยท Tabs ยท Plot ยท Stat ยท big ยท hints ยท Sparkles ยท Rect layout with rows / columns ยท keys with their modifiers, read and written in vim's notation (<C-a>) and shown as symbols (โA), mouse and resize events ยท Job for work on another thread ยท app::snapshot for tests ยท Frame::html for screenshots |
| command line | Cli for flags, options, arguments and subcommands ยท --help and --version for free ยท mistakes as a Report with "did you mean" ยท value_as for typed values |
| questions | prompt::confirm ยท input / Input (validation, placeholders, line editing) ยท password ยท number ยท date ยท select / Select ยท multiselect / MultiSelect (filter as you type, headings, disabled options with a reason, validation) ยท Dropdown for long lists (notes, badges, your own answer) ยท .back() to go back a question ยท Form to ask several, then look the answers over ยท editor ยท suggestions and path completion ยท confirm_typing |
| setup | install_panic_hook ยท set_output (Json, Quiet) ยท set_target (stderr) ยท set_focus ยท set_history ยท set_accent ยท set_theme ยท set_color_mode ยท set_fps ยท set_ctrl_c ยท timings |
| helpers | text::{width, width_with_tabs, pad, truncate, truncate_start, wrap, strip_ansi, content_width, fuzzy, highlight} ยท terminal_width ยท format::{bytes, duration, count, grouped, ago, ago_long, plural, local_clock} ยท clipboard::{copy, paste} (system tools, or OSC 52 over ssh) |
Full reference with examples for every item: docs.rs/tinsel.
Testing what you print #
Catch everything your own code prints through tinsel, as it would come out into a pipe: messages, steps, spinners, tables and errors, in order, without colour:
#[test]
fn deploy_says_where_it_went() {
let printed = tinsel::capture(|| my_cli::deploy("production"));
assert!(printed.contains("โ deployed to production"));
}
One piece on its own needs no capturing: .plain() gives any block's text.
#[test]
fn status_table() {
let table = tinsel::Table::new(["app", "size"]).row(["core", "34 MB"]);
assert_eq!(table.lines().plain().lines().last(), Some(" core 34 MB"));
}
For the colour codes themselves, tinsel::with_color_mode(ColorMode::TrueColor, || โฆ)
turns colour on for that closure, on that thread alone, so tests beside it aren't affected.
A Live display can run headless, on a clock that only moves when you say:
#[test]
fn deploy_shows_the_build_time() {
tinsel::set_color_mode(tinsel::ColorMode::None);
let live = tinsel::Live::headless("deploy", "my-app");
let build = live.step("Build");
build.start();
live.advance(std::time::Duration::from_millis(1200));
build.done();
assert!(live.snapshot().plain().ends_with("1.2s"));
}
Things it does on its own #
Estimates from history. Live steps remember their durations in ~/.cache/tinsel (or
$XDG_CACHE_HOME/tinsel), one small file per program. A step with no progress of its own
gets an estimate bar from its recent median, and says slower than usual when it is. Only
successful steps on a terminal are recorded. Live::remember_as("name") picks the file,
.no_history(), tinsel::set_history(false) or TINSEL_NO_HISTORY=1 (any value but an
empty one) turns it off. tinsel::timings(Some("my-app")) shows what's been learned, and
flags a step whose last run was unusually slow.
Focus. In terminals that report window focus (iTerm2, kitty, WezTerm, Ghostty,
Alacritty, foot, โฆ), animation slows while you're away, a run of 10s or more that finishes
while you're away sends a notification (.notify_after(โฆ), .no_notify()), and returning
re-twinkles what finished. Keys typed during a run are held back from the display and handed
to the shell afterwards. .no_focus(), tinsel::set_focus(false) or TINSEL_NO_FOCUS=1
turns all of this off, and leaves stdin alone. tinsel::notify sends a
notification yourself.
Tall displays. A Live display taller than the terminal leaves its top rows in
scrollback and keeps redrawing what fits, so long step lists don't scramble the screen.
Theme. Decided once from TINSEL_THEME=light|dark, then COLORFGBG, then by asking the
terminal for its background colour. Override with tinsel::set_theme.
Accent. Pink unless TINSEL_ACCENT (violet, blue, teal, orange, or a hue in
degrees) or tinsel::set_accent says otherwise. Every pink moves, including the faint tint
in the greys; red, amber and sage keep their meaning.
When it decides wrong, tinsel doctor says what it decided and why (colour off: stdout isn't a terminal, theme light: COLORFGBG=0;15) and warns about any setting it can't use,
like a misspelt TINSEL_THEMES or TINSEL_OUTPUT=jsn. tinsel::doctor() gives you the same
report, to print from a --debug-terminal flag of your own.
Platform notes #
Everything works on macOS, Linux and Windows. Ctrl-C puts the cursor and the terminal back everywhere.
- Raw mode on Unix shells out to
stty, to stay free of dependencies. Prompts,Keysand full-screen apps need it, so a minimal container without coreutils can't read single keypresses (everything that only draws still works). - Terminal size comes from
ioctlon macOS and Linux. Other Unixes, the BSDs among them, fall back to$COLUMNSand$LINES, then 80ร24. - Widths follow the Unicode 17 tables built into tinsel, so CJK, emoji and combining marks line up without a lookup at run time.
- Windows uses the console API for keys and size (Windows Terminal or a Windows 10+ console). Focus awareness and background detection need a terminal that answers, which there means Windows Terminal; the older console quietly goes without rather than wait for answers that never come.
- Colour is truecolor when
COLORTERMsays so, the 16 basic colours whenTERMnames a terminal without256color, and 256 colours otherwise.NO_COLOR,FORCE_COLORandCLICOLORare respected.
Stability #
tinsel follows semantic versioning from 1.0: nothing public changes
in a way that breaks your code without a new major version. Enums and structs that are
likely to grow are #[non_exhaustive], so a new key, colour mode or event can arrive in a
minor release; match them with a _ arm.
The minimum supported Rust version is 1.85. Raising it is a minor release, not a major one, and is said so in the changelog.
Contributing #
Issues and pull requests are welcome. tinsel is small on purpose: no dependencies, one visual language, and every component reads well as plain text too. CONTRIBUTING.md has the ground rules, the commands CI runs and how commits become the changelog.