use std::env;
use std::path::Path;
use std::process;
use std::result;
use getopts;
pub struct Arguments {
pub configuration_path: String,
}
pub type Result<T> = result::Result<T, Error>;
#[derive(Debug)]
pub enum Error {
ParseError(getopts::Fail),
}
impl Arguments {
pub fn parse() -> Result<Arguments> {
let arguments: Vec<String> = env::args().collect();
let program = arguments[0].clone();
let mut options = getopts::Options::new();
options.optopt("c", "config", "path of the configuration file", "PATH");
options.optflag("h", "help", "print help");
let matches = try!(options.parse(&arguments[1..]));
if matches.opt_present("h") {
print_usage(&program, options);
process::exit(1);
}
let default_configuration_path = format!("{}.conf.toml",
Path::new(&program)
.file_stem()
.unwrap()
.to_str()
.unwrap());
let configuration_path = if matches.opt_present("c") {
matches.opt_default("c", &default_configuration_path).unwrap()
} else {
default_configuration_path
};
Ok(Arguments { configuration_path: configuration_path })
}
}
impl From<getopts::Fail> for Error {
fn from(error: getopts::Fail) -> Self {
Error::ParseError(error)
}
}
fn print_usage(program: &str, options: getopts::Options) {
let brief = format!("Usage: {} FILE [options]", program);
print!("{}", options.usage(&brief));
}