diff options
author | Hendrik Rombach <h.rombach1@gmail.com> | 2020-05-06 11:19:53 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-05-06 11:19:53 +0200 |
commit | 108193103d45d2ebf3bbaab577ffb6ce83133eac (patch) | |
tree | 8d48c8c4c41f91ab56eb7c448946377a7b6e8e9b | |
parent | 4607e21fa6fa7165a8c820452e9ed214c6bd93c7 (diff) |
fix(git): show branch name in fresh repo (unborn master) (#1093)
* fix: branch_name in fresh repo (unborn master)
* test: add test for unborn branch_name fix
-rw-r--r-- | src/context.rs | 16 | ||||
-rw-r--r-- | tests/testsuite/git_branch.rs | 24 |
2 files changed, 38 insertions, 2 deletions
diff --git a/src/context.rs b/src/context.rs index bd8579588..049306e5c 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<String> { - 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 bea10a85e..e2977a6d4 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, |