diff options
author | Robin Krahl <robin.krahl@ireas.org> | 2018-12-18 00:39:24 +0100 |
---|---|---|
committer | Daniel Mueller <deso@posteo.net> | 2018-12-23 12:04:57 -0800 |
commit | 048c97adcedab552e8c5b33567a06de4cb5c0f81 (patch) | |
tree | 8271dde240632509260c074dd3ae9554b3dda442 /nitrocli/src/main.rs | |
parent | 32126d545532971302c0a8d512b5a8ec8226ed33 (diff) | |
download | nitrocli-048c97adcedab552e8c5b33567a06de4cb5c0f81.tar.gz nitrocli-048c97adcedab552e8c5b33567a06de4cb5c0f81.tar.bz2 |
Port argument handling to argparse
This patch replaces the macro for argument parsing with
`argparse::ArgumentParser` from the argparse crate. It moves the
application logic to the `commands` module and the argument parsing to
the `options` module. An enum is used to represent the available
commands. The code is based on the `subcommands.rs` example shipped
with argparse.
Diffstat (limited to 'nitrocli/src/main.rs')
-rw-r--r-- | nitrocli/src/main.rs | 47 |
1 files changed, 16 insertions, 31 deletions
diff --git a/nitrocli/src/main.rs b/nitrocli/src/main.rs index 86e9188..8a20494 100644 --- a/nitrocli/src/main.rs +++ b/nitrocli/src/main.rs @@ -68,6 +68,7 @@ //! Nitrocli is a program providing a command line interface to certain //! commands of the Nitrokey Storage device. +mod args; mod commands; mod error; mod pinentry; @@ -75,43 +76,27 @@ mod pinentry; use std::process; use std::result; -use nitrokey; - use crate::error::Error; type Result<T> = result::Result<T, Error>; -// A macro for generating a match of the different supported commands. -// Each supplied command is converted into a string and matched against. -macro_rules! commands { - ( $str:expr, [ $( $command:expr), *] ) => { - match &*$str.to_string() { - $( - stringify!($command) => { - if let Err(err) = $command() { - println!("{}", err); - return 1 - } - return 0 - }, - )* - x => { - println!("Invalid command: {}", x); - println!("Available commands: {}", stringify!( $($command)* )); - return 1 - }, - } - } -} - fn run() -> i32 { - let argv: Vec<String> = std::env::args().collect(); - if argv.len() != 2 { - println!("Usage: {} <command>", argv[0]); - return 1; + let args = std::env::args().collect(); + match args::handle_arguments(args) { + Ok(()) => 0, + Err(err) => match err { + Error::ArgparseError(err) => match err { + // argparse printed the help message + 0 => 0, + // argparse printed an error message + _ => 1, + }, + _ => { + println!("{}", err); + 1 + } + }, } - - commands!(&argv[1], [commands::status, commands::open, commands::close, commands::clear]); } fn main() { |