use std::path::{Path, PathBuf};
use crate::UserHome;
use crate::fs_probe::MAX_CONFIG_ANCESTOR_DEPTH;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RepositoryScope {
dirs: Vec<PathBuf>,
home: Option<UserHome>,
}
impl RepositoryScope {
#[must_use]
pub fn new(manifest_dir: &Path, root: &Path, home: Option<&Path>) -> Self {
let home = home.map(|home| UserHome::resolve(home.to_path_buf()));
Self::with_user_home(manifest_dir, root, home.as_ref())
}
#[must_use]
pub fn with_user_home(manifest_dir: &Path, root: &Path, home: Option<&UserHome>) -> Self {
let boundary = if manifest_dir.starts_with(root) {
root
} else {
manifest_dir
};
let mut dirs = Vec::new();
for dir in manifest_dir.ancestors().take(MAX_CONFIG_ANCESTOR_DEPTH) {
if home.is_some_and(|home| is_home(home, dir)) {
break;
}
dirs.push(dir.to_path_buf());
if dir == boundary {
break;
}
}
Self {
dirs,
home: home.cloned(),
}
}
#[must_use]
pub fn config_dirs(&self) -> Vec<PathBuf> {
self.dirs.clone()
}
#[must_use]
pub fn contains(&self, dir: &Path) -> bool {
self.dirs.iter().any(|candidate| candidate == dir)
}
#[must_use]
pub fn admits(&self, config_file: &Path, home_relative: &Path) -> bool {
let Some(dir) = home_relative
.components()
.try_fold(config_file, |path, _| path.parent())
else {
return false;
};
if !self.contains(dir) {
return false;
}
let Some(home) = &self.home else {
return true;
};
let home_copy = home.path().join(home_relative);
let same_file = std::fs::canonicalize(config_file)
.and_then(|real| std::fs::canonicalize(&home_copy).map(|home_real| real == home_real))
.unwrap_or(false);
!same_file
}
}
fn is_home(home: &UserHome, dir: &Path) -> bool {
home.is(dir) || std::fs::canonicalize(dir).is_ok_and(|real| home.is(&real))
}