1
0
mirror of https://github.com/Llewellynvdm/starship.git synced 2024-06-02 00:20:51 +00:00

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
This commit is contained in:
Walther Chen 2020-07-05 13:22:14 -04:00 committed by GitHub
parent 021d82a224
commit 489838e6a2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 4 deletions

View File

@ -321,8 +321,19 @@ fn get_current_branch(repository: &Repository) -> Option<String> {
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
};

View File

@ -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)