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
This commit is contained in:
Fraser Li 2024-02-26 22:21:00 +11:00 committed by GitHub
parent aaaf3d82e8
commit 6a96e84a15
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -30,13 +30,13 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
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`