6 releases
0.3.0 | Mar 21, 2020 |
---|---|
0.2.3 | Mar 14, 2020 |
0.2.0 | Feb 29, 2020 |
0.1.0 | Feb 26, 2020 |
#989 in Command-line interface
28KB
285 lines
medusa
General template for building command line interface (CLI) using (and written in) Rust
Running the example
- Run the example without arguments
cargo run --example simple
- Run the example with arguments
cargo run --example simple -- --echo "hello universe"
- Run the example with stateful arguments
cargo run --example stateful -- --echo "hello universe" --twice
How to use
- Add crates dependencies in your
Cargo.toml
...
[dependencies]
medusa = "0.3.0"
...
- Import the library
...
use medusa::{ArgType, CommandLine, Handler, Variant};
...
- Create example function as your CLI option handler
...
fn hello(handler: &Handler) {
println!("Hello, world!");
}
fn echo(handler: &Handler, payload: String) {
println!("payload : {}", payload);
}
fn print_twice(handler: &Handler) {
if let Some(argtype) = handler.get_arg("--echo") {
if let ArgType::Content(payload) = argtype {
println!("printed once more : {}", payload);
}
}
}
...
- Create your handler and add some actions
...
let mut handler: Handler = Handler::new();
handler.add(
String::from("--hello"),
Variant::Plain(hello),
String::from("Print hello world for testing purpose.")
);
handler.add(
String::from("--echo"),
Variant::WithArg(echo),
String::from("Print string passed to this parameter to output.")
);
handler.add(
String::from("--twice"),
Variant::Plain(print_twice),
String::from("Print again the payload \"--echo\" have."),
);
...
- Register your handler into CLI command
...
use std::env;
let mut command: CommandLine = CommandLine::new();
command.set_handler(handler);
command.set_name("mycli");
command.set_version("1.0.0");
command.run(env::args());
...
- Test your Rust code if it's really works
cargo run -- --hello
cargo run -- --echo something
cargo run -- --echo greatstring --twice
- Compile your code
cargo build