Skip to content

Commit

Permalink
fix(git_branch): fall back to "HEAD" when there is no current branch (#…
Browse files Browse the repository at this point in the history
…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
  • Loading branch information
fraserli committed Feb 26, 2024
1 parent aaaf3d8 commit 6a96e84
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions src/modules/git_branch.rs
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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`
Expand Down

0 comments on commit 6a96e84

Please sign in to comment.