Skip to main content

quanttide_devops/source/git/
repo.rs

1//! Git 仓库检测:判断路径是否为 Git 仓库。
2
3use std::path::Path;
4
5/// 判断路径是否为 git 仓库(存在 `.git` 目录或文件)。
6///
7/// `.git` 文件表示该目录是一个 git 子模块的工作树。
8pub fn is_git_repo(path: &Path) -> bool {
9    let git_dir = path.join(".git");
10    git_dir.is_dir() || git_dir.is_file()
11}
12
13#[cfg(test)]
14mod tests {
15    use super::*;
16
17    #[test]
18    fn test_is_git_repo_with_dot_git_dir() {
19        let d = tempfile::tempdir().unwrap();
20        std::fs::create_dir(d.path().join(".git")).unwrap();
21        assert!(is_git_repo(d.path()));
22    }
23
24    #[test]
25    fn test_is_git_repo_with_dot_git_file() {
26        let d = tempfile::tempdir().unwrap();
27        std::fs::write(d.path().join(".git"), "gitdir: ../.git/modules/foo").unwrap();
28        assert!(is_git_repo(d.path()));
29    }
30
31    #[test]
32    fn test_is_git_repo_false() {
33        let d = tempfile::tempdir().unwrap();
34        assert!(!is_git_repo(d.path()));
35    }
36
37    #[test]
38    fn test_is_git_repo_empty_dir() {
39        let d = tempfile::tempdir().unwrap();
40        std::fs::create_dir(d.path().join("empty")).unwrap();
41        assert!(!is_git_repo(d.path()));
42    }
43
44    #[test]
45    fn test_is_git_repo_non_existent_path() {
46        let d = tempfile::tempdir().unwrap();
47        let non_existent = d.path().join("does_not_exist");
48        assert!(!is_git_repo(&non_existent));
49    }
50}