pub mod root;
use self::root::RootResolver;
use crate::{
config::Config,
error::{Error, Result},
git::GIT_DIR,
paths,
scan::{DirectoryScan, scan_directories},
};
use std::{
collections::{BTreeSet, HashMap, HashSet},
hash::BuildHasher,
path::{Path, PathBuf},
};
use tracing::info;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Project {
pub path: PathBuf,
pub markers: Vec<String>,
identity: PathBuf,
}
impl Project {
pub fn new(path: PathBuf, markers: Vec<String>) -> Result<Self> {
let identity = paths::normalize(&path)?;
Ok(Self::with_identity(path, identity, markers))
}
const fn with_identity(path: PathBuf, identity: PathBuf, markers: Vec<String>) -> Self {
Self {
path,
markers,
identity,
}
}
#[must_use]
pub fn identity(&self) -> &Path {
&self.identity
}
}
fn covering_ancestors(candidate: &Path) -> impl Iterator<Item = &Path> {
candidate.ancestors().skip(2)
}
#[must_use]
pub fn is_covered<S: BuildHasher>(candidate: &Path, known: &HashSet<PathBuf, S>) -> bool {
known.contains(candidate)
|| covering_ancestors(candidate).any(|ancestor| known.contains(ancestor))
}
#[derive(Debug)]
pub struct ProjectFinder {
config: Config,
root_resolver: RootResolver,
}
impl ProjectFinder {
#[must_use]
pub fn new(config: Config) -> Self {
let root_resolver = RootResolver::from_config(&config);
Self {
config,
root_resolver,
}
}
pub fn find_projects(&self) -> Result<Vec<PathBuf>> {
self.find_project_details()
.map(|projects| projects.into_iter().map(|project| project.path).collect())
}
pub fn find_project_details(&self) -> Result<Vec<Project>> {
let scan = self.scan()?;
let mut projects = scan
.git_repos
.iter()
.map(|repo| (repo.clone(), BTreeSet::from([GIT_DIR.to_owned()])))
.collect::<HashMap<_, BTreeSet<String>>>();
let mut candidates = self.resolve_marker_roots(&scan)?;
candidates.sort_unstable();
candidates.dedup();
for (candidate, marker) in candidates {
let root = covering_ancestors(&candidate)
.find(|ancestor| projects.contains_key(*ancestor))
.map(Path::to_path_buf);
projects
.entry(root.unwrap_or(candidate))
.or_default()
.insert(marker);
}
merge_projects_by_identity(projects)
}
fn scan(&self) -> Result<DirectoryScan> {
for path in &self.config.paths {
if !path.is_dir() {
return Err(Error::PathNotFound(path.clone()));
}
info!("Searching in: {}", path.display());
}
scan_directories(
&self.config.paths,
&self.config.marker_files,
self.config.depth,
&self.config.exclude,
)
}
fn resolve_marker_roots(&self, scan: &DirectoryScan) -> Result<Vec<(PathBuf, String)>> {
scan.marker_files
.iter()
.filter_map(|marker| {
let dir = marker.parent()?;
let name = marker.file_name()?.to_str()?;
Some(
self.root_resolver
.resolve(dir, name)
.map(|root| (root, name.to_owned())),
)
})
.collect()
}
}
fn merge_projects_by_identity(
projects: HashMap<PathBuf, BTreeSet<String>>,
) -> Result<Vec<Project>> {
let home = paths::home();
let mut projects_by_identity = HashMap::<PathBuf, (PathBuf, BTreeSet<String>)>::new();
for (path, markers) in projects {
let identity = paths::normalize(&path)?;
let Some((display_path, existing_markers)) = projects_by_identity.get_mut(&identity) else {
projects_by_identity.insert(identity, (path, markers));
continue;
};
if prefer_display_path(&path, display_path, home.as_deref()) {
*display_path = path;
}
existing_markers.extend(markers);
}
let mut projects = projects_by_identity
.into_iter()
.map(|(identity, (path, markers))| {
Project::with_identity(path, identity, markers.into_iter().collect())
})
.collect::<Vec<_>>();
projects.sort_unstable_by(|left, right| left.path.cmp(&right.path));
Ok(projects)
}
fn prefer_display_path(candidate: &Path, current: &Path, home: Option<&Path>) -> bool {
let candidate_is_home = home.is_some_and(|home| candidate.starts_with(home));
let current_is_home = home.is_some_and(|home| current.starts_with(home));
(candidate_is_home && !current_is_home)
|| (candidate_is_home == current_is_home && candidate < current)
}
#[cfg(test)]
mod tests {
use super::*;
use rstest::rstest;
#[rstest]
#[case("/repo", "/repo", true, "the same directory is already known")]
#[case("/repo/pkg", "/repo", false, "a direct child is a distinct project")]
#[case(
"/repo/pkg/inner",
"/repo",
true,
"anything deeper belongs to the parent"
)]
#[case("/other", "/repo", false, "unrelated trees never cover each other")]
fn coverage_rules(
#[case] candidate: &str,
#[case] known: &str,
#[case] expected: bool,
#[case] reason: &str,
) {
let known = HashSet::from([PathBuf::from(known)]);
assert_eq!(
is_covered(Path::new(candidate), &known),
expected,
"{reason}"
);
}
}