From 74eb955687223219e96c62a778c34a4dc2d03562 Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Sun, 17 Feb 2019 13:34:44 +0000 Subject: Respect ctx.std{out,err} for version output Due to a bug in argparse [0], custom stdout and stderr settings are ignored when using argparse::Print, as we currently do for the --version option. This patch adds a workaround for this problem: Instead of using argparse::Print, we use argparse::StoreTrue for the --version option. The argument parsing will fail as the command is missing, but the version variable will still be set to true if the version option was set. So we ignore the parsing result and discard the argparse output if the version variable is set. [0] https://github.com/tailhook/rust-argparse/pull/50 --- nitrocli/src/args.rs | 52 +++++++++++++++++++++++++++++----------------------- 1 file changed, 29 insertions(+), 23 deletions(-) diff --git a/nitrocli/src/args.rs b/nitrocli/src/args.rs index 787ff65..8359557 100644 --- a/nitrocli/src/args.rs +++ b/nitrocli/src/args.rs @@ -859,6 +859,7 @@ fn parse_arguments<'io, 'ctx: 'io>( ctx: &'ctx mut RunCtx<'_>, args: Vec, ) -> Result<(Command, ExecCtx<'io>, Vec)> { + let mut version = false; let mut model: Option = None; let model_help = format!( "Select the device model to connect to ({})", @@ -869,9 +870,9 @@ fn parse_arguments<'io, 'ctx: 'io>( let cmd_help = cmd_help!(command); let mut subargs = vec![]; let mut parser = argparse::ArgumentParser::new(); - parser.add_option( + let _ = parser.refer(&mut version).add_option( &["-V", "--version"], - argparse::Print(format!("nitrocli {}", env!("CARGO_PKG_VERSION"))), + argparse::StoreTrue, "Print version information and exit", ); let _ = parser.refer(&mut verbosity).add_option( @@ -908,28 +909,33 @@ fn parse_arguments<'io, 'ctx: 'io>( }; let result = parse(&mut ctx_buf, parser, args); - use std::io::Write; - stdout_buf.flush()?; - stderr_buf.flush()?; - - match result { - Ok(()) => { - subargs.insert(0, format!("nitrocli {}", command)); - - let ctx = ExecCtx { - model, - stdout: ctx.stdout, - stderr: ctx.stderr, - admin_pin: ctx.admin_pin.take(), - user_pin: ctx.user_pin.take(), - new_admin_pin: ctx.new_admin_pin.take(), - new_user_pin: ctx.new_user_pin.take(), - password: ctx.password.take(), - verbosity, - }; - Ok((command, ctx, subargs)) + if version { + write!(ctx.stdout, "nitrocli {}", env!("CARGO_PKG_VERSION"))?; + Err(Error::ArgparseError(0)) + } else { + use std::io::Write; + stdout_buf.flush()?; + stderr_buf.flush()?; + + match result { + Ok(()) => { + subargs.insert(0, format!("nitrocli {}", command)); + + let ctx = ExecCtx { + model, + stdout: ctx.stdout, + stderr: ctx.stderr, + admin_pin: ctx.admin_pin.take(), + user_pin: ctx.user_pin.take(), + new_admin_pin: ctx.new_admin_pin.take(), + new_user_pin: ctx.new_user_pin.take(), + password: ctx.password.take(), + verbosity, + }; + Ok((command, ctx, subargs)) + } + Err(err) => Err(err), } - Err(err) => Err(err), } } -- cgit v1.2.1