rust: run `cargo clippy`
authorRaphaël Gomès <rgomes@octobus.net>
Mon, 09 Jan 2023 17:40:03 +0100
changeset 49914 58074252db3c
parent 49913 c15b415d1bff
child 49915 c8ef85ace216
rust: run `cargo clippy` These automatic fixes are good to have because they make the code more idiomatic and less surprising. The transform from `sort` -> `sort_unstable` is questionable, but this is only in a test, so it doesn't matter in our case.
rust/hg-core/examples/nodemap/main.rs
rust/hg-core/src/vfs.rs
rust/hg-core/tests/test_missing_ancestors.rs
rust/hg-cpython/src/dirstate/dirs_multiset.rs
rust/hg-cpython/src/dirstate/dirstate_map.rs
rust/hg-cpython/src/dirstate/item.rs
rust/hg-cpython/src/dirstate/status.rs
rust/hg-cpython/src/revlog.rs
rust/rhg/src/color.rs
rust/rhg/src/commands/cat.rs
rust/rhg/src/commands/debugignorerhg.rs
rust/rhg/src/commands/debugrhgsparse.rs
rust/rhg/src/commands/status.rs
rust/rhg/src/error.rs
rust/rhg/src/main.rs
rust/rhg/src/utils/path_utils.rs
--- a/rust/hg-core/examples/nodemap/main.rs	Fri Jan 06 18:52:04 2023 +0100
+++ b/rust/hg-core/examples/nodemap/main.rs	Mon Jan 09 17:40:03 2023 +0100
@@ -55,12 +55,7 @@
     let len = index.len() as u32;
     let mut rng = rand::thread_rng();
     let nodes: Vec<Node> = (0..queries)
-        .map(|_| {
-            index
-                .node((rng.gen::<u32>() % len) as Revision)
-                .unwrap()
-                .clone()
-        })
+        .map(|_| *index.node((rng.gen::<u32>() % len) as Revision).unwrap())
         .collect();
     if queries < 10 {
         let nodes_hex: Vec<String> =
@@ -125,7 +120,7 @@
                 nm_path.display(),
                 repo.display()
             );
-            create(&index, &Path::new(nm_path)).unwrap();
+            create(&index, Path::new(nm_path)).unwrap();
         }
         Command::Bench { queries } => {
             println!(
--- a/rust/hg-core/src/vfs.rs	Fri Jan 06 18:52:04 2023 +0100
+++ b/rust/hg-core/src/vfs.rs	Mon Jan 09 17:40:03 2023 +0100
@@ -48,7 +48,7 @@
         match self.read(relative_path) {
             Err(e) => match &e {
                 HgError::IoError { error, .. } => match error.kind() {
-                    ErrorKind::NotFound => return Ok(None),
+                    ErrorKind::NotFound => Ok(None),
                     _ => Err(e),
                 },
                 _ => Err(e),
--- a/rust/hg-core/tests/test_missing_ancestors.rs	Fri Jan 06 18:52:04 2023 +0100
+++ b/rust/hg-core/tests/test_missing_ancestors.rs	Mon Jan 09 17:40:03 2023 +0100
@@ -38,7 +38,7 @@
             // p2 is a random revision lower than i and different from p1
             let mut p2 = rng.gen_range(0..i - 1) as Revision;
             if p2 >= p1 {
-                p2 = p2 + 1;
+                p2 += 1;
             }
             vg.push([p1, p2]);
         } else if rng.gen_bool(prevprob) {
@@ -95,9 +95,9 @@
         random_seed: &str,
     ) -> Self {
         Self {
-            ancestors_sets: ancestors_sets,
+            ancestors_sets,
             bases: bases.clone(),
-            graph: graph,
+            graph,
             history: vec![MissingAncestorsAction::InitialBases(bases.clone())],
             random_seed: random_seed.into(),
         }
@@ -116,7 +116,7 @@
         for base in self.bases.iter().cloned() {
             if base != NULL_REVISION {
                 for rev in &self.ancestors_sets[base as usize] {
-                    revs.remove(&rev);
+                    revs.remove(rev);
                 }
             }
         }
@@ -140,12 +140,12 @@
         for base in self.bases.iter().cloned() {
             if base != NULL_REVISION {
                 for rev in &self.ancestors_sets[base as usize] {
-                    missing.remove(&rev);
+                    missing.remove(rev);
                 }
             }
         }
         let mut res: Vec<Revision> = missing.iter().cloned().collect();
-        res.sort();
+        res.sort_unstable();
         res
     }
 
@@ -196,7 +196,7 @@
     let nb = min(maxrev as usize, log_normal.sample(rng).floor() as usize);
 
     let dist = Uniform::from(NULL_REVISION..maxrev);
-    return rng.sample_iter(&dist).take(nb).collect();
+    rng.sample_iter(&dist).take(nb).collect()
 }
 
 /// Produces the hexadecimal representation of a slice of bytes
--- a/rust/hg-cpython/src/dirstate/dirs_multiset.rs	Fri Jan 06 18:52:04 2023 +0100
+++ b/rust/hg-cpython/src/dirstate/dirs_multiset.rs	Mon Jan 09 17:40:03 2023 +0100
@@ -98,7 +98,7 @@
 
     def __contains__(&self, item: PyObject) -> PyResult<bool> {
         Ok(self.inner(py).borrow().contains(HgPath::new(
-            item.extract::<PyBytes>(py)?.data(py).as_ref(),
+            item.extract::<PyBytes>(py)?.data(py),
         )))
     }
 });
