From 1af4c0771034aa5d5f0a1f558dabc58c87fa3b19 Mon Sep 17 00:00:00 2001 From: Daniel Mueller Date: Fri, 4 Jan 2019 18:27:45 -0800 Subject: Introduce -v/--verbose option This change introduces a new option, -v/--verbose, that can be used to increase the log level of libnitrokey. The option can be supplied multiple times, with each occurrence increasing the verbosity of the logging. On the implementation side, the option is set as part of connecting the device (piggy-backing on the previously introduced command execution context), although it describes global state that strictly speaking could be set anywhere. It is bad enough that libnitrokey just prints log messages to stderr (and does not accept a file handle) and that it does not track the log level on a per-device basis, but we don't want setting of global state from arbitrary locations inside the program. Instead, let's do that along with what pretty much is the first call into libnitrokey anyway: the connection to the device. --- nitrocli/src/commands.rs | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) (limited to 'nitrocli/src/commands.rs') diff --git a/nitrocli/src/commands.rs b/nitrocli/src/commands.rs index aa99bd1..27faf05 100644 --- a/nitrocli/src/commands.rs +++ b/nitrocli/src/commands.rs @@ -38,13 +38,33 @@ fn get_error(msg: &str, err: nitrokey::CommandError) -> Error { Error::Error(format!("{}: {:?}", msg, err)) } +/// Set `libnitrokey`'s log level based on the execution context's verbosity. +fn set_log_level(ctx: &args::ExecCtx) { + let log_lvl = match ctx.verbosity { + // The error log level is what libnitrokey uses by default. As such, + // there is no harm in us setting that as well when the user did not + // ask for higher verbosity. + 0 => nitrokey::LogLevel::Error, + 1 => nitrokey::LogLevel::Warning, + 2 => nitrokey::LogLevel::Info, + 3 => nitrokey::LogLevel::DebugL1, + 4 => nitrokey::LogLevel::Debug, + _ => nitrokey::LogLevel::DebugL2, + }; + nitrokey::set_log_level(log_lvl); +} + /// Connect to any Nitrokey device and return it. -fn get_device(_ctx: &args::ExecCtx) -> Result { +fn get_device(ctx: &args::ExecCtx) -> Result { + set_log_level(ctx); + nitrokey::connect().map_err(|_| Error::Error("Nitrokey device not found".to_string())) } /// Connect to a Nitrokey Storage device and return it. -fn get_storage_device(_ctx: &args::ExecCtx) -> Result { +fn get_storage_device(ctx: &args::ExecCtx) -> Result { + set_log_level(ctx); + nitrokey::Storage::connect().or_else(|_| { Err(Error::Error( "Nitrokey Storage device not found".to_string(), -- cgit v1.2.1