git_wrapper/
bare_repo.rs

1use crate::AbsoluteDirPath;
2use crate::ConfigReadError;
3use crate::GenericRepository;
4use std::path::Path;
5use std::process::Command;
6
7/// Represents a bare repository
8#[derive(Debug)]
9pub struct BareRepository(AbsoluteDirPath);
10
11impl BareRepository {
12    /// # Panics
13    ///
14    /// When git execution fails
15    ///
16    /// # Errors
17    ///
18    /// Returns a string output when something goes horrible wrong
19    ///
20    #[inline]
21    pub fn create(path: &Path) -> Result<Self, String> {
22        let mut cmd = Command::new("git");
23        let out = cmd
24            .arg("init")
25            .arg("--bare")
26            .current_dir(&path)
27            .output()
28            .expect("Execute git-init(1)");
29
30        if out.status.success() {
31            let git_dir = path.try_into().map_err(|e| format!("{}", e))?;
32            Ok(Self(git_dir))
33        } else {
34            Err(String::from_utf8_lossy(&out.stderr).to_string())
35        }
36    }
37
38    /// Return config value for specified key
39    ///
40    /// # Errors
41    ///
42    /// When given invalid key or an invalid config file is read.
43    ///
44    /// # Panics
45    ///
46    /// Will panic if git exits with an unexpected error code. Expected codes are 0, 1 & 3.
47    #[inline]
48    pub fn config(&self, key: &str) -> Result<String, ConfigReadError> {
49        self.gen_config(key)
50    }
51
52    /// Returns a prepared git `Command` struct
53    #[must_use]
54    #[inline]
55    pub fn git(&self) -> Command {
56        let mut cmd = Command::new("git");
57        let git_dir = self.0 .0.to_str().expect("Convert to string");
58        cmd.env("GIT_DIR", git_dir);
59        cmd
60    }
61}
62
63impl GenericRepository for BareRepository {
64    fn gen_git(&self) -> Command {
65        self.git()
66    }
67}
68
69#[cfg(test)]
70mod test {
71    use tempfile::TempDir;
72    #[test]
73    fn bare_repo() {
74        let tmp_dir = TempDir::new().unwrap();
75        let repo_path = tmp_dir.path();
76        let _repo = crate::BareRepository::create(repo_path).expect("Created a bare repo");
77    }
78}