Skip to content

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.

  1. Command-line flags
  2. Environment variables
  3. Configuration file
  4. 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 to stderr.
  • Add a --json flag or structured output mode when scripts consume the output.
  • Respect the NO_COLOR environment variable. Disable ANSI color codes when NO_COLOR is set and not empty, or when stdout is not a terminal (std::io::IsTerminal).
  • Return standard exit codes: 0 for success, 1 for runtime errors, and 2 for 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::Frame from the model.
  • Update: An event loop reads crossterm::event::Event values 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::Command with explicit argument arrays.

Refer to Secure development lifecycle for threat models and input validation rules.

Testing CLI and TUI code

  • Use assert_cmd or env!("CARGO_BIN_EXE_<name>") in tests/ to check flags, exit codes, stdout, and stderr. Refer to Integration and CLI tests.
  • Use insta to save snapshots of help text, JSON output, and rendered terminal frames.
  • Use ratatui::backend::TestBackend to 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_64 and aarch64 targets on Linux, macOS, and Windows. Tools such as cargo-dist generate GitHub Actions workflows, shell installers, PowerShell installers, and Homebrew formulas.
  • Include generated shell completions and man pages 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 with cargo-binstall.

Further reading