Console
- Introduction
- Writing commands
- Registering commands
- Writing output
- Prompting for input
- Showing progress
- Handling signals
- Background work
- Testing commands
- Troubleshooting commands
Introduction
Not every task in your application begins with an HTTP request. You may need to import a CSV file nightly, prune stale drafts, or repair data in production. Console commands handle these tasks directly from your application's binary, with full access to your configuration, services, and models.
Running your application binary with no command starts the HTTP server. Passing a command name executes that command instead. While you develop, run commands through the dust-framework CLI, which compiles your application and then runs the command you name. It shows the compiler's output only when the build fails:
dust serve # serve the applicationdust route:list # run a commanddust list # list every commanddust help route:list # show a command's helpIn production, you run the binary you built with the same arguments, such as ./app migrate --force.
Every command boots your application and executes inside an application context, so config, resolve, URL helpers, and your log channels work as they do in HTTP handlers. Because there is no incoming HTTP request, session and request helpers are not available.
Writing commands
Beyond the built-in commands, you can write your own. New applications place each command in its own file under src/console/. Define a command by annotating an async function with #[command] and its name. Its parameters define the command's input, parsed into typed values by clap. For example, this command publishes a draft post:
use dust::console::{Console, command};use dust::model::update;use crate::models::Post;/// Publish a draft post.#[command("posts:publish")]pub async fn publish_post( /// The ID of the post to publish. id: i64, /// Publish the post again if it's already published. #[arg(long)] force: bool, console: &mut Console,) -> dust::Result<()> { let mut post = Post::find_or_fail(id).await?; if post.published_at.is_some() && !force { console.info(format!("Post `{id}` is already published.")); return Ok(()); } update!(post { published_at: dust::now() }).await?; console.success(format!("Post `{id}` published.")); Ok(())}The function's doc comment becomes the description shown in list and --help, and each argument's doc comment documents that argument. dust-framework discovers command functions automatically, so you can run the command immediately:
dust posts:publish 42 --forcedust posts:publish --helpIn addition to CLI arguments, a command may accept &mut Console for output and prompts, services via Inject<T>, config sections via Section<T>, and &Application, in any order. These injected parameters are excluded from command-line parsing. For example, the included inspire command takes Inject<Inspiring> to retrieve its quotes.
Arguments and options
A plain parameter like id above defines a positional argument. #[arg(..)] supports any of clap's argument attributes, including long for named options, short for single-letter flags, and default_value_t for default values. This version of posts:publish accepts multiple IDs and a --min-votes option:
use dust::console::{Console, command};/// Publish draft posts.#[command("posts:publish")]pub async fn publish_posts( /// The IDs of the posts to publish. #[arg(required = true)] ids: Vec<i64>, /// Publish posts that are already published again. #[arg(short, long)] force: bool, /// Publish only the posts with at least this many votes. #[arg(long, value_name = "VOTES", default_value_t = 0)] min_votes: i64, console: &mut Console,) -> dust::Result<()> { // ... Ok(())}Clap converts snake-case parameter names into kebab-case flags:
dust posts:publish 3 7 12 -f --min-votes=10Each parameter's Rust type determines how clap parses it:
| Type | Command-line behavior |
|---|---|
i64, String, PathBuf, and other parsed types |
Required value. |
Option<T> |
Optional value. |
bool with #[arg(long)] |
Boolean switch, such as --force. |
Vec<T> |
Repeated value, such as --tag rust --tag dust. |
Enum deriving clap::ValueEnum with #[arg(value_enum)] |
One of the enum's variants, listed in --help. |
Struct deriving clap::Args with #[command(flatten)] |
Shared group of options reused across commands. |
Command-level attributes, such as aliases, follow the command name. Any of clap's command attributes are supported:
#[command("posts:publish", visible_alias = "publish")]To derive clap traits, import clap from dust::console rather than adding a separate clap dependency to your Cargo.toml.
Exit status
A command returning () or Ok(()) exits with status 0. To return a specific exit code, return u8 or dust::Result<u8>. For example, this command exits with status 1 if the post is already published:
use dust::console::{Console, command};use dust::model::update;use crate::models::Post;/// Publish a draft post.#[command("posts:publish")]pub async fn publish_post(id: i64, console: &mut Console) -> dust::Result<u8> { let mut post = Post::find_or_fail(id).await?; if post.published_at.is_some() { console.error(format!("Post `{id}` is already published.")); return Ok(1); } update!(post { published_at: dust::now() }).await?; Ok(0)}If a command returns Err or panics, dust-framework prints the error to stderr, reports it through your error handler, and exits with status 1. In the example above, find_or_fail returns an error when the post does not exist, so propagating it with ? handles missing records cleanly.
Command structs
If you prefer organizing a command's input in a struct, derive clap::Parser on the struct and place #[dust::console::command] on the impl block containing its handle method. The struct's fields define the CLI arguments, and handle accepts the same injected parameters as a command function:
use dust::console::{Console, clap};use dust::model::update;use crate::models::Post;/// Publish a draft post.#[derive(clap::Parser)]#[command(name = "posts:publish")]pub struct PublishPost { /// The ID of the post to publish. id: i64,}#[dust::console::command]impl PublishPost { async fn handle(self, console: &mut Console) -> dust::Result<()> { let mut post = Post::find_or_fail(self.id).await?; update!(post { published_at: dust::now() }).await?; console.success(format!("Post `{}` published.", self.id)); Ok(()) }}Unlike command functions, command structs must be registered explicitly.
Registering commands
dust-framework automatically discovers and registers every #[command] function in your application's app crate, regardless of which module it lives in, as long as the module is declared with mod.
Register command structs in src/app.rs using commands.add:
Application::configure() .with_commands(|commands, _config| { commands.add::<PublishPost>(); })Registering a command with the same name replaces the previous definition, allowing your application to override package or framework commands. Packages register their commands through their service provider.
To run console commands on a recurring schedule, configure them in the task scheduler.
Writing output
Commands write status messages and primary output to separate streams so piped output stays clean. Status messages go to stderr with colored markers:
console.info("Importing users...");console.warn("Skipping a duplicate.");console.error("Could not read users.csv.");console.step("Installing dependencies...");console.success("Imported.");Primary output goes to stdout. Use line to print a plain line and new_line to print a blank line:
console.line("Import complete.");console.new_line();console.line("Next steps...");table also writes to stdout and wraps cells to fit the terminal width. Pass a header array and rows of matching length:
let users = User::all().await?;console.table( ["Name", "Email"], users.iter().map(|user| [&user.name, &user.email]),);To display a titled message block on stderr, such as post-install instructions, use note:
console.note("Next steps", "Review your configuration, then run the import.");Styled text
To style parts of a line, use markup. Tags accept fg, bg, and options separated by semicolons, and </> closes the tag:
use dust::console::escape_markup;console.markup( "<fg=black;bg=cyan> Notice </> <fg=emerald-400;options=bold>Ready</>",);let name = console.ask("What is your name?").await?;console.markup(format!( "<fg=sky-400>Hello, {}.</>", escape_markup(&name),));Colors accept ANSI names such as red, Tailwind CSS colors such as emerald-400, or hex codes such as #ff8800. Always wrap untrusted or user-supplied text with escape_markup so < characters are not parsed as tags.
Quiet and verbose output
Every command supports the global --quiet (-q) and --verbose (-v) flags. Repeat -v up to three times to increase detail:
dust users:import -vdust users:import -vvvdust users:import --quietWrite verbosity-gated messages using verbose, very_verbose, and debug. Each line prints only when the user passes that verbosity level or higher:
console.info("Importing users...");console.verbose("Reading users.csv");console.very_verbose("Checking each user record");console.debug("Using the CSV importer");| Flag | Output shown |
|---|---|
-q, --quiet |
console.error and command failures only. |
| None | Standard messages, output, and progress displays. |
-v |
Adds verbose lines. |
-vv |
Adds very_verbose lines. |
-vvv |
Adds debug lines. |
When computing diagnostic output is expensive, check the verbosity level before doing the work:
if console.is_verbose() { let count = User::query().count().await?; console.verbose(format!("{count} users before the import"));}Use is_very_verbose, is_debug, and is_quiet to check the other levels.
Prompting for input
When a command needs interactive input from the person running it, such as the name and email of a new user, use ask for text, password for hidden input, and confirm for yes-or-no questions:
use dust::console::{Console, command};use dust::model::create;use crate::models::User;/// Create a user.#[command("user:create")]pub async fn create_user(console: &mut Console) -> dust::Result<()> { let name = console.ask("What is the user's name?").required(true).await?; let email = console.ask("What is their email address?").required(true).await?; let password = console.password("Choose a password").required(true).await?; if !console.confirm("Create the user?").default(true).await? { return Ok(()); } create!(User { name: &name, email: &email, password: &password, }) .await?; console.success("User created."); Ok(())}ask and password return a String, while confirm returns a bool. You may provide a default that the user can accept by pressing Enter:
let queue = console.ask("Which queue?").default("default").await?;If the user presses Ctrl+C during a prompt, dust-framework returns PromptError::Cancelled. Propagating it with ? exits the command with status 130 without reporting an error.
Validating answers
Passing .required(true) rejects empty answers. For custom validation rules, attach a validate closure that returns an error message when the input is invalid:
let email = console .ask("What is their email address?") .placeholder("you@example.com") .required(true) .validate(|email: &String| { if email.contains('@') { Ok(()) } else { Err("Enter an email address.") } }) .await?;let password = console .password("Choose a password") .required(true) .validate(|password: &String| { if password.len() >= 8 { Ok(()) } else { Err("Use at least eight characters.") } }) .await?;In an interactive terminal, validation errors re-prompt the user until they provide a valid answer. Because validate is synchronous, load any data it needs (such as existing emails) before displaying the prompt. placeholder renders dimmed hint text in an empty input without setting a default value.
Menus
Use choice to present a single-select menu navigated with arrow keys, and multiselect to allow toggling multiple options with the space bar. When given string options, choice returns a String and multiselect returns a Vec<String>:
let queue = console .choice("Which queue?", ["default", "high"]) .default("default") .await?;let roles = console .multiselect("Which roles?", ["admin", "editor", "viewer"]) .default(["editor"]) .await?;Defaults match an option's value rather than its index. Chain .searchable() on either menu to let users filter options by typing, and .required(true) on multiselect to require at least one selection.
When you want an option's display label to differ from its returned value, pass Choice items. Each Choice can also include a hint and preserves your value's Rust type, such as an enum:
use dust::console::Choice;#[derive(Clone, Debug, PartialEq, Eq)]enum Environment { Production, Staging,}let environment = console .choice( "Which environment?", [ Choice::new(Environment::Production, "Production") .hint("Live customer traffic"), Choice::new(Environment::Staging, "Staging") .hint("Testing environment"), ], ) .default(Environment::Staging) .await?;Defaults, validation callbacks, and scripted test answers all operate on the underlying choice values rather than their display labels.
Autocomplete and multiline answers
ask can suggest completions as the user types, using either a static list or a closure that receives the current input:
let language = console .ask("Which language?") .autocomplete(["Rust", "Go", "TypeScript"]) .await?;let emails = User::query().pluck(User::email).await?;let email = console .ask("Which user?") .autocomplete(move |input: &str| { emails .iter() .filter(|email| email.starts_with(input)) .cloned() .collect() }) .await?;Autocomplete suggestions do not restrict what the user may enter, so add .validate(..) if the input must match a known option. Keep autocomplete closures fast since they run on every keystroke.
For longer responses, chain .multiline(). Pressing Enter inserts a newline; pressing Escape previews the text and Enter submits it:
let description = console.ask("Describe your project").multiline().await?;Running unattended
When a deploy script or cron job runs your command, nobody is present to answer interactive prompts. Pass --no-interaction (-n) to automatically answer every prompt with its default value. dust-framework also enters non-interactive mode automatically when stdin is not attached to a terminal. Every prompt (including confirmations) must define a .default(..) in non-interactive mode, or the command fails with PromptError::NonInteractive.
Because --quiet does not disable prompts on its own, pass both flags for fully unattended runs:
dust user:create --quiet --no-interactionShowing progress
When a command processes thousands of records, displaying a progress bar shows how far along the work is. Use a progress bar when you know the total number of items, or a spinner when the total is unknown. For example, this command deletes unpublished drafts while advancing a progress bar:
use dust::console::{Console, command};use crate::models::Post;/// Delete every unpublished draft.#[command("posts:prune")]pub async fn prune_drafts(console: &mut Console) -> dust::Result<()> { let drafts = Post::query() .filter(Post::published_at.is_null()) .get() .await?; let mut progress = console.progress(drafts.len() as u64, "Deleting drafts...")?; for draft in drafts { draft.delete().await?; progress.advance(1); } progress.finish("Drafts deleted.")?; Ok(())}A spinner follows the same lifecycle without a total count:
let spinner = console.spinner("Loading users...")?;let users = User::all().await?;spinner.finish("Users loaded.")?;Call message to update the display's label and hint to render dimmed text underneath it. End any progress bar or spinner with finish, cancel, or fail. These methods only update the visual display; return an exit code or error from your command to control its exit status.
Because a progress display holds a mutable borrow of Console until finished, complete any interactive prompts before starting one.
Processing collections
progress_each iterates over a collection, runs an async closure for each item, and advances the progress bar automatically, returning the collected outputs in order. Here is posts:prune written with progress_each:
let drafts = Post::query() .filter(Post::published_at.is_null()) .get() .await?;console .progress_each("Deleting drafts", drafts, async |draft, mut progress| { progress.message(format!("Deleting {}", draft.title)); draft.delete().await }) .await?;The collection must have a known length (such as a Vec, array, or range). If any iteration returns an error, progress_each stops immediately and returns that error.
Running work with a spinner
Use spin to show a spinner while an async closure executes and return its output:
let users = console .spin("Loading users...", async || User::all().await) .await?;If the closure returns an error, the spinner marks itself as failed and spin propagates the error.
To render multiple progress bars and spinners together under a shared heading, use progress_group.
Handling signals
The operating system sends your command a signal when someone presses Ctrl+C or when a process manager sends SIGTERM. By default, the command terminates immediately. To finish the current unit of work before exiting, call console.trap_shutdown and check is_requested at a safe checkpoint. For example, this command deletes drafts in pages and stops after finishing the current page:
use dust::console::{Console, command};use dust::stream::TryStreamExt;use crate::models::Post;/// Delete every unpublished draft.#[command("posts:prune")]pub async fn prune_drafts(console: &mut Console) -> dust::Result<u8> { let shutdown = console.trap_shutdown()?; let mut pages = Post::query() .filter(Post::published_at.is_null()) .chunk_by_id(100); while let Some(drafts) = pages.try_next().await? { for draft in drafts { draft.delete().await?; } if shutdown.is_requested() { console.info("Stopped. Run the command again to delete the rest."); return Ok(130); } } Ok(0)}trap_shutdown traps Ctrl+C (Signal::Interrupt) on all platforms and SIGTERM (Signal::Terminate) on Unix. Trapping a signal does not exit the command or change its exit status. Returning Ok(130) when interrupted follows the standard shell convention for Ctrl+C so calling scripts know the work did not finish.
The Shutdown handle returned by trap_shutdown is Clone and provides wait, so you can race an async operation against shutdown using task::select!:
use dust::task;task::select! { result = sync_feeds() => result?, _ = shutdown.wait() => { console.info("Shutting down..."); }}To handle other signals, such as Signal::Hangup to reload configuration on Unix, register a callback with console.trap. Signal callbacks execute on the command's task while it awaits, so keep them brief and handle cleanup in your main loop:
use std::sync::Arc;use std::sync::atomic::{AtomicBool, Ordering};use dust::console::Signal;let reload = Arc::new(AtomicBool::new(false));let flag = Arc::clone(&reload);console.trap(Signal::Hangup, move |_| { flag.store(true, Ordering::Relaxed);})?;Signal::Interrupt handles Ctrl+C on all platforms. On Unix, you may also trap Terminate, Hangup, Quit, User1, and User2.
Long-running commands
Commands such as serve, queue:work, or a custom feed poller run indefinitely until stopped. By default, dust-framework wraps each command in a command span for its entire lifetime. On a command that never exits, that span stays open forever and groups all work into a single unfinished trace. Add long_running to the attribute so the command runs without an enclosing span:
use dust::console::command;use dust::prelude::*;use dust::task;use crate::feeds;/// Fetch new posts from every feed until stopped.#[command("feeds:watch", long_running)]pub async fn watch_feeds() -> dust::Result<()> { loop { feeds::refresh().await?; task::sleep(5.minutes()).await; }}For a command struct, write #[dust::console::command(long_running)] on the impl block.
If a long-running command keeps state in memory that needs periodic upkeep, such as counters you flush to the database, you may enable your application's ticks for that command by adding with_ticks (for example, #[command("feeds:watch", long_running, with_ticks)]). Inside those ticks, the process host is Host::Command("feeds:watch"), and any tick marked with run_on_shutdown runs one final time when the command exits.
Background work
Console commands and scheduled callbacks can start background work with task::background or event::dispatch_background, like HTTP handlers do. When the command returns, dust-framework waits for in-flight background work to finish before exiting. For example, this command announces a post to a webhook in the background:
use dust::console::{Console, command};use dust::http::client;use dust::task;use serde_json::json;use crate::models::Post;/// Announce a published post to the newsletter service.#[command("posts:announce")]pub async fn announce_post(id: i64, console: &mut Console) -> dust::Result<()> { let post = Post::find_or_fail(id).await?; let title = post.title.clone(); task::background(async move { client::post("https://example.com/webhooks/announcements") .json(json!({ "post_id": post.id, "title": post.title })) .ensure_successful() .await?; Ok(()) })?; console.success(format!("Announcing `{title}`.")); Ok(())}dust-framework waits up to SERVER_SHUTDOWN_TIMEOUT (20 seconds by default), and Ctrl+C or SIGTERM cuts the wait short. Background task failures are sent to your error handler without changing the command's exit status.
Testing commands
To test a command, pass the command string (the part after dust) to app.command:
use dust::model::create;use dust::testing::prelude::*;use app::models::{Post, User};#[dust::test]async fn it_publishes_a_post(app: Application) -> dust::Result<()> { let user = create!(User { name: "Taylor", email: "taylor@example.com", password: "password", }) .await?; let post = create!(Post { title: "My first post", user: &user, }) .await?; app.command(&format!("posts:publish {}", post.id)) .await .assert_successful() .assert_error_output_contains("published."); Ok(())}The command executes in the test's process, and the returned assertion helper captures stdout and stderr separately. line and table output go to stdout (assert_output_contains), while status messages, notes, and progress go to stderr (assert_error_output_contains). Use assert_output_missing, assert_error_output_missing, and assert_no_output to check absent output, and assert_exit_code or assert_failed to verify exit codes.
app.command splits the string using shell-like quoting without invoking a shell. To pass exact argument strings directly, use app.command_args(["posts:publish", "42", "--force"]).
To test interactive prompts, script the answers in the order the command asks them before awaiting:
#[dust::test]async fn it_creates_a_user(app: Application) { app.command("user:create") .expects_question("What is the user's name?", "Taylor") .expects_question("What is their email address?", "taylor@example.com") .expects_password("Choose a password", "secret-password") .expects_confirmation("Create the user?", true) .await .assert_successful();}Use expects_choice and expects_multiselect for menus, passing the underlying choice values such as Environment::Staging. Once you script any answer, you must script every prompt the command asks; the test fails on an unused expectation, an unexpected prompt, or an answer rejected by validation. Without scripted answers, each prompt uses its default.
To test signal traps, send a simulated signal with sends_signal:
use dust::console::Signal;app.command("posts:prune") .sends_signal(Signal::Interrupt) .await .assert_successful();Tests do not wait for a command's background work.
[!WARNING] Commands execute their real side effects in tests. For example, running
key:generatewithout--showmodifies.envin your working directory.servecannot run inside a test; test your routes with HTTP tests instead.
Troubleshooting commands
| Symptom | What to check |
|---|---|
The command doesn't appear in dust list |
The function is #[command] and its module is declared; a command struct is added with with_commands. |
dust: run this inside an application |
Run it from the application's directory or any directory inside it. |
| The command parses the wrong arguments | The injected parameters (&mut Console, Inject<T>, Section<T>, &Application) are excluded from parsing; a plain parameter is positional. |
| An option needs a value but takes none | bool is a switch with #[arg(long)]; use Option<T> or a String for a value. |
| A prompt fails in CI | Pass --no-interaction and give every prompt a .default(..), or pass --quiet --no-interaction. |
| The progress bar disappears | End it with finish, cancel, or fail before the command returns. |
| A command hangs after returning | It waits for background work up to SERVER_SHUTDOWN_TIMEOUT; a task that never finishes holds the process. |
Exit code is 130 |
Ctrl+C or a cancelled prompt; that is the shell convention for an interrupted command, not an error. |
In a test, a command that fails prints its error to stderr. Use assert_error_output_contains to see it, or run the command through cargo run -- <command> to watch it directly.