a lot more clippy lint fixes

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
This commit is contained in:
Wolfgang Bumiller 2020-07-16 14:11:01 +02:00
parent def1d54aa6
commit debd9f9f4f
5 changed files with 90 additions and 68 deletions

View File

@ -257,7 +257,7 @@ pub fn print_bash_completion(def: &CommandLineInterface) {
let cmdline = match std::env::var("COMP_LINE") { let cmdline = match std::env::var("COMP_LINE") {
Ok(mut val) => { Ok(mut val) => {
if let Some((byte_pos, _)) = val.char_indices().skip(comp_point).next() { if let Some((byte_pos, _)) = val.char_indices().nth(comp_point) {
val.truncate(byte_pos); val.truncate(byte_pos);
} }
val val

View File

@ -18,13 +18,11 @@ pub fn get_output_format(param: &Value) -> String {
if let Some(format) = param["output-format"].as_str() { if let Some(format) = param["output-format"].as_str() {
output_format = Some(format.to_owned()); output_format = Some(format.to_owned());
} else if let Some(format) = std::env::var(ENV_VAR_PROXMOX_OUTPUT_FORMAT).ok() { } else if let Ok(format) = std::env::var(ENV_VAR_PROXMOX_OUTPUT_FORMAT) {
output_format = Some(format.to_owned()); output_format = Some(format);
} }
let output_format = output_format.unwrap_or(String::from("text")); output_format.unwrap_or_else(|| String::from("text"))
output_format
} }
/// Helper to get TableFormatOptions with default from environment /// Helper to get TableFormatOptions with default from environment
@ -77,7 +75,7 @@ fn data_to_text(data: &Value, schema: &Schema) -> Result<String, Error> {
Schema::String(_string_schema) => { Schema::String(_string_schema) => {
match data.as_str() { match data.as_str() {
Some(value) => { Some(value) => {
Ok(format!("{}", value)) Ok(value.to_string())
} }
None => bail!("got unexpected data (expected string)."), None => bail!("got unexpected data (expected string)."),
} }
@ -101,7 +99,10 @@ struct TableBorders {
impl TableBorders { impl TableBorders {
fn new(column_widths: &Vec<usize>, ascii_delimiters: bool) -> Self { fn new<I>(column_widths: I, ascii_delimiters: bool) -> Self
where
I: Iterator<Item = usize>,
{
let mut top = String::new(); let mut top = String::new();
let mut head = String::new(); let mut head = String::new();
@ -110,27 +111,25 @@ impl TableBorders {
let column_separator = if ascii_delimiters { '|' } else { '│' }; let column_separator = if ascii_delimiters { '|' } else { '│' };
for (i, column_width) in column_widths.iter().enumerate() { for (i, column_width) in column_widths.enumerate() {
if ascii_delimiters { if ascii_delimiters {
top.push('+'); top.push('+');
head.push('+'); head.push('+');
middle.push('+'); middle.push('+');
bottom.push('+'); bottom.push('+');
} else if i == 0 {
top.push('┌');
head.push('╞');
middle.push('├');
bottom.push('└');
} else { } else {
if i == 0 { top.push('┬');
top.push('┌'); head.push('╪');
head.push('╞'); middle.push('┼');
middle.push('├'); bottom.push('┴');
bottom.push('└');
} else {
top.push('┬');
head.push('╪');
middle.push('┼');
bottom.push('┴');
}
} }
for _j in 0..*column_width+2 { for _j in 0..(column_width + 2) {
if ascii_delimiters { if ascii_delimiters {
top.push('='); top.push('=');
head.push('='); head.push('=');
@ -266,11 +265,11 @@ impl TableFormatOptions {
match self.sortkeys { match self.sortkeys {
None => { None => {
let mut list = Vec::new(); let mut list = Vec::new();
list.push((key.to_string(), sort_desc)); list.push((key, sort_desc));
self.sortkeys = Some(list); self.sortkeys = Some(list);
} }
Some(ref mut list) => { Some(ref mut list) => {
list.push((key.to_string(), sort_desc)); list.push((key, sort_desc));
} }
} }
self self
@ -381,9 +380,7 @@ fn format_table<W: Write>(
use std::cmp::Ordering; use std::cmp::Ordering;
list.sort_unstable_by(move |a, b| { list.sort_unstable_by(move |a, b| {
for &(ref sortkey, sort_desc, numeric) in &sortinfo {
for pos in 0..sortinfo.len() {
let (ref sortkey, sort_desc, numeric) = sortinfo[pos];
let res = if numeric { let res = if numeric {
let (v1, v2) = if sort_desc { let (v1, v2) = if sort_desc {
(b[&sortkey].as_f64(), a[&sortkey].as_f64()) (b[&sortkey].as_f64(), a[&sortkey].as_f64())
@ -395,18 +392,17 @@ fn format_table<W: Write>(
(Some(_), None) => Ordering::Greater, (Some(_), None) => Ordering::Greater,
(None, Some(_)) => Ordering::Less, (None, Some(_)) => Ordering::Less,
(Some(a), Some(b)) => { (Some(a), Some(b)) => {
#[allow(clippy::if_same_then_else)]
if a.is_nan() { if a.is_nan() {
Ordering::Greater Ordering::Greater
} else if b.is_nan() { } else if b.is_nan() {
Ordering::Less Ordering::Less
} else if a < b {
Ordering::Less
} else if a > b {
Ordering::Greater
} else { } else {
if a < b { Ordering::Equal
Ordering::Less
} else if a > b {
Ordering::Greater
} else {
Ordering::Equal
}
} }
} }
} }
@ -418,9 +414,12 @@ fn format_table<W: Write>(
}; };
v1.cmp(&v2) v1.cmp(&v2)
}; };
if res != Ordering::Equal { return res; }
if res != Ordering::Equal {
return res;
}
} }
return Ordering::Equal; Ordering::Equal
}); });
let mut tabledata: Vec<TableColumn> = Vec::new(); let mut tabledata: Vec<TableColumn> = Vec::new();
@ -478,8 +477,8 @@ fn format_table<W: Write>(
fn render_table<W: Write>( fn render_table<W: Write>(
mut output: W, mut output: W,
tabledata: &Vec<TableColumn>, tabledata: &[TableColumn],
column_names: &Vec<String>, column_names: &[String],
options: &TableFormatOptions, options: &TableFormatOptions,
) -> Result<(), Error> { ) -> Result<(), Error> {
@ -494,9 +493,8 @@ fn render_table<W: Write>(
Ok(()) Ok(())
}; };
let column_widths = tabledata.iter().map(|d| d.width).collect(); let column_widths = tabledata.iter().map(|d| d.width);
let borders = TableBorders::new(column_widths, options.ascii_delimiters);
let borders = TableBorders::new(&column_widths, options.ascii_delimiters);
if !options.noborder { write_line(&borders.top)?; } if !options.noborder { write_line(&borders.top)?; }

View File

@ -57,14 +57,14 @@ impl fmt::Debug for Permission {
Permission::And(list) => { Permission::And(list) => {
f.write_str("And(\n")?; f.write_str("And(\n")?;
for subtest in list.iter() { for subtest in list.iter() {
write!(f, " {:?}\n", subtest)?; writeln!(f, " {:?}", subtest)?;
} }
f.write_str(")\n") f.write_str(")\n")
} }
Permission::Or(list) => { Permission::Or(list) => {
f.write_str("Or(\n")?; f.write_str("Or(\n")?;
for subtest in list.iter() { for subtest in list.iter() {
write!(f, " {:?}\n", subtest)?; writeln!(f, " {:?}", subtest)?;
} }
f.write_str(")\n") f.write_str(")\n")
} }
@ -98,6 +98,8 @@ pub fn check_api_permission(
check_api_permission_tail(perm, userid, param, info) check_api_permission_tail(perm, userid, param, info)
} }
// some of them are deeply nested
#[allow(clippy::needless_return)]
fn check_api_permission_tail( fn check_api_permission_tail(
perm: &Permission, perm: &Permission,
userid: Option<&str>, userid: Option<&str>,
@ -161,14 +163,20 @@ fn check_api_permission_tail(
} }
Permission::And(list) => { Permission::And(list) => {
for subtest in list.iter() { for subtest in list.iter() {
if !check_api_permission_tail(subtest, userid, param, info) { return false; } if !check_api_permission_tail(subtest, userid, param, info) {
return false;
}
} }
return true; return true;
} }
Permission::Or(list) => { Permission::Or(list) => {
for subtest in list.iter() { for subtest in list.iter() {
if check_api_permission_tail(subtest, userid, param, info) { return true; } if check_api_permission_tail(subtest, userid, param, info) {
return true;
}
} }
return false; return false;
} }
} }

View File

@ -82,8 +82,13 @@ pub struct SectionConfigData {
order: VecDeque<String>, order: VecDeque<String>,
} }
impl SectionConfigData { impl Default for SectionConfigData {
fn default() -> Self {
Self::new()
}
}
impl SectionConfigData {
/// Creates a new instance without any data. /// Creates a new instance without any data.
pub fn new() -> Self { pub fn new() -> Self {
Self { sections: HashMap::new(), order: VecDeque::new() } Self { sections: HashMap::new(), order: VecDeque::new() }
@ -167,13 +172,13 @@ impl SectionConfigData {
pub fn convert_to_typed_array<T: DeserializeOwned>(&self, type_name: &str) -> Result<Vec<T>, Error> { pub fn convert_to_typed_array<T: DeserializeOwned>(&self, type_name: &str) -> Result<Vec<T>, Error> {
let mut list: Vec<T> = vec![]; let mut list: Vec<T> = vec![];
for (_, (section_type, data)) in &self.sections { for (section_type, data) in self.sections.values() {
if section_type == type_name { if section_type == type_name {
list.push(T::deserialize(data.clone())?); list.push(T::deserialize(data.clone())?);
} }
} }
Ok(list.into()) Ok(list)
} }
} }
@ -235,7 +240,6 @@ impl SectionConfig {
/// plugins. Please note that `filename` is only used to improve /// plugins. Please note that `filename` is only used to improve
/// error messages. /// error messages.
pub fn write(&self, filename: &str, config: &SectionConfigData) -> Result<String, Error> { pub fn write(&self, filename: &str, config: &SectionConfigData) -> Result<String, Error> {
try_block!({ try_block!({
let mut list = VecDeque::new(); let mut list = VecDeque::new();
@ -247,7 +251,7 @@ impl SectionConfig {
done.insert(section_id); done.insert(section_id);
} }
for (section_id, _) in &config.sections { for section_id in config.sections.keys() {
if done.contains(section_id) { continue }; if done.contains(section_id) { continue };
list.push_back(section_id); list.push_back(section_id);
} }
@ -293,7 +297,6 @@ impl SectionConfig {
/// plugins. Please note that `filename` is only used to improve /// plugins. Please note that `filename` is only used to improve
/// error messages. /// error messages.
pub fn parse(&self, filename: &str, raw: &str) -> Result<SectionConfigData, Error> { pub fn parse(&self, filename: &str, raw: &str) -> Result<SectionConfigData, Error> {
let mut state = ParseState::BeforeHeader; let mut state = ParseState::BeforeHeader;
let test_required_properties = |value: &Value, schema: &ObjectSchema, id_property: &Option<String>| -> Result<(), Error> { let test_required_properties = |value: &Value, schema: &ObjectSchema, id_property: &Option<String>| -> Result<(), Error> {
@ -304,7 +307,7 @@ impl SectionConfig {
continue; continue;
} }
} }
if *optional == false && value[name] == Value::Null { if !*optional && value[name] == Value::Null {
return Err(format_err!("property '{}' is missing and it is not optional.", name)); return Err(format_err!("property '{}' is missing and it is not optional.", name));
} }
} }
@ -373,6 +376,7 @@ impl SectionConfig {
} }
}; };
#[allow(clippy::collapsible_if)] // clearer
if is_array { if is_array {
if config[&key] == Value::Null { if config[&key] == Value::Null {
config[key] = json!([value]); config[key] = json!([value]);
@ -422,7 +426,6 @@ impl SectionConfig {
key: &str, key: &str,
value: &Value, value: &Value,
) -> Result<String, Error> { ) -> Result<String, Error> {
if let Value::Array(array) = value { if let Value::Array(array) = value {
let mut list = String::new(); let mut list = String::new();
for item in array { for item in array {
@ -450,11 +453,15 @@ impl SectionConfig {
} }
fn default_parse_section_content(line: &str) -> Option<(String, String)> { fn default_parse_section_content(line: &str) -> Option<(String, String)> {
if line.is_empty() {
return None;
}
if line.is_empty() { return None; }
let first_char = line.chars().next().unwrap(); let first_char = line.chars().next().unwrap();
if !first_char.is_whitespace() { return None } if !first_char.is_whitespace() {
return None;
}
let mut kv_iter = line.trim_start().splitn(2, |c: char| c.is_whitespace()); let mut kv_iter = line.trim_start().splitn(2, |c: char| c.is_whitespace());
@ -463,7 +470,7 @@ impl SectionConfig {
None => return None, None => return None,
}; };
if key.len() == 0 { return None; } if key.is_empty() { return None; }
let value = match kv_iter.next() { let value = match kv_iter.next() {
Some(v) => v.trim(), Some(v) => v.trim(),
@ -474,12 +481,15 @@ impl SectionConfig {
} }
fn default_parse_section_header(line: &str) -> Option<(String, String)> { fn default_parse_section_header(line: &str) -> Option<(String, String)> {
if line.is_empty() {
if line.is_empty() { return None; }; return None;
};
let first_char = line.chars().next().unwrap(); let first_char = line.chars().next().unwrap();
if !first_char.is_alphabetic() { return None } if !first_char.is_alphabetic() {
return None;
}
let mut head_iter = line.splitn(2, ':'); let mut head_iter = line.splitn(2, ':');
@ -488,7 +498,9 @@ impl SectionConfig {
None => return None, None => return None,
}; };
if section_type.len() == 0 { return None; } if section_type.is_empty() {
return None;
}
let section_id = match head_iter.next() { let section_id = match head_iter.next() {
Some(v) => v.trim(), Some(v) => v.trim(),
@ -499,7 +511,10 @@ impl SectionConfig {
} }
fn systemd_format_section_header(type_name: &str, section_id: &str, _data: &Value) -> Result<String, Error> { fn systemd_format_section_header(type_name: &str, section_id: &str, _data: &Value) -> Result<String, Error> {
if type_name != section_id { bail!("gut unexpexted section type"); } if type_name != section_id {
bail!("gut unexpexted section type");
}
Ok(format!("[{}]\n", section_id)) Ok(format!("[{}]\n", section_id))
} }
@ -537,7 +552,6 @@ impl SectionConfig {
} }
fn systemd_parse_section_content(line: &str) -> Option<(String, String)> { fn systemd_parse_section_content(line: &str) -> Option<(String, String)> {
let line = line.trim_end(); let line = line.trim_end();
if line.is_empty() { return None; } if line.is_empty() { return None; }
@ -555,17 +569,21 @@ impl SectionConfig {
} }
fn systemd_parse_section_header(line: &str) -> Option<(String, String)> { fn systemd_parse_section_header(line: &str) -> Option<(String, String)> {
let line = line.trim_end(); let line = line.trim_end();
if line.is_empty() { return None; }; if line.is_empty() {
return None;
};
if !line.starts_with("[") { return None; } if !line.starts_with('[') || !line.ends_with(']') {
if !line.ends_with("]") { return None; } return None;
}
let section = line[1..line.len()-1].trim(); let section = line[1..line.len()-1].trim();
if section.len() == 0 { return None; } if section.is_empty() {
return None;
}
Some((section.into(), section.into())) Some((section.into(), section.into()))
} }

View File

@ -115,8 +115,6 @@ pub mod bytes_as_base64 {
/// assert_eq!(obj, deserialized); /// assert_eq!(obj, deserialized);
/// ``` /// ```
pub mod string_as_base64 { pub mod string_as_base64 {
use base64;
use serde::{Deserialize, Deserializer, Serializer}; use serde::{Deserialize, Deserializer, Serializer};
pub fn serialize<S>(data: &str, serializer: S) -> Result<S::Ok, S::Error> pub fn serialize<S>(data: &str, serializer: S) -> Result<S::Ok, S::Error>