use std::error::Error;
use std::{
env,
fmt::{Display, Formatter},
fs,
path::{Path, PathBuf},
};
#[derive(Debug, Clone)]
pub(crate) struct CargoError {
msg: String,
}
impl CargoError {
pub(crate) fn new(msg: String) -> Self {
Self { msg }
}
}
impl Display for CargoError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "CargoError: {}", self.msg)
}
}
impl Error for CargoError {}
const MAX_ANCESTORS: u32 = 10;
pub(crate) fn crate_root() -> Result<PathBuf, CargoError> {
env::current_dir()
.ok()
.and_then(|mut wd| {
for _ in 0..MAX_ANCESTORS {
if contains_manifest(&wd) {
return Some(wd);
}
if !wd.pop() {
break;
}
}
None
})
.ok_or_else(|| {
CargoError::new("Failed to find directory containing Cargo.toml".to_string())
})
}
fn contains_manifest(path: &Path) -> bool {
fs::read_dir(path)
.map(|entries| {
entries
.filter_map(Result::ok)
.any(|ent| &ent.file_name() == "Cargo.toml")
})
.unwrap_or(false)
}