1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
mod init {
    use crate::Repository;
    use std::path::Path;

    impl Repository {
        /// Really just a sketch at this point to help guide the API.
        pub fn create_and_init(directory: impl AsRef<Path>) -> Result<Self, crate::init::Error> {
            // TODO: proper error
            crate::init::repository(directory.as_ref())?;
            Ok(Repository::discover(directory).unwrap()) // TODO: a specialized method without discovery
        }
    }
}

pub mod discover {
    use crate::{path::discover, Repository};
    use quick_error::quick_error;
    use std::path::Path;

    quick_error! {
        #[derive(Debug)]
        pub enum Error {
            Discover(err: discover::existing::Error) {
                display("Could not find a valid git repository directory")
                from()
                source(err)
            }
            ObjectStoreInitialization(err: git_odb::linked::init::Error) {
                display("Could not initialize the object database")
                from()
                source(err)
            }
        }
    }

    impl Repository {
        pub fn discover(directory: impl AsRef<Path>) -> Result<Self, Error> {
            let path = discover::existing(directory)?;
            let (git_dir, working_tree) = match path {
                crate::Path::WorkingTree(working_tree) => (working_tree.join(".git"), Some(working_tree)),
                crate::Path::Repository(repository) => (repository, None),
            };
            Ok(Repository {
                odb: git_odb::linked::Store::at(git_dir.join("objects"))?,
                refs: git_ref::file::Store::at(
                    git_dir,
                    if working_tree.is_none() {
                        git_ref::file::WriteReflog::Disable
                    } else {
                        git_ref::file::WriteReflog::Normal
                    },
                ),
                working_tree,
            })
        }
    }
}