From 489838e6a24ea1c08be6abe56d066724a1d59abd Mon Sep 17 00:00:00 2001 From: Walther Chen Date: Sun, 5 Jul 2020 13:22:14 -0400 Subject: [PATCH] feat: git branch: read from HEAD on newly initialized repo (#1336) * Git branch: read from HEAD on newly init repo On a newly initialized git repo, there are no branches created until a commit is made. Previously, starship handled this by having a default branch "master" for when branch `head` could not be read. However, if a user wants to set a different default branch name, that name won't appear on starship until a commit is made to the branch. If git2 provides a way to read the default branch name, we can use that, but at the moment it's not obvious how. For the moment, we can directly read `.git/HEAD`, which contains the name of the default branch head reference. This commit implements this strategy. Closes #1327 * update git_branch test from unborn master to unborn default * cargo fmt --- src/context.rs | 15 +++++++++++++-- tests/testsuite/git_branch.rs | 9 +++++++-- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/context.rs b/src/context.rs index 27feac0f..17a73c68 100644 --- a/src/context.rs +++ b/src/context.rs @@ -321,8 +321,19 @@ fn get_current_branch(repository: &Repository) -> Option { 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")) + // in that case read directly from `.git/HEAD` + let mut head_path = repository.path().to_path_buf(); + head_path.push("HEAD"); + + // get first line, then last path segment + fs::read_to_string(&head_path) + .ok()? + .lines() + .next()? + .trim() + .split('/') + .last() + .map(|r| r.to_owned()) } else { None }; diff --git a/tests/testsuite/git_branch.rs b/tests/testsuite/git_branch.rs index 2f5bf901..63cecdfe 100644 --- a/tests/testsuite/git_branch.rs +++ b/tests/testsuite/git_branch.rs @@ -100,7 +100,7 @@ fn test_japanese_truncation() -> io::Result<()> { } #[test] -fn test_works_with_unborn_master() -> io::Result<()> { +fn test_works_with_unborn_default_branch() -> io::Result<()> { let repo_dir = tempfile::tempdir()?.into_path(); Command::new("git") @@ -108,6 +108,11 @@ fn test_works_with_unborn_master() -> io::Result<()> { .current_dir(&repo_dir) .output()?; + Command::new("git") + .args(&["symbolic-ref", "HEAD", "refs/heads/main"]) + .current_dir(&repo_dir) + .output()?; + let output = common::render_module("git_branch") .arg("--path") .arg(&repo_dir) @@ -117,7 +122,7 @@ fn test_works_with_unborn_master() -> io::Result<()> { let expected = format!( "on {} ", - Color::Purple.bold().paint(format!("\u{e0a0} {}", "master")), + Color::Purple.bold().paint(format!("\u{e0a0} {}", "main")), ); assert_eq!(expected, actual); remove_dir_all(repo_dir)