Skip to content

Commit

Permalink
Fix crate normalize-path (rust-lang#508)
Browse files Browse the repository at this point in the history
* Impl new function `NormalizePath::is_normalized`
* Always normalize and ret `PathBuf` in `NormalizePath::normalize`

Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
  • Loading branch information
NobodyXu committed Nov 3, 2022
1 parent 25a4ceb commit c48bc2a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 25 deletions.
4 changes: 2 additions & 2 deletions crates/binstalk/src/bins.rs
Expand Up @@ -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}
Expand Down
48 changes: 25 additions & 23 deletions crates/normalize-path/src/lib.rs
Expand Up @@ -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 {
Expand All @@ -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 is_normalized(path: &Path) -> bool {
for component in path.components() {
match component {
Component::CurDir | Component::ParentDir => {
return false;
}
_ => continue,
}
}
fn normalize(&self) -> PathBuf;

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());
Expand All @@ -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
}
}

0 comments on commit c48bc2a

Please sign in to comment.