Skip to content

Commit b93b5b3

Browse files
committed
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.
1 parent 59a38b5 commit b93b5b3

File tree

1 file changed

+53
-3
lines changed

1 file changed

+53
-3
lines changed

src/bin.rs

Lines changed: 53 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,63 @@
1-
use cuid::cuid;
2-
use std::process::exit;
1+
use cuid::{cuid, slug};
2+
use std::{
3+
env::{self, Args},
4+
process::exit,
5+
};
36

47
/// Generate a new CUID and print it to stdout
58
pub fn main() {
6-
match cuid() {
9+
let args: CuidArgs = env::args().into();
10+
11+
let res = if args.slug { slug() } else { cuid() };
12+
13+
match res {
714
Ok(id) => println!("{}", id),
815
Err(err) => {
916
eprintln!("{:?}", err);
1017
exit(1)
1118
}
1219
}
1320
}
21+
22+
const HELP: &'static str = r#"Usage: cuid [OPTION]...
23+
Generate and print a CUID.
24+
25+
Options:
26+
--slug generate a slug instead of a full CUID
27+
-h, --help display this help and exit
28+
-v, --version display version information and exit"#;
29+
30+
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
31+
32+
/// Commandline arguments for the CUID binary
33+
#[derive(Debug)]
34+
struct CuidArgs {
35+
/// Whether to produce a slug instead of a CUID
36+
slug: bool,
37+
}
38+
impl From<Args> for CuidArgs {
39+
fn from(args: Args) -> Self {
40+
let mut slug = false;
41+
42+
// The first argument should be the binary name. Skip it.
43+
args.skip(1).for_each(|arg| match arg.as_str() {
44+
"-h" | "--help" => {
45+
println!("{}", HELP);
46+
exit(0);
47+
}
48+
"-v" | "--version" => {
49+
println!("{}", VERSION);
50+
exit(0);
51+
}
52+
"--slug" => slug = true,
53+
_ => {
54+
println!("error: unrecognized argument {}", arg);
55+
println!("");
56+
println!("{}", HELP);
57+
exit(1);
58+
}
59+
});
60+
61+
CuidArgs { slug }
62+
}
63+
}

0 commit comments

Comments
 (0)