Skip to content

Commit

Permalink
feat: add slug, help, and version opts to binary
Browse files Browse the repository at this point in the history
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
mplanchard committed Oct 4, 2021
1 parent 59a38b5 commit b93b5b3
Showing 1 changed file with 53 additions and 3 deletions.
56 changes: 53 additions & 3 deletions src/bin.rs
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 }
}
}

0 comments on commit b93b5b3

Please sign in to comment.