diff --git a/src/context.rs b/src/context.rs index 61e9125f..27feac0f 100644 --- a/src/context.rs +++ b/src/context.rs @@ -136,7 +136,11 @@ impl<'a> Context<'a> { pub fn get_repo(&self) -> Result<&Repo, std::io::Error> { self.repo .get_or_try_init(|| -> Result { - let repository = Repository::discover(&self.current_dir).ok(); + let repository = if env::var("GIT_DIR").is_ok() { + Repository::open_from_env().ok() + } else { + Repository::discover(&self.current_dir).ok() + }; let branch = repository .as_ref() .and_then(|repo| get_current_branch(repo)); diff --git a/tests/testsuite/git_branch.rs b/tests/testsuite/git_branch.rs index e2977a6d..2f5bf901 100644 --- a/tests/testsuite/git_branch.rs +++ b/tests/testsuite/git_branch.rs @@ -1,6 +1,7 @@ use ansi_term::Color; use remove_dir_all::remove_dir_all; use std::io; +use std::path::Path; use std::process::Command; use crate::common::{self, TestCommand}; @@ -122,6 +123,29 @@ fn test_works_with_unborn_master() -> io::Result<()> { remove_dir_all(repo_dir) } +#[test] +fn test_git_dir_env_variable() -> io::Result<()> { + let repo_dir = tempfile::tempdir()?.into_path(); + + Command::new("git") + .args(&["init"]) + .current_dir(&repo_dir) + .output()?; + + let output = common::render_module("git_branch") + .env("GIT_DIR", Path::new(&repo_dir).join(".git")) + .output() + .unwrap(); + let actual = String::from_utf8(output.stdout).unwrap(); + + let expected = format!( + "on {} ", + Color::Purple.bold().paint(format!("\u{e0a0} {}", "master")), + ); + assert_eq!(expected, actual); + remove_dir_all(repo_dir) +} + fn test_truncate_length( branch_name: &str, truncate_length: i64,