paris/formatter/keys/
key.rs1use crate::formatter::color::Color;
2use crate::formatter::icons::LogIcon;
3use crate::formatter::keys::FromKey;
4use crate::formatter::style::Style;
5use std::fmt::{Display, Formatter, Result};
6
7pub struct Key<'a> {
8 contents: &'a str,
9 clean: String,
10}
11
12impl<'a> Key<'a> {
13 pub fn new(value: &'a str) -> Self {
14 Self {
15 contents: value,
16 clean: Self::clean(value),
17 }
18 }
19
20 pub fn contents(&self) -> &str {
21 self.contents
22 }
23
24 pub fn as_color(&self) -> Option<String> {
25 Color::from_key(&self.clean)
26 }
27
28 pub fn as_style(&self) -> Option<String> {
29 Style::from_key(&self.clean)
30 }
31
32 pub fn as_icon(&self) -> Option<String> {
33 LogIcon::from_key(&self.clean)
34 }
35
36 pub fn to_ansi(&self) -> String {
37 let mut content: String = self.contents().to_owned();
38
39 if let Some(c) = self.as_color() {
40 content = c;
41 }
42
43 if let Some(s) = self.as_style() {
44 content = s;
45 }
46
47 if let Some(i) = self.as_icon() {
48 content = i;
49 }
50
51 content
52 }
53
54 fn clean(key: &str) -> String {
58 let key = key.trim_matches(|c| c == '<' || c == '>');
59
60 if key.contains(' ') {
63 return key.to_string();
64 }
65
66 key.chars()
67 .map(|c| match c {
68 '_' => ' ',
69 '-' => ' ',
70 _ => c,
71 })
72 .collect()
73 }
74}
75
76impl Display for Key<'_> {
77 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
78 write!(f, "{}", self.contents)
79 }
80}
81
82#[cfg(test)]
83mod tests {
84 use super::*;
85
86 #[test]
87 fn cleanup() {
88 let color = "<on_bright-green>";
89
90 let clean = Key::clean(color);
91
92 assert_eq!("on bright green", clean);
93 }
94}