use std::env;
use std::path::{Path, PathBuf};
pub fn get_project_root() -> Result<PathBuf, String> {
if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
let project_root = Path::new(&manifest_dir).to_path_buf();
println!("Get the project root directory with CARGO_MANIFEST_DIR:{}", project_root.display());
return Ok(project_root);
}
if let Ok(current_exe) = env::current_exe() {
let mut project_root = current_exe;
project_root.pop(); project_root.pop(); println!("Deduce the project root directory through current_exe:{}", project_root.display());
return Ok(project_root);
}
if let Ok(mut current_dir) = env::current_dir() {
current_dir.pop();
println!("Deduce the project root directory through current_dir:{}", current_dir.display());
return Ok(current_dir);
}
Err("The project root directory cannot be obtained. Please check the running environment and project structure.".to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_project_root() {
match get_project_root() {
Ok(path) => {
assert!(path.exists(), "The project root directory does not exist:{}", path.display());
println!("The test is passed, the project root directory:{}", path.display());
}
Err(e) => panic!("Failed to get the project root directory:{e}"),
}
}
}