1
use git2::Repository;
2

            
3
/// Traverse the directory tree to find the repository root. Return
4
/// Ok(Repository) if found, or Error if not found.
5
6
pub fn open() -> Result<Repository, git2::Error> {
6
6
    let path = std::env::current_dir().expect("Failed to get current directory.");
7
6
    Repository::discover(path)
8
6
}
9

            
10
#[cfg(test)]
11
mod tests {
12
    use super::*;
13

            
14
    use std::{env, fs};
15

            
16
    use crate::test_utilities;
17

            
18
    #[test]
19
2
    fn test_open_current() {
20
2
        // GIVEN a repository
21
2
        let (_testdir, repo) = test_utilities::create_mock_repo();
22
2

            
23
2
        let original_dir = env::current_dir().unwrap();
24
2
        env::set_current_dir(repo.path()).unwrap();
25
2

            
26
2
        // WHEN the repository is opened
27
2
        let actual = open().unwrap();
28
2
        env::set_current_dir(original_dir).unwrap();
29
2

            
30
2
        // THEN it should match the expected repository
31
2
        assert_eq!(actual.path(), repo.path());
32
2
    }
33

            
34
    #[test]
35
2
    fn test_open_parent() {
36
2
        // GIVEN a repository with a subdirectory
37
2
        let (_testdir, repo) = test_utilities::create_mock_repo();
38
2
        let subdir = repo.path().join("subdir");
39
2
        fs::create_dir(&subdir).unwrap();
40
2

            
41
2
        let original_dir = env::current_dir().unwrap();
42
2
        env::set_current_dir(&subdir).unwrap();
43
2

            
44
2
        // WHEN the repository is opened
45
2
        let actual = open().unwrap();
46
2
        env::set_current_dir(original_dir).unwrap();
47
2

            
48
2
        // THEN it should match the expected repository
49
2
        assert_eq!(actual.path(), repo.path());
50
2
    }
51

            
52
    #[test]
53
2
    fn test_open_not_found() {
54
2
        // GIVEN a directory that is not a repository
55
2
        let testdir = tempfile::tempdir().unwrap();
56
2

            
57
2
        let original_dir = env::current_dir().unwrap();
58
2
        env::set_current_dir(testdir.path()).unwrap();
59
2

            
60
2
        // WHEN the repository is opened
61
2
        let actual = open();
62
2
        env::set_current_dir(original_dir).unwrap();
63
2

            
64
2
        // THEN it should not be found
65
2
        assert!(actual.is_err());
66
2
    }
67
}