use std::path::{Path, PathBuf};
use std::sync::Arc;
use super::error::RustProjectError;
use crate::resolution::path_normalization::RelativePathError;
use crate::resolution::paths::RootError;
pub(super) use crate::resolution::paths::path_text;
pub(super) fn canonical_root(root: &Path) -> Result<PathBuf, RustProjectError> {
crate::resolution::paths::canonical_root(root).map_err(|error| RustProjectError::InvalidRoot {
path: path_text(root),
reason: RootError::reason(error),
})
}
pub(super) fn relative_text(root: &Path, path: &Path) -> Result<Box<str>, RustProjectError> {
crate::resolution::path_normalization::relative_text(root, path)
.map_err(|error| unrelative(error, root, path))
}
pub(super) fn relative_shared(root: &Path, path: &Path) -> Result<Arc<str>, RustProjectError> {
crate::resolution::path_normalization::relative_shared(root, path)
.map_err(|error| unrelative(error, root, path))
}
pub(super) fn unrelative(error: RelativePathError, root: &Path, path: &Path) -> RustProjectError {
match error {
RelativePathError::OutsideRoot => RustProjectError::OutOfRoot {
path: path_text(path),
root: path_text(root),
},
RelativePathError::NonUtf8 => RustProjectError::NonUtf8Path {
path: path_text(path),
},
}
}
pub(super) fn contains(root: &Path, path: &Path) -> bool {
path.starts_with(root)
}
pub(super) fn read_directory(path: &Path) -> Result<Box<[std::fs::DirEntry]>, RustProjectError> {
let entries = std::fs::read_dir(path).map_err(|source| RustProjectError::ManifestRead {
path: path_text(path),
source,
})?;
entries
.collect::<Result<Box<[_]>, _>>()
.map_err(|source| RustProjectError::ManifestRead {
path: path_text(path),
source,
})
}
pub(super) fn canonical_manifest(directory: &Path) -> Result<Option<PathBuf>, RustProjectError> {
let manifest = directory.join("Cargo.toml");
match std::fs::canonicalize(&manifest) {
Ok(canonical) => Ok(canonical.is_file().then_some(canonical)),
Err(source) if source.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(source) => Err(RustProjectError::ManifestRead {
path: path_text(&manifest),
source,
}),
}
}