From c48bc2a264eda3efbcd74bbb74f7a64081bf93c4 Mon Sep 17 00:00:00 2001 From: Jiahao XU Date: Thu, 3 Nov 2022 21:11:43 +1100 Subject: [PATCH] Fix crate `normalize-path` (#508) * Impl new function `NormalizePath::is_normalized` * Always normalize and ret `PathBuf` in `NormalizePath::normalize` Signed-off-by: Jiahao XU --- crates/binstalk/src/bins.rs | 4 +-- crates/normalize-path/src/lib.rs | 48 +++++++++++++++++--------------- 2 files changed, 27 insertions(+), 25 deletions(-) diff --git a/crates/binstalk/src/bins.rs b/crates/binstalk/src/bins.rs index 221cfc59..8961d89d 100644 --- a/crates/binstalk/src/bins.rs +++ b/crates/binstalk/src/bins.rs @@ -113,11 +113,11 @@ impl BinFile { if !is_valid_path(&path_normalized) { return Err(BinstallError::InvalidSourceFilePath { - path: path_normalized.into_owned(), + path: path_normalized, }); } - data.bin_path.join(path_normalized.as_ref()) + data.bin_path.join(&path_normalized) }; // Destination at install dir + base-name{.extension} diff --git a/crates/normalize-path/src/lib.rs b/crates/normalize-path/src/lib.rs index 20e9ea68..42e2b8ec 100644 --- a/crates/normalize-path/src/lib.rs +++ b/crates/normalize-path/src/lib.rs @@ -18,10 +18,7 @@ //! ); //! ``` -use std::{ - borrow::Cow, - path::{Component, Path, PathBuf}, -}; +use std::path::{Component, Path, PathBuf}; /// Extension trait to add `normalize_path` to std's [`Path`]. pub trait NormalizePath { @@ -30,28 +27,19 @@ pub trait NormalizePath { /// All redundant separator and up-level references are collapsed. /// /// However, this does not resolve links. - fn normalize(&self) -> Cow<'_, Path>; -} + fn normalize(&self) -> PathBuf; -fn is_normalized(path: &Path) -> bool { - for component in path.components() { - match component { - Component::CurDir | Component::ParentDir => { - return false; - } - _ => continue, - } - } - - true + /// Return `true` if the path is normalized. + /// + /// # Quirk + /// + /// If the path does not start with `./` but contains `./` in the middle, + /// then this function might returns `true`. + fn is_normalized(&self) -> bool; } impl NormalizePath for Path { - fn normalize(&self) -> Cow<'_, Path> { - if is_normalized(self) { - return Cow::Borrowed(self); - } - + fn normalize(&self) -> PathBuf { let mut components = self.components().peekable(); let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek() { let buf = PathBuf::from(c.as_os_str()); @@ -76,6 +64,20 @@ impl NormalizePath for Path { } } } - Cow::Owned(ret) + + ret + } + + fn is_normalized(&self) -> bool { + for component in self.components() { + match component { + Component::CurDir | Component::ParentDir => { + return false; + } + _ => continue, + } + } + + true } }