--- a/rust/hg-cpython/src/dirstate/dirstate_map.rs	Fri Jan 06 18:52:04 2023 +0100
+++ b/rust/hg-cpython/src/dirstate/dirstate_map.rs	Mon Jan 09 17:40:03 2023 +0100
@@ -104,9 +104,7 @@
         let bytes = f.extract::<PyBytes>(py)?;
         let path = HgPath::new(bytes.data(py));
         let res = self.inner(py).borrow_mut().set_tracked(path);
-        let was_tracked = res.or_else(|_| {
-            Err(PyErr::new::<exc::OSError, _>(py, "Dirstate error".to_string()))
-        })?;
+        let was_tracked = res.map_err(|_| PyErr::new::<exc::OSError, _>(py, "Dirstate error".to_string()))?;
         Ok(was_tracked.to_py_object(py))
     }
 
@@ -114,9 +112,7 @@
         let bytes = f.extract::<PyBytes>(py)?;
         let path = HgPath::new(bytes.data(py));
         let res = self.inner(py).borrow_mut().set_untracked(path);
-        let was_tracked = res.or_else(|_| {
-            Err(PyErr::new::<exc::OSError, _>(py, "Dirstate error".to_string()))
-        })?;
+        let was_tracked = res.map_err(|_| PyErr::new::<exc::OSError, _>(py, "Dirstate error".to_string()))?;
         Ok(was_tracked.to_py_object(py))
     }
 
@@ -136,9 +132,7 @@
         let res = self.inner(py).borrow_mut().set_clean(
             path, mode, size, timestamp,
         );
-        res.or_else(|_| {
-            Err(PyErr::new::<exc::OSError, _>(py, "Dirstate error".to_string()))
-        })?;
+        res.map_err(|_| PyErr::new::<exc::OSError, _>(py, "Dirstate error".to_string()))?;
         Ok(PyNone)
     }
 
@@ -146,9 +140,7 @@
         let bytes = f.extract::<PyBytes>(py)?;
         let path = HgPath::new(bytes.data(py));
         let res = self.inner(py).borrow_mut().set_possibly_dirty(path);
-        res.or_else(|_| {
-            Err(PyErr::new::<exc::OSError, _>(py, "Dirstate error".to_string()))
-        })?;
+        res.map_err(|_| PyErr::new::<exc::OSError, _>(py, "Dirstate error".to_string()))?;
         Ok(PyNone)
     }
 
@@ -195,9 +187,7 @@
             has_meaningful_mtime,
             parent_file_data,
         );
-        res.or_else(|_| {
-            Err(PyErr::new::<exc::OSError, _>(py, "Dirstate error".to_string()))
-        })?;
+        res.map_err(|_| PyErr::new::<exc::OSError, _>(py, "Dirstate error".to_string()))?;
         Ok(PyNone)
     }
 
