Crates.io | grab |
lib.rs | grab |
version | 0.3.1 |
source | src |
created_at | 2021-02-25 22:37:22.671999 |
updated_at | 2021-03-19 12:37:52.413645 |
description | Easily grab user input to your CLI |
homepage | |
repository | https://github.com/bazaah/grab-rs |
max_upload_size | |
id | 360730 |
size | 58,586 |
A library for effortlessly grabbing input users provide to your CLI. Whether from files, stdin or just plain text on the command line, we've got you covered.
Add it to your Cargo.toml dependencies
# Cargo.toml
[dependencies]
grab = "0.3"
Import and use it
use grab::{ /* ... */ }
The main type exposed by this library is grab::Input
. An instance of Input
can
be created via grab::Config::parse
which takes a &str
as input and attempts to
parse it into a known Input
source.
Currently, known sources are:
&str
) passed in as inputThe default Config
uration recognizes -
for stdin per the unix tradition, and
takes cues from curl -d
by recognizing @<file path>
as a file.
This means that you can easily support all three of the most common input sources
with a single type. For example, assume we had a simple CLI tool named hello
that prints out a hello to the user...
use structopt::StructOpt;
use grab::Input;
// We use the popular StructOpt library for our CLI skeleton
#[derive(StructOpt)]
struct HelloCLI {
// Note we use Input instead of the typical String or Vec<u8>
/// The name we're going to greet
name: Input
}
fn main() -> Result<()> {
// Parse our argument(s)
let args = HelloCLI::from_args();
// Access the user's input, reading it to a string
let name = args.name.access()?.read_to_string()?;
// Say hello!
println!("Hello, {}!", &name);
Ok(())
}
Now we can support all three of the following invocations with absolutely zero extra code:
$ hello John
Hello, John!
$ echo Bob | hello -
Hello, Bob!
$ print Fred >name.txt ; hello @name.txt
Hello, Fred!