more clippy fixups

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
This commit is contained in:
Wolfgang Bumiller 2019-12-05 12:28:05 +01:00
parent 65a284784b
commit ee1a7cd68b
10 changed files with 60 additions and 60 deletions

View File

@ -93,6 +93,7 @@ impl CliCommand {
} }
/// Define nested CLI commands. /// Define nested CLI commands.
#[derive(Default)]
pub struct CliCommandMap { pub struct CliCommandMap {
/// Each command has an unique name. The map associates names with /// Each command has an unique name. The map associates names with
/// command definitions. /// command definitions.
@ -102,9 +103,7 @@ pub struct CliCommandMap {
impl CliCommandMap { impl CliCommandMap {
/// Create a new instance. /// Create a new instance.
pub fn new() -> Self { pub fn new() -> Self {
Self { Default::default()
commands: HashMap::new(),
}
} }
/// Insert another command. /// Insert another command.

View File

@ -73,7 +73,7 @@ fn handle_nested_command(
def: &CliCommandMap, def: &CliCommandMap,
mut args: Vec<String>, mut args: Vec<String>,
) -> Result<(), Error> { ) -> Result<(), Error> {
if args.len() < 1 { if args.is_empty() {
let mut cmds: Vec<&String> = def.commands.keys().collect(); let mut cmds: Vec<&String> = def.commands.keys().collect();
cmds.sort(); cmds.sort();
@ -214,7 +214,7 @@ pub fn handle_command(
pub fn run_cli_command(def: CommandLineInterface) { pub fn run_cli_command(def: CommandLineInterface) {
let def = match def { let def = match def {
CommandLineInterface::Simple(cli_cmd) => CommandLineInterface::Simple(cli_cmd), CommandLineInterface::Simple(cli_cmd) => CommandLineInterface::Simple(cli_cmd),
CommandLineInterface::Nested(map) => CommandLineInterface::Nested(map.insert_help().into()), CommandLineInterface::Nested(map) => CommandLineInterface::Nested(map.insert_help()),
}; };
let mut args = std::env::args(); let mut args = std::env::args();
@ -244,7 +244,7 @@ pub fn run_cli_command(def: CommandLineInterface) {
} }
} }
if let Err(_) = handle_command(Arc::new(def), &prefix, args) { if handle_command(Arc::new(def), &prefix, args).is_err() {
std::process::exit(-1); std::process::exit(-1);
} }
} }

View File

@ -45,7 +45,7 @@ fn get_property_completion(
let mut completions = Vec::new(); let mut completions = Vec::new();
for value in list.iter() { for value in list.iter() {
if value.starts_with(arg) { if value.starts_with(arg) {
completions.push(value.to_string()); completions.push((*value).to_string());
} }
} }
return completions; return completions;
@ -58,13 +58,13 @@ fn get_property_completion(
lowercase_arg.make_ascii_lowercase(); lowercase_arg.make_ascii_lowercase();
for value in ["0", "1", "yes", "no", "true", "false", "on", "off"].iter() { for value in ["0", "1", "yes", "no", "true", "false", "on", "off"].iter() {
if value.starts_with(&lowercase_arg) { if value.starts_with(&lowercase_arg) {
completions.push(value.to_string()); completions.push((*value).to_string());
} }
} }
return completions; return completions;
} }
return Vec::new(); Vec::new()
} }
fn get_simple_completion( fn get_simple_completion(
@ -81,7 +81,9 @@ fn get_simple_completion(
if args.len() > 1 { if args.len() > 1 {
record_done_argument(done, cli_cmd.info.parameters, prop_name, &args[0]); record_done_argument(done, cli_cmd.info.parameters, prop_name, &args[0]);
return get_simple_completion(cli_cmd, done, &arg_param[1..], &args[1..]); return get_simple_completion(cli_cmd, done, &arg_param[1..], &args[1..]);
} else if args.len() == 1 { }
if args.len() == 1 {
record_done_argument(done, cli_cmd.info.parameters, prop_name, &args[0]); record_done_argument(done, cli_cmd.info.parameters, prop_name, &args[0]);
if let Some((_, schema)) = cli_cmd.info.parameters.lookup(prop_name) { if let Some((_, schema)) = cli_cmd.info.parameters.lookup(prop_name) {
return get_property_completion( return get_property_completion(
@ -93,6 +95,7 @@ fn get_simple_completion(
); );
} }
} }
return Vec::new(); return Vec::new();
} }
if args.is_empty() { if args.is_empty() {
@ -115,7 +118,7 @@ fn get_simple_completion(
let prefix = &args[args.len() - 1]; // match on last arg let prefix = &args[args.len() - 1]; // match on last arg
// complete option-name or option-value ? // complete option-name or option-value ?
if !prefix.starts_with("-") && args.len() > 1 { if !prefix.starts_with('-') && args.len() > 1 {
let last = &args[args.len() - 2]; let last = &args[args.len() - 2];
if last.starts_with("--") && last.len() > 2 { if last.starts_with("--") && last.len() > 2 {
let prop_name = &last[2..]; let prop_name = &last[2..];
@ -156,9 +159,7 @@ fn get_help_completion(
let mut done = HashMap::new(); let mut done = HashMap::new();
match def { match def {
CommandLineInterface::Simple(_) => { CommandLineInterface::Simple(_) => get_simple_completion(help_cmd, &mut done, &[], args),
return get_simple_completion(help_cmd, &mut done, &[], args);
}
CommandLineInterface::Nested(map) => { CommandLineInterface::Nested(map) => {
if args.is_empty() { if args.is_empty() {
let mut completions = Vec::new(); let mut completions = Vec::new();
@ -177,7 +178,7 @@ fn get_help_completion(
return Vec::new(); return Vec::new();
} }
if first.starts_with("-") { if first.starts_with('-') {
return get_simple_completion(help_cmd, &mut done, &[], args); return get_simple_completion(help_cmd, &mut done, &[], args);
} }
@ -187,7 +188,7 @@ fn get_help_completion(
completions.push(cmd.to_string()); completions.push(cmd.to_string());
} }
} }
return completions; completions
} }
} }
} }
@ -199,7 +200,7 @@ fn get_nested_completion(def: &CommandLineInterface, args: &[String]) -> Vec<Str
cli_cmd.fixed_param.iter().for_each(|(key, value)| { cli_cmd.fixed_param.iter().for_each(|(key, value)| {
record_done_argument(&mut done, &cli_cmd.info.parameters, &key, &value); record_done_argument(&mut done, &cli_cmd.info.parameters, &key, &value);
}); });
return get_simple_completion(cli_cmd, &mut done, &cli_cmd.arg_param, args); get_simple_completion(cli_cmd, &mut done, &cli_cmd.arg_param, args)
} }
CommandLineInterface::Nested(map) => { CommandLineInterface::Nested(map) => {
if args.is_empty() { if args.is_empty() {
@ -222,7 +223,7 @@ fn get_nested_completion(def: &CommandLineInterface, args: &[String]) -> Vec<Str
completions.push(cmd.to_string()); completions.push(cmd.to_string());
} }
} }
return completions; completions
} }
} }
} }
@ -272,7 +273,7 @@ pub fn get_completions(
}; };
if skip_first { if skip_first {
if args.len() == 0 { if args.is_empty() {
return (0, Vec::new()); return (0, Vec::new());
} }

View File

@ -4,6 +4,7 @@ use std::collections::HashMap;
use crate::{RpcEnvironment, RpcEnvironmentType}; use crate::{RpcEnvironment, RpcEnvironmentType};
/// `RpcEnvironmet` implementation for command line tools /// `RpcEnvironmet` implementation for command line tools
#[derive(Default)]
pub struct CliEnvironment { pub struct CliEnvironment {
result_attributes: HashMap<String, Value>, result_attributes: HashMap<String, Value>,
user: Option<String>, user: Option<String>,
@ -11,10 +12,7 @@ pub struct CliEnvironment {
impl CliEnvironment { impl CliEnvironment {
pub fn new() -> Self { pub fn new() -> Self {
Self { Default::default()
result_attributes: HashMap::new(),
user: None,
}
} }
} }

View File

@ -1,3 +1,5 @@
#![allow(clippy::match_bool)] // just no...
use serde_json::Value; use serde_json::Value;
use std::collections::HashSet; use std::collections::HashSet;
@ -93,7 +95,7 @@ pub fn generate_usage_str(
let type_text = get_schema_type_text(param_schema, ParameterDisplayStyle::Arg); let type_text = get_schema_type_text(param_schema, ParameterDisplayStyle::Arg);
if *optional { if *optional {
if options.len() > 0 { if !options.is_empty() {
options.push('\n'); options.push('\n');
} }
options.push_str(&get_property_description( options.push_str(&get_property_description(
@ -112,7 +114,11 @@ pub fn generate_usage_str(
done_hash.insert(prop); done_hash.insert(prop);
} }
let option_indicator = if options.len() > 0 { " [OPTIONS]" } else { "" }; let option_indicator = if !options.is_empty() {
" [OPTIONS]"
} else {
""
};
let mut text = match format { let mut text = match format {
DocumentationFormat::Short => { DocumentationFormat::Short => {
@ -131,11 +137,11 @@ pub fn generate_usage_str(
), ),
}; };
if arg_descr.len() > 0 { if !arg_descr.is_empty() {
text.push_str(&arg_descr); text.push_str(&arg_descr);
text.push('\n'); text.push('\n');
} }
if options.len() > 0 { if !options.is_empty() {
text.push_str(&options); text.push_str(&options);
text.push('\n'); text.push('\n');
} }
@ -170,7 +176,7 @@ pub fn generate_nested_usage(
match def.commands.get(cmd).unwrap() { match def.commands.get(cmd).unwrap() {
CommandLineInterface::Simple(cli_cmd) => { CommandLineInterface::Simple(cli_cmd) => {
if usage.len() > 0 && format == DocumentationFormat::ReST { if !usage.is_empty() && format == DocumentationFormat::ReST {
usage.push_str("----\n\n"); usage.push_str("----\n\n");
} }
usage.push_str(&generate_usage_str(&new_prefix, cli_cmd, format, "")); usage.push_str(&generate_usage_str(&new_prefix, cli_cmd, format, ""));
@ -188,7 +194,7 @@ pub fn generate_nested_usage(
pub fn print_help( pub fn print_help(
top_def: &CommandLineInterface, top_def: &CommandLineInterface,
mut prefix: String, mut prefix: String,
args: &Vec<String>, args: &[String],
verbose: Option<bool>, verbose: Option<bool>,
) { ) {
let mut iface = top_def; let mut iface = top_def;

View File

@ -21,28 +21,27 @@ fn parse_argument(arg: &str) -> RawArgument {
}; };
} }
let mut first = 1; let first = if bytes[1] == b'-' {
if bytes[1] == b'-' {
if length == 2 { if length == 2 {
return RawArgument::Separator; return RawArgument::Separator;
} }
first = 2; 2
} } else {
1
};
for start in first..length { if let Some(i) = bytes[first..length].iter().position(|b| *b == b'=') {
if bytes[start] == b'=' { let start = i + first;
// Since we take a &str, we know the contents of it are valid utf8. // Since we take a &str, we know the contents of it are valid utf8.
// Since bytes[start] == b'=', we know the byte beginning at start is a single-byte // Since bytes[start] == b'=', we know the byte beginning at start is a single-byte
// code pointer. We also know that 'first' points exactly after a single-byte code // code pointer. We also know that 'first' points exactly after a single-byte code
// point as it points to the first byte after a hyphen. // point as it points to the first byte after a hyphen.
// Therefore we know arg[first..start] is valid utf-8, therefore it is safe to use // Therefore we know arg[first..start] is valid utf-8, therefore it is safe to use
// get_unchecked() to speed things up. // get_unchecked() to speed things up.
return RawArgument::Option { return RawArgument::Option {
name: unsafe { arg.get_unchecked(first..start).to_string() }, name: unsafe { arg.get_unchecked(first..start).to_string() },
value: Some(unsafe { arg.get_unchecked((start + 1)..).to_string() }), value: Some(unsafe { arg.get_unchecked((start + 1)..).to_string() }),
}; };
}
} }
RawArgument::Option { RawArgument::Option {
@ -76,12 +75,9 @@ pub(crate) fn parse_argument_list<T: AsRef<str>>(
if let Some((_optional, param_schema)) = schema.lookup(&name) { if let Some((_optional, param_schema)) = schema.lookup(&name) {
if let Schema::Boolean(boolean_schema) = param_schema { if let Schema::Boolean(boolean_schema) = param_schema {
want_bool = true; want_bool = true;
if let Some(default) = boolean_schema.default { match boolean_schema.default {
if default == false { Some(false) | None => can_default = true,
can_default = true; Some(true) => (),
}
} else {
can_default = true;
} }
} }
} }
@ -93,7 +89,7 @@ pub(crate) fn parse_argument_list<T: AsRef<str>>(
let next = args[pos + 1].as_ref(); let next = args[pos + 1].as_ref();
if let RawArgument::Argument { .. } = parse_argument(next) { if let RawArgument::Argument { .. } = parse_argument(next) {
next_is_argument = true; next_is_argument = true;
if let Ok(_) = parse_boolean(next) { if parse_boolean(next).is_ok() {
next_is_bool = true; next_is_bool = true;
} }
} }
@ -181,7 +177,7 @@ pub fn parse_arguments<T: AsRef<str>>(
let name = arg_param[i]; let name = arg_param[i];
let is_last_arg_param = i == (arg_param.len() - 1); let is_last_arg_param = i == (arg_param.len() - 1);
if rest.len() == 0 { if rest.is_empty() {
if !(is_last_arg_param && last_arg_param_is_optional) { if !(is_last_arg_param && last_arg_param_is_optional) {
errors.push(format_err!("missing argument '{}'", name)); errors.push(format_err!("missing argument '{}'", name));
} }
@ -195,7 +191,7 @@ pub fn parse_arguments<T: AsRef<str>>(
} }
} }
if errors.len() > 0 { if !errors.is_empty() {
return Err(errors); return Err(errors);
} }

View File

@ -36,7 +36,7 @@ impl rustyline::completion::Completer for CliHelper {
let (start, completions) = super::get_completions(&*self.cmd_def, line, false); let (start, completions) = super::get_completions(&*self.cmd_def, line, false);
return Ok((start, completions)); Ok((start, completions))
} }
} }

View File

@ -112,7 +112,7 @@ pub fn shellword_split_unclosed(
/// Return words unescaped and without quotes. /// Return words unescaped and without quotes.
pub fn shellword_split(s: &str) -> Result<Vec<String>, Error> { pub fn shellword_split(s: &str) -> Result<Vec<String>, Error> {
let (args, unclosed_field) = shellword_split_unclosed(s, true); let (args, unclosed_field) = shellword_split_unclosed(s, true);
if !unclosed_field.is_none() { if unclosed_field.is_some() {
bail!("shellword split failed - found unclosed quote."); bail!("shellword split failed - found unclosed quote.");
} }
Ok(args) Ok(args)

View File

@ -291,7 +291,7 @@ pub fn dump_api(
//keys.sort_unstable_by(|a, b| a.cmp(b)); //keys.sort_unstable_by(|a, b| a.cmp(b));
for (key, sub_router) in dirmap.iter() { for (key, sub_router) in dirmap.iter() {
let sub_path = if path == "." { let sub_path = if path == "." {
key.to_string() (*key).to_string()
} else { } else {
format!("{}/{}", path, key) format!("{}/{}", path, key)
}; };

View File

@ -634,7 +634,7 @@ pub fn parse_parameter_strings(
} }
} }
if test_required && errors.len() == 0 { if test_required && errors.is_empty() {
for (name, optional, _prop_schema) in schema.properties { for (name, optional, _prop_schema) in schema.properties {
if !(*optional) && params[name] == Value::Null { if !(*optional) && params[name] == Value::Null {
errors.push(format_err!( errors.push(format_err!(