Skip to main content

quanttide_devops/source/
git_repo.rs

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