Fix crate normalize-path (#508)

* Impl new function `NormalizePath::is_normalized`
* Always normalize and ret `PathBuf` in `NormalizePath::normalize`

Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
This commit is contained in:
Jiahao XU 2022-11-03 21:11:43 +11:00 committed by GitHub
parent 25a4ceb050
commit c48bc2a264
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 25 deletions

View file

@ -113,11 +113,11 @@ impl BinFile {
if !is_valid_path(&path_normalized) { if !is_valid_path(&path_normalized) {
return Err(BinstallError::InvalidSourceFilePath { 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} // Destination at install dir + base-name{.extension}

View file

@ -18,10 +18,7 @@
//! ); //! );
//! ``` //! ```
use std::{ use std::path::{Component, Path, PathBuf};
borrow::Cow,
path::{Component, Path, PathBuf},
};
/// Extension trait to add `normalize_path` to std's [`Path`]. /// Extension trait to add `normalize_path` to std's [`Path`].
pub trait NormalizePath { pub trait NormalizePath {
@ -30,28 +27,19 @@ pub trait NormalizePath {
/// All redundant separator and up-level references are collapsed. /// All redundant separator and up-level references are collapsed.
/// ///
/// However, this does not resolve links. /// However, this does not resolve links.
fn normalize(&self) -> Cow<'_, Path>; fn normalize(&self) -> PathBuf;
}
fn is_normalized(path: &Path) -> bool { /// Return `true` if the path is normalized.
for component in path.components() { ///
match component { /// # Quirk
Component::CurDir | Component::ParentDir => { ///
return false; /// If the path does not start with `./` but contains `./` in the middle,
} /// then this function might returns `true`.
_ => continue, fn is_normalized(&self) -> bool;
}
}
true
} }
impl NormalizePath for Path { impl NormalizePath for Path {
fn normalize(&self) -> Cow<'_, Path> { fn normalize(&self) -> PathBuf {
if is_normalized(self) {
return Cow::Borrowed(self);
}
let mut components = self.components().peekable(); let mut components = self.components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek() { let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek() {
let buf = PathBuf::from(c.as_os_str()); 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
} }
} }