From 048c97adcedab552e8c5b33567a06de4cb5c0f81 Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Tue, 18 Dec 2018 00:39:24 +0100 Subject: 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. --- nitrocli/src/main.rs | 47 ++++++++++++++++------------------------------- 1 file changed, 16 insertions(+), 31 deletions(-) (limited to 'nitrocli/src/main.rs') 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 = result::Result; -// 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 = std::env::args().collect(); - if argv.len() != 2 { - println!("Usage: {} ", 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() { -- cgit v1.2.1