--- a/rust/hg-cpython/src/dirstate/item.rs	Fri Jan 06 18:52:04 2023 +0100
+++ b/rust/hg-cpython/src/dirstate/item.rs	Mon Jan 09 17:40:03 2023 +0100
@@ -40,7 +40,7 @@
             }
         }
         let entry = DirstateEntry::from_v2_data(DirstateV2Data {
-            wc_tracked: wc_tracked,
+            wc_tracked,
             p1_tracked,
             p2_info,
             mode_size: mode_size_opt,
--- a/rust/hg-cpython/src/dirstate/status.rs	Fri Jan 06 18:52:04 2023 +0100
+++ b/rust/hg-cpython/src/dirstate/status.rs	Mon Jan 09 17:40:03 2023 +0100
@@ -72,12 +72,11 @@
     for (path, bad_match) in collection.iter() {
         let message = match bad_match {
             BadMatch::OsError(code) => get_error_message(*code)?,
-            BadMatch::BadType(bad_type) => format!(
-                "unsupported file type (type is {})",
-                bad_type.to_string()
-            )
-            .to_py_object(py)
-            .into_object(),
+            BadMatch::BadType(bad_type) => {
+                format!("unsupported file type (type is {})", bad_type)
+                    .to_py_object(py)
+                    .into_object()
+            }
         };
         list.append(
             py,
--- a/rust/hg-cpython/src/revlog.rs	Fri Jan 06 18:52:04 2023 +0100
+++ b/rust/hg-cpython/src/revlog.rs	Mon Jan 09 17:40:03 2023 +0100
@@ -144,9 +144,9 @@
         // __delitem__ is both for `del idx[r]` and `del idx[r1:r2]`
         self.cindex(py).borrow().inner().del_item(py, key)?;
         let mut opt = self.get_nodetree(py)?.borrow_mut();
-        let mut nt = opt.as_mut().unwrap();
+        let nt = opt.as_mut().unwrap();
         nt.invalidate_all();
-        self.fill_nodemap(py, &mut nt)?;
+        self.fill_nodemap(py, nt)?;
         Ok(())
     }
 
--- a/rust/rhg/src/color.rs	Fri Jan 06 18:52:04 2023 +0100
+++ b/rust/rhg/src/color.rs	Mon Jan 09 17:40:03 2023 +0100
@@ -245,11 +245,8 @@
 impl ColorConfig {
     // Similar to _modesetup in mercurial/color.py
     pub fn new(config: &Config) -> Result<Option<Self>, HgError> {
-        Ok(match ColorMode::get(config)? {
-            None => None,
-            Some(ColorMode::Ansi) => Some(ColorConfig {
-                styles: effects_from_config(config),
-            }),
-        })
+        Ok(ColorMode::get(config)?.map(|ColorMode::Ansi| ColorConfig {
+            styles: effects_from_config(config),
+        }))
     }
 }
--- a/rust/rhg/src/commands/cat.rs	Fri Jan 06 18:52:04 2023 +0100
+++ b/rust/rhg/src/commands/cat.rs	Mon Jan 09 17:40:03 2023 +0100
@@ -95,7 +95,7 @@
         None => format!("{:x}", repo.dirstate_parents()?.p1),
     };
 
-    let output = cat(&repo, &rev, files).map_err(|e| (e, rev.as_str()))?;
+    let output = cat(repo, &rev, files).map_err(|e| (e, rev.as_str()))?;
     for (_file, contents) in output.results {
         invocation.ui.write_stdout(&contents)?;
     }
--- a/rust/rhg/src/commands/debugignorerhg.rs	Fri Jan 06 18:52:04 2023 +0100
+++ b/rust/rhg/src/commands/debugignorerhg.rs	Mon Jan 09 17:40:03 2023 +0100
@@ -23,10 +23,10 @@
 
     let (ignore_matcher, warnings) = get_ignore_matcher(
         vec![ignore_file],
-        &repo.working_directory_path().to_owned(),
+        repo.working_directory_path(),
         &mut |_source, _pattern_bytes| (),
     )
-    .map_err(|e| StatusError::from(e))?;
+    .map_err(StatusError::from)?;
 
     if !warnings.is_empty() {
         warn!("Pattern warnings: {:?}", &warnings);
--- a/rust/rhg/src/commands/debugrhgsparse.rs	Fri Jan 06 18:52:04 2023 +0100
+++ b/rust/rhg/src/commands/debugrhgsparse.rs	Mon Jan 09 17:40:03 2023 +0100
@@ -24,7 +24,7 @@
 pub fn run(invocation: &crate::CliInvocation) -> Result<(), CommandError> {
     let repo = invocation.repo?;
 
-    let (matcher, _warnings) = hg::sparse::matcher(&repo).unwrap();
+    let (matcher, _warnings) = hg::sparse::matcher(repo).unwrap();
     let files = invocation.subcommand_args.get_many::<OsString>("files");
     if let Some(files) = files {
         let files: Vec<&OsStr> = files
--- a/rust/rhg/src/commands/status.rs	Fri Jan 06 18:52:04 2023 +0100
+++ b/rust/rhg/src/commands/status.rs	Mon Jan 09 17:40:03 2023 +0100
@@ -169,7 +169,7 @@
 }
 
 fn has_unfinished_merge(repo: &Repo) -> Result<bool, CommandError> {
-    return Ok(repo.dirstate_parents()?.is_merge());
+    Ok(repo.dirstate_parents()?.is_merge())
 }
 
 fn has_unfinished_state(repo: &Repo) -> Result<bool, CommandError> {
@@ -192,7 +192,7 @@
             return Ok(true);
         }
     }
-    return Ok(false);
+    Ok(false)
 }
 
 pub fn run(invocation: &crate::CliInvocation) -> Result<(), CommandError> {
@@ -244,12 +244,10 @@
 
     let repo = invocation.repo?;
 
-    if verbose {
-        if has_unfinished_state(repo)? {
-            return Err(CommandError::unsupported(
-                "verbose status output is not supported by rhg (and is needed because we're in an unfinished operation)",
-            ));
-        };
+    if verbose && has_unfinished_state(repo)? {
+        return Err(CommandError::unsupported(
+            "verbose status output is not supported by rhg (and is needed because we're in an unfinished operation)",
+        ));
     }
 
     let mut dmap = repo.dirstate_map_mut()?;
@@ -271,7 +269,7 @@
     let after_status = |res: StatusResult| -> Result<_, CommandError> {
         let (mut ds_status, pattern_warnings) = res?;
         for warning in pattern_warnings {
-            ui.write_stderr(&print_pattern_file_warning(&warning, &repo))?;
+            ui.write_stderr(&print_pattern_file_warning(&warning, repo))?;
         }
 
         for (path, error) in ds_status.bad {
@@ -408,7 +406,7 @@
                 ui.write_stderr(&msg)?;
             }
             sparse::SparseWarning::Pattern(e) => {
-                ui.write_stderr(&print_pattern_file_warning(e, &repo))?;
+                ui.write_stderr(&print_pattern_file_warning(e, repo))?;
             }
         }
     }
--- a/rust/rhg/src/error.rs	Fri Jan 06 18:52:04 2023 +0100
+++ b/rust/rhg/src/error.rs	Mon Jan 09 17:40:03 2023 +0100
@@ -50,7 +50,7 @@
             // of error messages to handle non-UTF-8 filenames etc:
             // https://www.mercurial-scm.org/wiki/EncodingStrategy#Mixing_output
             message: utf8_to_local(message.as_ref()).into(),
-            detailed_exit_code: detailed_exit_code,
+            detailed_exit_code,
             hint: None,
         }
     }
--- a/rust/rhg/src/main.rs	Fri Jan 06 18:52:04 2023 +0100
+++ b/rust/rhg/src/main.rs	Mon Jan 09 17:40:03 2023 +0100
@@ -69,7 +69,7 @@
         .version("0.0.1");
     let app = add_subcommand_args(app);
 
-    let matches = app.clone().try_get_matches_from(argv.iter())?;
+    let matches = app.try_get_matches_from(argv.iter())?;
 
     let (subcommand_name, subcommand_args) =
         matches.subcommand().expect("subcommand required");
@@ -203,7 +203,7 @@
                 // Same as `_matchscheme` in `mercurial/util.py`
                 regex::bytes::Regex::new("^[a-zA-Z0-9+.\\-]+:").unwrap();
         }
