gnostr_asyncgit/sync/
repository.rs

1use std::{
2    cell::RefCell,
3    path::{Path, PathBuf},
4};
5
6use git2::{Repository, RepositoryOpenFlags};
7
8use crate::error::Result;
9
10///
11pub type RepoPathRef = RefCell<RepoPath>;
12
13///
14#[derive(Clone, Debug)]
15pub enum RepoPath {
16    ///
17    Path(PathBuf),
18    ///
19    Workdir {
20        ///
21        gitdir: PathBuf,
22        ///
23        workdir: PathBuf,
24    },
25}
26
27impl RepoPath {
28    ///
29    pub fn gitpath(&self) -> &Path {
30        match self {
31            Self::Path(p) => p.as_path(),
32            Self::Workdir { gitdir, .. } => gitdir.as_path(),
33        }
34    }
35
36    ///
37    pub fn workdir(&self) -> Option<&Path> {
38        match self {
39            Self::Path(_) => None,
40            Self::Workdir { workdir, .. } => Some(workdir.as_path()),
41        }
42    }
43
44    ///
45    pub fn as_path(&self) -> &Path {
46        self.gitpath()
47    }
48}
49
50impl From<&str> for RepoPath {
51    fn from(p: &str) -> Self {
52        Self::Path(PathBuf::from(p))
53    }
54}
55
56pub fn repo(repo_path: &RepoPath) -> Result<Repository> {
57    let repo = Repository::open_ext(
58        repo_path.gitpath(),
59        RepositoryOpenFlags::empty(),
60        Vec::<&Path>::new(),
61    )?;
62
63    if let Some(workdir) = repo_path.workdir() {
64        repo.set_workdir(workdir, false)?;
65    }
66
67    Ok(repo)
68}