2019-04-27 02:07:07 +00:00
|
|
|
use ansi_term::Color;
|
2019-09-02 19:56:59 +00:00
|
|
|
use unicode_segmentation::UnicodeSegmentation;
|
2019-04-27 02:07:07 +00:00
|
|
|
|
2019-05-01 20:34:24 +00:00
|
|
|
use super::{Context, Module};
|
2019-04-27 02:07:07 +00:00
|
|
|
|
2019-07-19 20:18:52 +00:00
|
|
|
/// Creates a module with the Git branch in the current directory
|
2019-04-27 02:07:07 +00:00
|
|
|
///
|
|
|
|
/// Will display the branch name if the current directory is a git repo
|
2019-07-02 20:12:53 +00:00
|
|
|
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
|
2019-05-14 04:43:11 +00:00
|
|
|
const GIT_BRANCH_CHAR: &str = " ";
|
2019-07-31 23:48:51 +00:00
|
|
|
|
2019-07-02 20:12:53 +00:00
|
|
|
let mut module = context.new_module("git_branch")?;
|
2019-09-08 00:33:06 +00:00
|
|
|
|
|
|
|
let segment_color = module
|
|
|
|
.config_value_style("style")
|
|
|
|
.unwrap_or_else(|| Color::Purple.bold());
|
2019-05-14 04:43:11 +00:00
|
|
|
module.set_style(segment_color);
|
|
|
|
module.get_prefix().set_value("on ");
|
2019-04-27 02:07:07 +00:00
|
|
|
|
2019-09-02 19:56:59 +00:00
|
|
|
let unsafe_truncation_length = module
|
|
|
|
.config_value_i64("truncation_length")
|
|
|
|
.unwrap_or(std::i64::MAX);
|
|
|
|
let truncation_symbol = get_graphemes(
|
|
|
|
module.config_value_str("truncation_symbol").unwrap_or("…"),
|
|
|
|
1,
|
|
|
|
);
|
|
|
|
|
2019-07-19 20:18:52 +00:00
|
|
|
module.new_segment("symbol", GIT_BRANCH_CHAR);
|
2019-09-02 19:56:59 +00:00
|
|
|
|
|
|
|
// TODO: Once error handling is implemented, warn the user if their config
|
|
|
|
// truncation length is nonsensical
|
|
|
|
let len = if unsafe_truncation_length <= 0 {
|
|
|
|
log::debug!(
|
|
|
|
"[WARN]: \"truncation_length\" should be a positive value, found {}",
|
|
|
|
unsafe_truncation_length
|
|
|
|
);
|
|
|
|
std::usize::MAX
|
|
|
|
} else {
|
|
|
|
unsafe_truncation_length as usize
|
|
|
|
};
|
|
|
|
let branch_name = context.branch_name.as_ref()?;
|
|
|
|
let truncated_graphemes = get_graphemes(&branch_name, len);
|
|
|
|
// The truncation symbol should only be added if we truncated
|
|
|
|
let truncated_and_symbol = if len < graphemes_len(&branch_name) {
|
|
|
|
truncated_graphemes + &truncation_symbol
|
|
|
|
} else {
|
|
|
|
truncated_graphemes
|
|
|
|
};
|
|
|
|
|
|
|
|
module.new_segment("name", &truncated_and_symbol);
|
2019-04-27 02:07:07 +00:00
|
|
|
|
2019-05-14 04:43:11 +00:00
|
|
|
Some(module)
|
2019-04-27 02:07:07 +00:00
|
|
|
}
|
2019-09-02 19:56:59 +00:00
|
|
|
|
|
|
|
fn get_graphemes(text: &str, length: usize) -> String {
|
|
|
|
UnicodeSegmentation::graphemes(text, true)
|
|
|
|
.take(length)
|
|
|
|
.collect::<Vec<&str>>()
|
|
|
|
.concat()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn graphemes_len(text: &str) -> usize {
|
|
|
|
UnicodeSegmentation::graphemes(&text[..], true).count()
|
|
|
|
}
|