Add support for hex colors

This commit is contained in:
Barnabas 2020-12-29 16:19:46 +01:00 committed by Ferran Basora
parent b97519170b
commit 25d410497e
4 changed files with 31 additions and 0 deletions

1
Cargo.lock generated
View File

@ -164,6 +164,7 @@ version = "0.5.0"
dependencies = [ dependencies = [
"base64", "base64",
"clap", "clap",
"lazy_static",
"regex", "regex",
"termion", "termion",
"unicode-width", "unicode-width",

View File

@ -14,6 +14,7 @@ regex = "1.3.1"
clap = "2.33.0" clap = "2.33.0"
base64 = "0.11.0" base64 = "0.11.0"
unicode-width = "0.1.7" unicode-width = "0.1.7"
lazy_static = "1.4.0"
[[bin]] [[bin]]
name = "thumbs" name = "thumbs"

View File

@ -1,6 +1,19 @@
use regex::Regex;
use termion::color; use termion::color;
pub fn get_color(color_name: &str) -> Box<dyn color::Color> { pub fn get_color(color_name: &str) -> Box<dyn color::Color> {
lazy_static! {
static ref RGB: Regex = Regex::new(r"#([[:xdigit:]]{2})([[:xdigit:]]{2})([[:xdigit:]]{2})").unwrap();
}
if let Some(captures) = RGB.captures(color_name) {
let r = u8::from_str_radix(captures.get(1).unwrap().as_str(), 16).unwrap();
let g = u8::from_str_radix(captures.get(2).unwrap().as_str(), 16).unwrap();
let b = u8::from_str_radix(captures.get(3).unwrap().as_str(), 16).unwrap();
return Box::new(color::Rgb(r, g, b));
}
match color_name { match color_name {
"black" => Box::new(color::Black), "black" => Box::new(color::Black),
"red" => Box::new(color::Red), "red" => Box::new(color::Red),
@ -27,6 +40,20 @@ mod tests {
assert_eq!(text1, text2); assert_eq!(text1, text2);
} }
#[test]
fn parse_rgb() {
let text1 = println!("{}{}", color::Fg(&*get_color("#1b1cbf")), "foo");
let text2 = println!("{}{}", color::Fg(color::Rgb(27, 28, 191)), "foo");
assert_eq!(text1, text2);
}
#[test]
#[should_panic]
fn parse_invalid_rgb() {
println!("{}{}", color::Fg(&*get_color("#1b1cbj")), "foo");
}
#[test] #[test]
#[should_panic] #[should_panic]
fn no_match_color() { fn no_match_color() {

View File

@ -1,3 +1,5 @@
#[macro_use]
extern crate lazy_static;
extern crate base64; extern crate base64;
extern crate clap; extern crate clap;
extern crate termion; extern crate termion;