From 6a96e84a15e3ea598356e4fcad23ac4b2690dd1e Mon Sep 17 00:00:00 2001 From: Fraser Li Date: Mon, 26 Feb 2024 22:21:00 +1100 Subject: [PATCH] fix(git_branch): fall back to "HEAD" when there is no current branch (#5768) * fix(git_branch): fall back to "HEAD" when there is no current branch * test(git_branch): add test for branch fallback on detached HEAD --- src/modules/git_branch.rs | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/src/modules/git_branch.rs b/src/modules/git_branch.rs index f57b8657..cda4065c 100644 --- a/src/modules/git_branch.rs +++ b/src/modules/git_branch.rs @@ -30,13 +30,13 @@ pub fn module<'a>(context: &'a Context) -> Option> { return None; } - let branch_name = repo.branch.as_ref()?; + let branch_name = repo.branch.as_deref().unwrap_or("HEAD"); let mut graphemes: Vec<&str> = branch_name.graphemes(true).collect(); if config .ignore_branches .iter() - .any(|ignored| branch_name.eq(ignored)) + .any(|&ignored| branch_name.eq(ignored)) { return None; } @@ -428,6 +428,29 @@ mod tests { remote_dir.close() } + #[test] + fn test_branch_fallback_on_detached() -> io::Result<()> { + let repo_dir = fixture_repo(FixtureProvider::Git)?; + + create_command("git")? + .args(["checkout", "@~1"]) + .current_dir(repo_dir.path()) + .output()?; + + let actual = ModuleRenderer::new("git_branch") + .config(toml::toml! { + [git_branch] + format = "$branch" + }) + .path(repo_dir.path()) + .collect(); + + let expected = Some("HEAD".into()); + + assert_eq!(expected, actual); + repo_dir.close() + } + // This test is not possible until we switch to `git status --porcelain` // where we can mock the env for the specific git process. This is because // git2 does not care about our mocking and when we set the real `GIT_DIR`