]> git.proxmox.com Git - proxmox.git/commitdiff
a lot more clippy lint fixes
authorWolfgang Bumiller <w.bumiller@proxmox.com>
Thu, 16 Jul 2020 12:11:01 +0000 (14:11 +0200)
committerWolfgang Bumiller <w.bumiller@proxmox.com>
Thu, 16 Jul 2020 12:11:01 +0000 (14:11 +0200)
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
proxmox/src/api/cli/completion.rs
proxmox/src/api/cli/text_table.rs
proxmox/src/api/permission.rs
proxmox/src/api/section_config.rs
proxmox/src/tools/serde.rs

index ca2ecda0d8af380c3ca521643ab7752dba7ecba6..2bb819773e0cb50854b50113971e0ee5e6e95d23 100644 (file)
@@ -257,7 +257,7 @@ pub fn print_bash_completion(def: &CommandLineInterface) {
 
     let cmdline = match std::env::var("COMP_LINE") {
         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
index 604989617bbd93703306073acf91b43e83325701..0176b20cd8e8f2cbe0e8522aca50bdd4d8edd0a1 100644 (file)
@@ -18,13 +18,11 @@ pub fn get_output_format(param: &Value) -> String {
 
     if let Some(format) = param["output-format"].as_str() {
          output_format = Some(format.to_owned());
-    } else if let Some(format) = std::env::var(ENV_VAR_PROXMOX_OUTPUT_FORMAT).ok() {
-        output_format = Some(format.to_owned());
+    } else if let Ok(format) = std::env::var(ENV_VAR_PROXMOX_OUTPUT_FORMAT) {
+        output_format = Some(format);
     }
 
-    let output_format = output_format.unwrap_or(String::from("text"));
-
-    output_format
+    output_format.unwrap_or_else(|| String::from("text"))
 }
 
 /// 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) => {
             match data.as_str() {
                 Some(value) => {
-                    Ok(format!("{}", value))
+                    Ok(value.to_string())
                 }
                 None => bail!("got unexpected data (expected string)."),
             }
@@ -101,7 +99,10 @@ struct 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 head = String::new();
@@ -110,27 +111,25 @@ impl TableBorders {
 
         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 {
                 top.push('+');
                 head.push('+');
                 middle.push('+');
                 bottom.push('+');
+            } else if i == 0 {
+                top.push('┌');
+                head.push('╞');
+                middle.push('├');
+                bottom.push('└');
             } else {
-                if i == 0 {
-                    top.push('┌');
-                    head.push('╞');
-                    middle.push('├');
-                    bottom.push('└');
-                } else {
-                    top.push('┬');
-                    head.push('╪');
-                    middle.push('┼');
-                    bottom.push('┴');
-                }
+                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 {
                     top.push('=');
                     head.push('=');
@@ -266,11 +265,11 @@ impl TableFormatOptions {
         match self.sortkeys {
             None => {
                 let mut list = Vec::new();
-                list.push((key.to_string(), sort_desc));
+                list.push((key, sort_desc));
                 self.sortkeys = Some(list);
             }
             Some(ref mut list) => {
-               list.push((key.to_string(), sort_desc));
+               list.push((key, sort_desc));
             }
         }
         self
@@ -381,9 +380,7 @@ fn format_table<W: Write>(
 
     use std::cmp::Ordering;
     list.sort_unstable_by(move |a, b| {
-
-        for pos in 0..sortinfo.len() {
-            let (ref sortkey, sort_desc, numeric) = sortinfo[pos];
+        for &(ref sortkey, sort_desc, numeric) in &sortinfo {
             let res = if numeric {
                 let (v1, v2) = if sort_desc {
                     (b[&sortkey].as_f64(), a[&sortkey].as_f64())
@@ -395,18 +392,17 @@ fn format_table<W: Write>(
                     (Some(_), None) => Ordering::Greater,
                     (None, Some(_)) => Ordering::Less,
                     (Some(a), Some(b)) => {
+                        #[allow(clippy::if_same_then_else)]
                         if a.is_nan() {
                             Ordering::Greater
                         } else if b.is_nan() {
                             Ordering::Less
+                        } else if a < b {
+                            Ordering::Less
+                        } else if a > b {
+                            Ordering::Greater
                         } else {
-                            if a < b {
-                                Ordering::Less
-                            } else if a > b {
-                                Ordering::Greater
-                            } else {
-                                Ordering::Equal
-                            }
+                            Ordering::Equal
                         }
                     }
                 }
@@ -418,9 +414,12 @@ fn format_table<W: Write>(
                 };
                 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();
@@ -478,8 +477,8 @@ fn format_table<W: Write>(
 
 fn render_table<W: Write>(
     mut output: W,
-    tabledata: &Vec<TableColumn>,
-    column_names: &Vec<String>,
+    tabledata: &[TableColumn],
+    column_names: &[String],
     options: &TableFormatOptions,
 ) -> Result<(), Error> {
 
@@ -494,9 +493,8 @@ fn render_table<W: Write>(
         Ok(())
     };
 
-    let column_widths = tabledata.iter().map(|d| d.width).collect();
-
-    let borders = TableBorders::new(&column_widths, options.ascii_delimiters);
+    let column_widths = tabledata.iter().map(|d| d.width);
+    let borders = TableBorders::new(column_widths, options.ascii_delimiters);
 
     if !options.noborder { write_line(&borders.top)?; }
 
index c423ec637a7a93815b39f08ea390d2a084447a36..bbaf52f1eb9ad5361384b0a7b8579790a9473b60 100644 (file)
@@ -57,14 +57,14 @@ impl fmt::Debug for Permission {
             Permission::And(list) => {
                 f.write_str("And(\n")?;
                 for subtest in list.iter() {
-                    write!(f, "  {:?}\n", subtest)?;
+                    writeln!(f, "  {:?}", subtest)?;
                 }
                 f.write_str(")\n")
             }
             Permission::Or(list) => {
                 f.write_str("Or(\n")?;
                 for subtest in list.iter() {
-                    write!(f, "  {:?}\n", subtest)?;
+                    writeln!(f, "  {:?}", subtest)?;
                 }
                 f.write_str(")\n")
             }
@@ -98,6 +98,8 @@ pub fn check_api_permission(
     check_api_permission_tail(perm, userid, param, info)
 }
 
+// some of them are deeply nested
+#[allow(clippy::needless_return)]
 fn check_api_permission_tail(
     perm: &Permission,
     userid: Option<&str>,
@@ -161,14 +163,20 @@ fn check_api_permission_tail(
         }
         Permission::And(list) => {
             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;
         }
         Permission::Or(list) => {
             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;
         }
     }
index 97f3a98995fb0748562454ad4c4fb9d850461ab3..3fc82cbe94bed0be479f3d7113e6b0c2cb3778f9 100644 (file)
@@ -82,8 +82,13 @@ pub struct SectionConfigData {
     order: VecDeque<String>,
 }
 
-impl SectionConfigData {
+impl Default for SectionConfigData {
+    fn default() -> Self {
+        Self::new()
+    }
+}
 
+impl SectionConfigData {
     /// Creates a new instance without any data.
     pub fn new() -> Self {
         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> {
         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 {
                 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
     /// error messages.
     pub fn write(&self, filename: &str, config: &SectionConfigData) -> Result<String, Error> {
-
         try_block!({
             let mut list = VecDeque::new();
 
@@ -247,7 +251,7 @@ impl SectionConfig {
                 done.insert(section_id);
             }
 
-            for (section_id, _) in &config.sections {
+            for section_id in config.sections.keys() {
                 if done.contains(section_id) { continue };
                 list.push_back(section_id);
             }
@@ -293,7 +297,6 @@ impl SectionConfig {
     /// plugins. Please note that `filename` is only used to improve
     /// error messages.
     pub fn parse(&self, filename: &str, raw: &str) -> Result<SectionConfigData, Error> {
-
         let mut state = ParseState::BeforeHeader;
 
         let test_required_properties = |value: &Value, schema: &ObjectSchema, id_property: &Option<String>| -> Result<(), Error> {
@@ -304,7 +307,7 @@ impl SectionConfig {
                         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));
                 }
             }
@@ -373,6 +376,7 @@ impl SectionConfig {
                                     }
                                 };
 
+                                #[allow(clippy::collapsible_if)] // clearer
                                 if is_array {
                                    if config[&key] == Value::Null {
                                        config[key] = json!([value]);
@@ -422,7 +426,6 @@ impl SectionConfig {
         key: &str,
         value: &Value,
     ) -> Result<String, Error> {
-
         if let Value::Array(array) = value {
             let mut list = String::new();
             for item in array {
@@ -450,11 +453,15 @@ impl SectionConfig {
     }
 
     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();
 
-        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());
 
@@ -463,7 +470,7 @@ impl SectionConfig {
             None => return None,
         };
 
-        if key.len() == 0 { return None; }
+        if key.is_empty() { return None; }
 
         let value = match kv_iter.next() {
             Some(v) => v.trim(),
@@ -474,12 +481,15 @@ impl SectionConfig {
    }
 
     fn default_parse_section_header(line: &str) -> Option<(String, String)> {
-
-        if line.is_empty() { return None; };
+        if line.is_empty() {
+            return None;
+        };
 
         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, ':');
 
@@ -488,7 +498,9 @@ impl SectionConfig {
             None => return None,
         };
 
-        if section_type.len() == 0 { return None; }
+        if section_type.is_empty() {
+            return None;
+        }
 
         let section_id = match head_iter.next() {
             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> {
-        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))
     }
 
@@ -537,7 +552,6 @@ impl SectionConfig {
     }
 
     fn systemd_parse_section_content(line: &str) -> Option<(String, String)> {
-
         let line = line.trim_end();
 
         if line.is_empty() { return None; }
@@ -555,17 +569,21 @@ impl SectionConfig {
     }
 
     fn systemd_parse_section_header(line: &str) -> Option<(String, String)> {
-
         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.ends_with("]") { return None; }
+        if !line.starts_with('[') || !line.ends_with(']') {
+            return None;
+        }
 
         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()))
     }
index 9fb28b10d354f6712b13ccc9bc15abd4bf50ebdb..d6a5b7714db57c3a45b197a473ea63a092c2589f 100644 (file)
@@ -115,8 +115,6 @@ pub mod bytes_as_base64 {
 /// assert_eq!(obj, deserialized);
 /// ```
 pub mod string_as_base64 {
-
-    use base64;
     use serde::{Deserialize, Deserializer, Serializer};
 
     pub fn serialize<S>(data: &str, serializer: S) -> Result<S::Ok, S::Error>