-
Notifications
You must be signed in to change notification settings - Fork 16
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add slug, help, and version opts to binary
Adds some really basic cmdline argument parsing to the binary, supporting help text, version display, and printing of a slug rather than a full CUID.
- Loading branch information
1 parent
59a38b5
commit b93b5b3
Showing
1 changed file
with
53 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,13 +1,63 @@ | ||
use cuid::cuid; | ||
use std::process::exit; | ||
use cuid::{cuid, slug}; | ||
use std::{ | ||
env::{self, Args}, | ||
process::exit, | ||
}; | ||
|
||
/// Generate a new CUID and print it to stdout | ||
pub fn main() { | ||
match cuid() { | ||
let args: CuidArgs = env::args().into(); | ||
|
||
let res = if args.slug { slug() } else { cuid() }; | ||
|
||
match res { | ||
Ok(id) => println!("{}", id), | ||
Err(err) => { | ||
eprintln!("{:?}", err); | ||
exit(1) | ||
} | ||
} | ||
} | ||
|
||
const HELP: &'static str = r#"Usage: cuid [OPTION]... | ||
Generate and print a CUID. | ||
Options: | ||
--slug generate a slug instead of a full CUID | ||
-h, --help display this help and exit | ||
-v, --version display version information and exit"#; | ||
|
||
const VERSION: &'static str = env!("CARGO_PKG_VERSION"); | ||
|
||
/// Commandline arguments for the CUID binary | ||
#[derive(Debug)] | ||
struct CuidArgs { | ||
/// Whether to produce a slug instead of a CUID | ||
slug: bool, | ||
} | ||
impl From<Args> for CuidArgs { | ||
fn from(args: Args) -> Self { | ||
let mut slug = false; | ||
|
||
// The first argument should be the binary name. Skip it. | ||
args.skip(1).for_each(|arg| match arg.as_str() { | ||
"-h" | "--help" => { | ||
println!("{}", HELP); | ||
exit(0); | ||
} | ||
"-v" | "--version" => { | ||
println!("{}", VERSION); | ||
exit(0); | ||
} | ||
"--slug" => slug = true, | ||
_ => { | ||
println!("error: unrecognized argument {}", arg); | ||
println!(""); | ||
println!("{}", HELP); | ||
exit(1); | ||
} | ||
}); | ||
|
||
CuidArgs { slug } | ||
} | ||
} |