Skip to main content

workon/
get_repo.rs

1use git2::Repository;
2use std::{env, path::PathBuf};
3
4use crate::{error::Result, RepoError};
5
6/// Discover and open a bare repository from `path` (or the current directory).
7///
8/// If the discovered repository is a linked worktree, follows the `commondir`
9/// pointer back to the bare repo. Returns [`RepoError::NotBare`] if the
10/// repository is not bare.
11pub fn get_repo(path: Option<PathBuf>) -> Result<Repository> {
12    let path = match path {
13        Some(p) => p,
14        None => env::current_dir()?,
15    };
16
17    let mut repo = Repository::discover(path)?;
18
19    if repo.is_worktree() {
20        repo = Repository::discover(repo.commondir())?;
21    }
22
23    match repo.is_bare() {
24        true => Ok(repo),
25        false => Err(RepoError::NotBare(repo.path().display().to_string()).into()),
26    }
27}