CLI and TUI Applications
Command-line interface (CLI) and terminal user interface (TUI) programs give users fast, scriptable tools that operate in a terminal. Configure argument parsing, output streams, terminal state recovery, tests, and release packages before you publish a binary.
Crate stack
Select pure-Rust crates that operate on Linux, macOS, and Windows.
| Purpose | Crate | Notes |
|---|---|---|
| Argument parser | clap |
Use the derive feature for typed flags and subcommands. |
| Shell completions | clap_complete |
Generate completion scripts for Bash, Zsh, Fish, and PowerShell. |
| Manual pages | clap_mangen |
Generate man pages from the clap command definition. |
| TUI layout | ratatui |
Render terminal widgets with an immediate-mode frame loop. |
| Terminal backend | crossterm |
Control raw mode, the alternate screen, and keyboard events across operating systems. |
| Diagnostics | miette or thiserror |
Use thiserror for library errors and miette for rich user diagnostics. |
| ANSI styles | anstyle |
Add terminal colors without a heavy dependency tree. |
Keep the core logic in src/lib.rs and keep only the entry point in src/main.rs.
Refer to Binary and library targets.
Argument parsing and configuration
Define arguments with clap derive macros. Enable the env feature so users can
set options with environment variables.
use clap::Parser;use std::path::PathBuf;
#[derive(Debug, Parser)]#[command(version, about = "Inspect project manifests")]pub struct Cli { /// Path to the configuration file. #[arg(short, long, env = "MY_TOOL_CONFIG")] pub config: Option<PathBuf>,
/// Write output as JSON. #[arg(long)] pub json: bool,}Use this order of priority for configuration values.
- Command-line flags
- Environment variables
- Configuration file
- Default values
Refer to Configuration priority for tests of each pair of sources.
Output streams, colors, and exit codes
Follow the Command Line Interface Guidelines so scripts and human users can both use the tool reliably.
- Write primary data to
stdout. Write diagnostics, progress messages, and errors tostderr. - Add a
--jsonflag or structured output mode when scripts consume the output. - Respect the
NO_COLORenvironment variable. Disable ANSI color codes whenNO_COLORis set and not empty, or whenstdoutis not a terminal (std::io::IsTerminal). - Return standard exit codes:
0for success,1for runtime errors, and2for command-line usage errors. - Do not panic on malformed files, invalid UTF-8, or broken pipes. Return a clear error message and a non-zero exit code.
TUI architecture and terminal recovery
Separate application state from rendering in a TUI. Use a Model-View-Update structure:
- Model: A struct holds the application state, selection indices, and data buffers.
- View: A pure function draws widgets onto a
ratatui::Framefrom the model. - Update: An event loop reads
crossterm::event::Eventvalues and updates the model.
If a TUI stops or panics while raw mode is active, the user terminal can stay in an unusable state. Always restore the terminal on normal exit and on panic.
ratatui::run initializes the terminal, installs a panic hook that restores the
terminal, and cleans up on exit.
use ratatui::DefaultTerminal;use std::io;
fn main() -> io::Result<()> { ratatui::run(app)}
fn app(terminal: &mut DefaultTerminal) -> io::Result<()> { loop { terminal.draw(|frame| { // Render widgets here. })?; // Read events with crossterm::event::poll and break on quit. break; } Ok(())}If the TUI reads network data or large files, move that work to a background
thread or a tokio task. Send updates to the render loop through a bounded
channel so the interface stays responsive.
Security considerations
- Do not pass secrets such as API tokens as command-line arguments. Other local
users can inspect command-line arguments in the process table. Read secrets from
environment variables, files with restricted permissions, or
stdin. - Validate file paths before you write or extract archives to prevent path traversal.
- Do not pass untrusted input to a shell command. Use
std::process::Commandwith explicit argument arrays.
Refer to Secure development lifecycle for threat models and input validation rules.
Testing CLI and TUI code
- Use
assert_cmdorenv!("CARGO_BIN_EXE_<name>")intests/to check flags, exit codes,stdout, andstderr. Refer to Integration and CLI tests. - Use
instato save snapshots of help text, JSON output, and rendered terminal frames. - Use
ratatui::backend::TestBackendto render TUI screens into an in-memory buffer during unit tests. Assert on the buffer text without a real terminal.
#[cfg(test)]mod tests { use ratatui::{backend::TestBackend, Terminal};
#[test] fn renders_title_bar() { let backend = TestBackend::new(40, 10); let mut terminal = Terminal::new(backend).expect("create test terminal"); terminal .draw(|frame| { frame.render_widget(ratatui::widgets::Paragraph::new("Status: OK"), frame.area()); }) .expect("draw frame");
let buffer = terminal.backend().buffer(); let line: String = (0..10).map(|x| buffer[(x, 0)].symbol()).collect(); assert_eq!(line, "Status: OK"); }}Packaging and distribution
- Build precompiled archives for
x86_64andaarch64targets on Linux, macOS, and Windows. Tools such ascargo-distgenerate GitHub Actions workflows, shell installers, PowerShell installers, and Homebrew formulas. - Include generated shell completions and
manpages in each release archive. - Publish SHA-256 checksums, build provenance attestations, and a software bill of materials (SBOM) with each release. Refer to Release automation.
- Configure
[package.metadata.binstall]if users install the binary withcargo-binstall.