improve command line parser

This commit is contained in:
Dietmar Maurer 2018-11-30 12:10:26 +01:00
parent d42398666c
commit 73f29c34d7
2 changed files with 38 additions and 11 deletions

View File

@ -45,7 +45,7 @@ fn parse_argument(arg: &str) -> RawArgument {
pub fn parse_arguments(
args: &Vec<String>,
arg_param: &Vec<String>,
arg_param: &Vec<&'static str>,
schema: &ObjectSchema,
) -> Result<(Value,Vec<String>), ParameterError> {
@ -133,7 +133,7 @@ pub fn parse_arguments(
for i in 0..arg_param.len() {
if rest.len() > i {
data.push((arg_param[i].clone(), rest[i].clone()));
data.push((arg_param[i].to_string(), rest[i].clone()));
} else {
errors.push(format_err!("missing argument '{}'", arg_param[i]));
}

View File

@ -16,25 +16,52 @@ use futures::future::Future;
use hyper;
fn main() {
println!("Proxmox REST Server example.");
let prop : Arc<Schema> = StringSchema::new("This is a test").into();
let command : Arc<Schema> = StringSchema::new("Command.")
.format(Arc::new(ApiStringFormat::Enum(vec![
"start".into(),
"status".into(),
"stop".into()
])))
.into();
//let prop = Arc::new(ApiString!{ optional => true });
let schema = ObjectSchema::new("Parameters.")
.required("name1", prop.clone())
.required("name2", prop.clone());
.required("command", command);
let args: Vec<String> = std::env::args().skip(1).collect();
match getopts::parse_arguments(&args, &vec![], &schema) {
let options = match getopts::parse_arguments(&args, &vec!["command"], &schema) {
Ok((options, rest)) => {
println!("Got Options: {}", options);
println!("Remaining Arguments: {:?}", rest);
if !rest.is_empty() {
eprintln!("Error: got additional arguments: {:?}", rest);
std::process::exit(-1);
}
options
}
Err(err) => {
eprintln!("Unable to parse arguments:\n{}", err);
eprintln!("Error: unable to parse arguments:\n{}", err);
std::process::exit(-1);
}
};
let command = options["command"].as_str().unwrap();
match command {
"start" => {
println!("Starting server.");
},
"stop" => {
println!("Stopping server.");
std::process::exit(0);
},
"status" => {
println!("Server status.");
std::process::exit(0);
},
_ => {
eprintln!("got unexpected command {}", command);
std::process::exit(-1);
},
}
let addr = ([127, 0, 0, 1], 8007).into();