diff --git a/src/context.rs b/src/context.rs index bd857958..049306e5 100644 --- a/src/context.rs +++ b/src/context.rs @@ -3,7 +3,7 @@ use crate::module::Module; use crate::modules; use clap::ArgMatches; -use git2::{Repository, RepositoryState}; +use git2::{ErrorCode::UnbornBranch, Repository, RepositoryState}; use once_cell::sync::OnceCell; use std::collections::{HashMap, HashSet}; use std::env; @@ -312,7 +312,19 @@ impl<'a> ScanDir<'a> { } fn get_current_branch(repository: &Repository) -> Option { - let head = repository.head().ok()?; + let head = match repository.head() { + Ok(reference) => reference, + Err(e) => { + return if e.code() == UnbornBranch { + // HEAD should only be an unborn branch if the repository is fresh, + // in that case assume "master" + Some(String::from("master")) + } else { + None + }; + } + }; + let shorthand = head.shorthand(); shorthand.map(std::string::ToString::to_string) diff --git a/tests/testsuite/git_branch.rs b/tests/testsuite/git_branch.rs index bea10a85..e2977a6d 100644 --- a/tests/testsuite/git_branch.rs +++ b/tests/testsuite/git_branch.rs @@ -98,6 +98,30 @@ fn test_japanese_truncation() -> io::Result<()> { test_truncate_length("がんばってね", 4, "がんばっ", "…") } +#[test] +fn test_works_with_unborn_master() -> 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") + .arg("--path") + .arg(&repo_dir) + .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,