Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://gitlab.com/tardi/medusa

General template for building command line interface (CLI) using (and written in) Rust
https://gitlab.com/tardi/medusa

binary cli command-line command-line-interface command-line-tool command-line-utilities crate executable libraty rust rust-crate rust-lang rust-library scratch

Last synced: 2 months ago
JSON representation

General template for building command line interface (CLI) using (and written in) Rust

Awesome Lists containing this project

README

        

# medusa

General template for building command line interface (CLI) using (and written in) Rust

## Running the example

- Run the example without arguments

```bash
cargo run --example simple
```

- Run the example with arguments

```bash
cargo run --example simple -- --echo "hello universe"
```

- Run the example with stateful arguments

```bash
cargo run --example stateful -- --echo "hello universe" --twice
```

## How to use

- Add crates dependencies in your `Cargo.toml`

```toml
...
[dependencies]
medusa = "0.3.0"
...
```

- Import the library

```rust
...
use medusa::{ArgType, CommandLine, Handler, Variant};
...
```

- Create example function as your CLI option handler

```rust
...
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

```rust
...
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

```rust
...
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

```bash
cargo run -- --hello
cargo run -- --echo something
cargo run -- --echo greatstring --twice
```

- Compile your code

```bash
cargo build
```