use std::env;
use std::path::PathBuf;
const ROOT_MARKERS: &[&str] = &[
"resQ.sln",
"package.json",
"Cargo.toml",
"pyproject.toml",
".git",
];
pub fn find_project_root() -> PathBuf {
let cwd = env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
for ancestor in cwd.ancestors() {
for marker in ROOT_MARKERS {
if ancestor.join(marker).exists() {
return ancestor.to_path_buf();
}
}
}
cwd
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::tempdir;
#[test]
fn test_find_project_root() -> anyhow::Result<()> {
let dir = tempdir()?;
let root = dir.path();
fs::write(root.join("resQ.sln"), "")?;
let sub = root.join("a/b/c");
fs::create_dir_all(&sub)?;
let original_cwd = env::current_dir()?;
env::set_current_dir(&sub)?;
let found_root = find_project_root();
env::set_current_dir(original_cwd)?;
assert_eq!(found_root.canonicalize()?, root.canonicalize()?);
Ok(())
}
}