use std::io;
use std::path::{Component, Path, PathBuf};
use super::DiscoverError;
pub(super) fn canonicalize(path: &Path) -> Result<PathBuf, DiscoverError> {
std::fs::canonicalize(path).map_err(|source| DiscoverError::Io {
path: path.to_path_buf(),
source,
})
}
pub(super) fn normalize_for_containment(path: &Path) -> Result<PathBuf, DiscoverError> {
match std::fs::canonicalize(path) {
Ok(canonical) => Ok(canonical),
Err(err) if err.kind() == io::ErrorKind::NotFound => {
let absolute = std::path::absolute(path).map_err(|source| DiscoverError::Io {
path: path.to_path_buf(),
source,
})?;
Ok(lexical_normalize(&absolute))
}
Err(source) => Err(DiscoverError::Io {
path: path.to_path_buf(),
source,
}),
}
}
fn lexical_normalize(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for component in path.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
out.pop();
}
other => out.push(other.as_os_str()),
}
}
out
}
pub(super) fn ensure_contained(
workspace_root: &Path,
repository_root: &Path,
) -> Result<(), DiscoverError> {
if workspace_root.starts_with(repository_root) {
Ok(())
} else {
Err(DiscoverError::WorkspaceRootOutsideRepository {
workspace_root: workspace_root.to_path_buf(),
repository_root: repository_root.to_path_buf(),
})
}
}
pub(super) fn repo_relative(dir: &Path, repository_root: &Path) -> Result<String, DiscoverError> {
let relative =
dir.strip_prefix(repository_root)
.map_err(|_| DiscoverError::InvalidMetadata {
message: format!(
"package directory {} is outside the repository root {}",
dir.display(),
repository_root.display()
),
})?;
let text = relative
.to_str()
.ok_or_else(|| DiscoverError::InvalidMetadata {
message: format!("package directory {} is not valid UTF-8", dir.display()),
})?;
Ok(text.replace('\\', "/"))
}