allow user to use hex colors in config (#486)

This commit is contained in:
Darren Schroeder 2021-12-13 09:02:54 -06:00 committed by GitHub
parent ee6ab17fde
commit 3701fd1d76
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -15,6 +15,15 @@ use std::collections::HashMap;
// } // }
pub fn lookup_ansi_color_style(s: String) -> Style { pub fn lookup_ansi_color_style(s: String) -> Style {
if s.starts_with('#') {
match color_from_hex(&s) {
Ok(c) => match c {
Some(c) => c.normal(),
None => Style::default(),
},
Err(_) => Style::default(),
}
} else {
match s.as_str() { match s.as_str() {
"g" | "green" => Color::Green.normal(), "g" | "green" => Color::Green.normal(),
"gb" | "green_bold" => Color::Green.bold(), "gb" | "green_bold" => Color::Green.bold(),
@ -82,6 +91,22 @@ pub fn lookup_ansi_color_style(s: String) -> Style {
"wst" | "white_strike" => Color::White.strikethrough(), "wst" | "white_strike" => Color::White.strikethrough(),
_ => Color::White.normal(), _ => Color::White.normal(),
} }
}
}
fn color_from_hex(hex_color: &str) -> std::result::Result<Option<Color>, std::num::ParseIntError> {
// right now we only allow hex colors with hashtag and 6 characters
let trimmed = hex_color.trim_matches('#');
if trimmed.len() != 6 {
Ok(None)
} else {
// make a nu_ansi_term::Color::Rgb color by converting hex to decimal
Ok(Some(Color::Rgb(
u8::from_str_radix(&trimmed[..2], 16)?,
u8::from_str_radix(&trimmed[2..4], 16)?,
u8::from_str_radix(&trimmed[4..6], 16)?,
)))
}
} }
// TODO: i'm not sure how this ever worked but leaving it in case it's used elsewhere but not implemented yet // TODO: i'm not sure how this ever worked but leaving it in case it's used elsewhere but not implemented yet