Build a Full‑Featured Rust CLI with interactcli‑rs in Four Simple Steps
This article walks you through the fundamentals of creating a robust command‑line interface in Rust using the interactcli‑rs scaffold and the clap library, covering project setup, directory layout, command definition, registration, parsing, and interactive prompt customization.
Learning a programming language is similar to learning a human language: start with keywords, basic syntax, and standard libraries, then practice by building simple applications that communicate with a machine.
To avoid overwhelming beginners, begin with the simplest possible command‑line interface (CLI) program, which is essentially a "hello world" application.
CLI programs often need to handle two types of interaction: the classic shell‑style one‑command‑per‑execution model (well supported by Rust's clap crate) and domain‑specific interactive sessions (e.g., MySQL or Redis clients) that require custom handling.
The interactcli‑rs scaffold provides a ready‑made framework for building interactive CLIs with common features.
Quick Start
Clone the project and run the example:
git clone https://github.com/jiashiwen/interactcli-rs.git
cd interactcli-rsRun a simple request sample in command mode: cargo run requestsample baidu Enter interactive mode:
cargo run -- -i
interact-rs> requestsample baiduThe command sends an HTTP request to Baidu.
Four Steps to a Complete CLI
1. Project Structure
.
├── examples
├── log
├── logs
└── src
├── cmd
├── commons
├── configure
├── interact
├── logger
└── requestThe cmd directory holds the command implementations.
2. Define Commands
use clap::Command;
pub fn new_requestsample_cmd() -> Command<'static> {
clap::Command::new("requestsample")
.about("requestsample")
.subcommand(get_baidu_cmd())
}
pub fn get_baidu_cmd() -> Command<'static> {
clap::Command::new("baidu")
.about("request www.baidu.com")
}The new_requestsample_cmd creates the requestsample command and its baidu sub‑command.
3. Register Commands
lazy_static! {
static ref CLIAPP: clap::Command<'static> = clap::Command::new("interact-rs")
.version("1.0")
.author("Your Name. <[email protected]>")
.about("command line sample")
.arg_required_else_help(true)
.arg(Arg::new("config").short('c').long("config").value_name("FILE").help("Sets a custom config file").takes_value(true))
.arg(Arg::new("daemon").short('d').long("daemon").help("run as daemon"))
.arg(Arg::new("interact").short('i').long("interact").conflicts_with("daemon").help("run as interact mod"))
.arg(Arg::new("v").short('v').multiple_occurrences(true).takes_value(true).help("Sets the level of verbosity"))
.subcommand(new_requestsample_cmd())
.subcommand(new_config_cmd())
.subcommand(new_multi_cmd())
.subcommand(new_task_cmd())
.subcommand(new_loop_cmd())
.subcommand(clap::Command::new("test")
.about("controls testing features")
.version("1.3")
.author("Someone E. <[email protected]>")
.arg(Arg::new("debug").short('d').help("print debug information verbosely")));
}
static ref SUBCMDS: Vec<SubCmd> = subcommands();The command tree is built at runtime, enabling automatic help and sub‑command discovery.
4. Parse Commands
fn cmd_match(matches: &ArgMatches) {
if let Some(ref matches) = matches.subcommand_matches("requestsample") {
if let Some(_) = matches.subcommand_matches("baidu") {
let rt = tokio::runtime::Runtime::new().unwrap();
let async_req = async {
let result = req::get_baidu().await;
println!("{:?}", result);
};
rt.block_on(async_req);
}
}
}The cmd_match function dispatches the appropriate logic based on the parsed sub‑commands.
To customize the interactive prompt, edit src/interact/cli.rs:
pub fn run() {
loop {
let p = format!("{}> ", "interact-rs");
rl.helper_mut().expect("No helper").colored_prompt = format!("\x1b[1;32m{}\x1b[0m", p);
// ... handle input ...
}
}This sets a green-colored prompt for the interactive mode.
The article concludes by promising a future post that will dive deeper into the various features implemented by interactcli‑rs.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
JD Cloud Developers
JD Cloud Developers (Developer of JD Technology) is a JD Technology Group platform offering technical sharing and communication for AI, cloud computing, IoT and related developers. It publishes JD product technical information, industry content, and tech event news. Embrace technology and partner with developers to envision the future.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
