Skip to main content

anza_xtask/utils/
git.rs

1use {
2    anyhow::{anyhow, Result},
3    std::{path::PathBuf, process::Command},
4};
5
6pub fn get_git_root_path() -> Result<PathBuf> {
7    let output = Command::new("git")
8        .args(["rev-parse", "--show-toplevel"])
9        .output()
10        .map_err(|e| anyhow!("failed to get git root path, error: {e}"))?;
11    let root = String::from_utf8_lossy(&output.stdout).trim().to_string();
12    Ok(PathBuf::from(root))
13}
14
15#[cfg(test)]
16mod tests {
17    use {super::*, pretty_assertions::assert_eq, serial_test::serial, std::fs};
18
19    #[test]
20    #[serial]
21    fn test_get_git_root_path() {
22        let temp_dir = tempfile::tempdir().unwrap();
23
24        std::env::set_current_dir(temp_dir.path()).unwrap();
25        Command::new("git").args(["init"]).output().unwrap();
26
27        let root_path = get_git_root_path().unwrap();
28
29        let canonicalized_root_path = fs::canonicalize(root_path).unwrap();
30        let canonicalized_temp_dir_path = fs::canonicalize(temp_dir.path()).unwrap();
31
32        assert_eq!(canonicalized_root_path, canonicalized_temp_dir_path);
33    }
34}