1
0
mirror of https://github.com/Llewellynvdm/starship.git synced 2024-12-26 03:27:30 +00:00

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
This commit is contained in:
Hendrik Rombach 2020-05-06 11:19:53 +02:00 committed by GitHub
parent 4607e21fa6
commit 108193103d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 38 additions and 2 deletions

View File

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

View File

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