-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstylizer.rs
249 lines (223 loc) Β· 9.39 KB
/
stylizer.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
use {
super::style::{Color, StyleAttributes as StyleBitflags},
eyre::Result,
};
pub mod instructions {
use {
super::{Color, Result, StyleBitflags},
bitflags::parser::{from_str, ParseError},
};
/// struct that holds the style information
pub struct StyledString {
pub fg: Option<Color>,
pub bg: Option<Color>,
pub attrs: StyleBitflags,
}
impl Default for StyledString {
fn default() -> Self {
StyledString {
fg: None,
bg: None,
attrs: StyleBitflags::empty(),
}
}
}
/// parses the instruction into a `StyledString`
pub fn parse(instructions: &str) -> Result<StyledString> {
let mut styled_string = StyledString::default();
if instructions.starts_with('+') {
// only attributes
styled_string.attrs = attributes_from_str(instructions.trim_start_matches('+'))
.map_err(|e| eyre::eyre!(e))?;
return Ok(styled_string);
}
// try to separate the colors from the attributes
let parts = instructions.split('+').collect::<Vec<_>>();
match parts.len() {
1 => {
// no attributes
let (fg, bg) = parse_color_instruction(parts[0].trim())?;
styled_string.fg = fg;
styled_string.bg = bg;
}
2 => {
// attributes
let (fg, bg) = parse_color_instruction(parts[0].trim())?;
styled_string.fg = fg;
styled_string.bg = bg;
styled_string.attrs = attributes_from_str(parts[1]).map_err(|e| eyre::eyre!(e))?;
}
_ => {
return Err(eyre::eyre!("Invalid instruction: {}", instructions));
}
};
Ok(styled_string)
}
/// parses the color part of an instruction into a tuple of fg and bg colors.
pub fn parse_color_instruction(instruction: &str) -> Result<(Option<Color>, Option<Color>)> {
if let Some(prefix) = instruction.strip_prefix("on ") {
return Ok((None, Some(Color::from_str(prefix)?)));
}
let colors: Vec<&str> = instruction.split(" on ").collect();
match colors.len() {
1 => {
// Only fg color is provided
Ok((Some(Color::from_str(colors[0])?), None))
}
2 => {
// Both fg and bg colors are provided
Ok((
Some(Color::from_str(colors[0])?),
Some(Color::from_str(colors[1])?),
))
}
_ => Err(eyre::eyre!("Invalid color instruction: {}", instruction)),
}
}
fn attributes_from_str(s: &str) -> Result<StyleBitflags, ParseError> {
from_str(s.to_uppercase().as_str())
}
}
/// π§ Β» Stylize Trait
/// --
///
/// `Trait` that extends `String` and `str` with the ability to stylize them
/// with ANSI color and attrs, using methods that return a new string with the given style.
#[rustfmt::skip]
pub trait Stylize {
/// Basic styling method, receives a styling instruction
/// see the `stylize` function for more information
fn stl(&self, instruction: &str) -> String;
/// π§ Β» makes the text **black**
fn black(&self) -> String { self.stl("black") }
/// π§ Β» makes the text **red**
fn red(&self) -> String { self.stl("red") }
/// π§ Β» makes the text **green**
fn green(&self) -> String { self.stl("green") }
/// π§ Β» makes the text **yellow**
fn yellow(&self) -> String { self.stl("yellow") }
/// π§ Β» makes the text **blue**
fn blue(&self) -> String { self.stl("blue") }
/// π§ Β» makes the text **magenta**
fn magenta(&self) -> String { self.stl("magenta") }
/// π§ Β» makes the text **cyan**
fn cyan(&self) -> String { self.stl("cyan") }
/// π§ Β» makes the text **white**
fn white(&self) -> String { self.stl("white") }
/// π§ Β» makes the text **bright black**
fn bright_black(&self) -> String { self.stl("bright-black") }
/// π§ Β» makes the text **bright red**
fn bright_red(&self) -> String { self.stl("bright-red") }
/// π§ Β» makes the text **bright green**
fn bright_green(&self) -> String { self.stl("bright-green") }
/// π§ Β» makes the text **bright yellow**
fn bright_yellow(&self) -> String { self.stl("bright-yellow") }
/// π§ Β» makes the text **bright blue**
fn bright_blue(&self) -> String { self.stl("bright-blue") }
/// π§ Β» makes the text **bright magenta**
fn bright_magenta(&self) -> String { self.stl("bright-magenta") }
/// π§ Β» makes the text **bright cyan**
fn bright_cyan(&self) -> String { self.stl("bright-cyan") }
/// π§ Β» makes the text **bright white**
fn bright_white(&self) -> String { self.stl("bright-white") }
/// π§ Β» makes the text colored after the **`rgb`** param (`#RRGGBB` format)
fn rgb(&self, rgb: &str) -> String { self.stl(rgb) }
/// π§ Β» makes the background of the text **black**
fn on_black(&self) -> String { self.stl("on black") }
/// π§ Β» makes the background of the text **red**
fn on_red(&self) -> String { self.stl("on red") }
/// π§ Β» makes the background of the text **green**
fn on_green(&self) -> String { self.stl("on green") }
/// π§ Β» makes the background of the text **yellow**
fn on_yellow(&self) -> String { self.stl("on yellow") }
/// π§ Β» makes the background of the text **blue**
fn on_blue(&self) -> String { self.stl("on blue") }
/// π§ Β» makes the background of the text **magenta**
fn on_magenta(&self) -> String { self.stl("on magenta") }
/// π§ Β» makes the background of the text **cyan**
fn on_cyan(&self) -> String { self.stl("on cyan") }
/// π§ Β» makes the background of the text **white**
fn on_white(&self) -> String { self.stl("on white") }
/// π§ Β» makes the background of the text **bright black**
fn on_bright_black(&self) -> String { self.stl("on bright-black") }
/// π§ Β» makes the background of the text **bright red**
fn on_bright_red(&self) -> String { self.stl("on bright-red") }
/// π§ Β» makes the background of the text **bright green**
fn on_bright_green(&self) -> String { self.stl("on bright-green") }
/// π§ Β» makes the background of the text **bright yellow**
fn on_bright_yellow(&self) -> String { self.stl("on bright-yellow") }
/// π§ Β» makes the background of the text **bright blue**
fn on_bright_blue(&self) -> String { self.stl("on bright-blue") }
/// π§ Β» makes the background of the text **bright magenta**
fn on_bright_magenta(&self) -> String { self.stl("on bright-magenta") }
/// π§ Β» makes the background of the text **bright cyan**
fn on_bright_cyan(&self) -> String { self.stl("on bright-cyan") }
/// π§ Β» makes the background of the text **bright white**
fn on_bright_white(&self) -> String { self.stl("on bright-white") }
/// π§ Β» makes the background color = **`rgb`** param (`#RRGGBB` format)
fn on_rgb(&self, rgb: &str) -> String { self.stl(&format!("on {}", rgb)) }
/// π§ Β» makes the text **bold**
fn bold(&self) -> String { self.stl("+bold") }
/// π§ Β» makes the text **dim**
fn dim(&self) -> String { self.stl("+dim") }
/// π§ Β» makes the text **italic**
fn italic(&self) -> String { self.stl("+italic") }
/// π§ Β» makes the text **underline**
fn underline(&self) -> String { self.stl("+underline") }
/// π§ Β» makes the text **blink**
fn blink(&self) -> String { self.stl("+blink") }
/// π§ Β» makes the text **reverse**
fn reverse(&self) -> String { self.stl("+reverse") }
/// π§ Β» makes the text **hidden**
fn hidden(&self) -> String { self.stl("+hidden") }
/// π§ Β» makes the text **strikethrough**
fn strikethrough(&self) -> String { self.stl("+strikethrough") }
}
impl Stylize for str {
fn stl(&self, instruction: &str) -> String {
stylize(self, instruction)
}
}
impl Stylize for String {
fn stl(&self, instruction: &str) -> String {
stylize(self, instruction)
}
}
/// π§ Β» stylize fn
/// --
///
/// Stylizes a string with optional ANSI color and attributes.
pub fn stylize<S: AsRef<str>>(s: S, instructions: &str) -> String {
let styled_string = instructions::parse(instructions);
if styled_string.is_err() {
return s.as_ref().to_string();
}
let styled_string = styled_string.unwrap();
let mut formatted = String::new();
if let Some(fg) = styled_string.fg {
formatted.push_str(&format!("\x1b[{}m", fg.to_fg_str()));
}
if let Some(bg) = styled_string.bg {
formatted.push_str(&format!("\x1b[{}m", bg.to_bg_str()));
}
if !styled_string.attrs.is_empty() {
let ansi_codes = styled_string.attrs.to_ansi_codes();
if !ansi_codes.is_empty() {
formatted.push_str(&format!("\x1b[{}m", ansi_codes.join(";")));
}
}
// Append the original string and clear the style
formatted.push_str(s.as_ref());
formatted.push_str("\x1b[0m");
formatted
}
// alias for stylize: stl
/// π§ Β» stl fn
/// --
///
/// Stylizes a string with optional ANSI color and attributes.
///
/// This is an alias for the `stylize` function.
pub fn stl<S: AsRef<str>>(s: S, instructions: &str) -> String {
stylize(s, instructions)
}