1
0
mirror of https://github.com/Llewellynvdm/starship.git synced 2024-11-16 18:15:16 +00:00
starship/src/modules/git_branch.rs

41 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> {
if context.repository.is_none() {
return None;
}
let repository = context.repository.as_ref().unwrap();
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")),
}
}