1
0
mirror of https://github.com/Llewellynvdm/starship.git synced 2024-09-28 21:19:10 +00:00
starship/src/modules/git_branch.rs

39 lines
1.2 KiB
Rust
Raw Normal View History

use ansi_term::Color;
use git2::Repository;
2019-05-01 20:34:24 +00:00
use super::{Context, Module};
/// Creates a segment with the Git branch in the current directory
///
/// Will display the branch name if the current directory is a git repo
2019-05-01 20:34:24 +00:00
pub fn segment(context: &Context) -> Option<Module> {
2019-05-10 03:51:50 +00:00
let repo_root = context.repo_root.as_ref()?;
let repository = Repository::open(repo_root).ok()?;
2019-05-10 03:51:50 +00:00
match get_current_branch(&repository) {
Ok(branch_name) => {
2019-05-01 20:34:24 +00:00
const GIT_BRANCH_CHAR: &str = "";
let segment_color = Color::Purple.bold();
2019-05-01 20:34:24 +00:00
let mut module = Module::new("git_branch");
module.set_style(segment_color);
module.get_prefix().set_value("in ");
2019-05-01 20:34:24 +00:00
module.new_segment("branch_char", GIT_BRANCH_CHAR);
module.new_segment("branch_name", branch_name);
2019-05-01 20:34:24 +00:00
Some(module)
}
Err(_e) => None,
}
}
fn get_current_branch(repository: &Repository) -> Result<String, git2::Error> {
let head = repository.head()?;
let head_name = head.shorthand();
match head_name {
Some(name) => Ok(name.to_string()),
None => Err(git2::Error::from_str("No branch name found")),
}
}