Add help menu

This commit is contained in:
Kasper 2021-07-03 02:51:03 +02:00
parent cedc70af3a
commit 87c10619b5
2 changed files with 48 additions and 23 deletions

View File

@ -1,5 +1,6 @@
## Next
- Add support for non-US "metre" and "litre" spellings
- Add help menu
- Add `--version` flag
- Freak out instead of ignoring unexpected arguments
- Fix decimeter parsed as centimeter

View File

@ -1,23 +1,48 @@
use cpc::eval;
use cpc::units::Unit;
use std::process::exit;
use std::env;
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
fn print_help() {
println!(concat!(
"Usage: cpc '<expression>' [options]",
"\n",
"\nOptions:",
"\n --verbose Enable verbose logging",
"\n --version Show cpc version",
"\n --help Show this help page",
));
}
fn get_args() -> env::Args {
let mut args = env::args().into_iter();
args.next(); // skip binary name
return args;
}
/// CLI interface
fn main() {
use std::env;
let mut args = env::args().into_iter();
args.next();
let mut verbose = false;
let mut expression_opt = None;
for arg in args {
// parse these first so they work if there are unexpected args
for arg in get_args() {
match arg.as_str() {
"-v" | "--verbose" => verbose = true,
"--version" => {
println!("{}", VERSION);
exit(0);
},
"--help" => {
print_help();
exit(0);
},
_ => {},
}
}
let mut verbose = false;
let mut expression_opt = None;
for arg in get_args() {
match arg.as_str() {
"-v" | "--verbose" => verbose = true,
_ => {
if expression_opt == None {
expression_opt = Some(arg);
@ -28,23 +53,22 @@ fn main() {
}
}
}
match expression_opt {
Some(expression) => {
match eval(&expression, true, Unit::Celsius, verbose) {
Ok(answer) => {
if !verbose {
println!("{}", answer);
}
},
Err(e) => {
eprintln!("{}", e);
exit(1);
},
}
}
let expression = match expression_opt {
Some(expression) => expression,
None => {
eprintln!("No argument supplied");
print_help();
exit(0);
},
};
match eval(&expression, true, Unit::Celsius, verbose) {
Ok(answer) => {
if !verbose {
println!("{}", answer);
}
},
Err(e) => {
eprintln!("{}", e);
exit(1);
}
},
}
}