-        if SCHEME_RE.is_match(&repo_path_bytes) {
+        if SCHEME_RE.is_match(repo_path_bytes) {
             exit(
                 &argv,
                 &initial_current_dir,
@@ -223,7 +223,7 @@
             )
         }
     }
-    let repo_arg = early_args.repo.unwrap_or(Vec::new());
+    let repo_arg = early_args.repo.unwrap_or_default();
     let repo_path: Option<PathBuf> = {
         if repo_arg.is_empty() {
             None
@@ -254,7 +254,7 @@
             let non_repo_config_val = {
                 let non_repo_val = non_repo_config.get(b"paths", &repo_arg);
                 match &non_repo_val {
-                    Some(val) if val.len() > 0 => home::home_dir()
+                    Some(val) if !val.is_empty() => home::home_dir()
                         .unwrap_or_else(|| PathBuf::from("~"))
                         .join(get_path_from_bytes(val))
                         .canonicalize()
@@ -270,7 +270,7 @@
                 Some(val) => {
                     let local_config_val = val.get(b"paths", &repo_arg);
                     match &local_config_val {
-                        Some(val) if val.len() > 0 => {
+                        Some(val) if !val.is_empty() => {
                             // presence of a local_config assures that
                             // current_dir
                             // wont result in an Error
@@ -304,7 +304,7 @@
             )
         };
     let early_exit = |config: &Config, error: CommandError| -> ! {
-        simple_exit(&Ui::new_infallible(config), &config, Err(error))
+        simple_exit(&Ui::new_infallible(config), config, Err(error))
     };
     let repo_result = match Repo::find(&non_repo_config, repo_path.to_owned())
     {
@@ -328,13 +328,13 @@
         && config_cow
             .as_ref()
             .get_bool(b"ui", b"tweakdefaults")
-            .unwrap_or_else(|error| early_exit(&config, error.into()))
+            .unwrap_or_else(|error| early_exit(config, error.into()))
     {
         config_cow.to_mut().tweakdefaults()
     };
     let config = config_cow.as_ref();
-    let ui = Ui::new(&config)
-        .unwrap_or_else(|error| early_exit(&config, error.into()));
+    let ui = Ui::new(config)
+        .unwrap_or_else(|error| early_exit(config, error.into()));
 
     if let Ok(true) = config.get_bool(b"rhg", b"fallback-immediately") {
         exit(
@@ -360,7 +360,7 @@
         repo_result.as_ref(),
         config,
     );
-    simple_exit(&ui, &config, result)
+    simple_exit(&ui, config, result)
 }
 
 fn main() -> ! {
@@ -422,7 +422,7 @@
             }
             Some(executable) => executable,
         };
-        let executable_path = get_path_from_bytes(&executable);
+        let executable_path = get_path_from_bytes(executable);
         let this_executable = args.next().expect("exepcted argv[0] to exist");
         if executable_path == &PathBuf::from(this_executable) {
             // Avoid spawning infinitely many processes until resource
--- a/rust/rhg/src/utils/path_utils.rs	Fri Jan 06 18:52:04 2023 +0100
+++ b/rust/rhg/src/utils/path_utils.rs	Mon Jan 09 17:40:03 2023 +0100
@@ -23,7 +23,7 @@
         let repo_root = repo.working_directory_path();
         let repo_root = cwd.join(repo_root); // Make it absolute
         let repo_root_hgpath =
-            HgPathBuf::from(get_bytes_from_path(repo_root.to_owned()));
+            HgPathBuf::from(get_bytes_from_path(&repo_root));
 
         if let Ok(cwd_relative_to_repo) = cwd.strip_prefix(&repo_root) {
             // The current directory is inside the repo, so we can work with