Debian Codegraph @

src/style.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 use std::borrow::Cow;
2 use std::fmt;
3 use std::hash::{Hash, Hasher};
4
5 use lazy_static::lazy_static;
6
7 use crate::ansi;
8 use crate::color;
9 use crate::git_config::GitConfig;
10
11 // PERF: Avoid deriving Copy here?
12 #[derive(Clone, Copy, PartialEq, Default)]
13 pub struct Style {
14 pub ansi_term_style: ansi_term::Style,
15 pub is_emph: bool,
16 pub is_omitted: bool,
17 pub is_raw: bool,
18 pub is_syntax_highlighted: bool,
19 pub decoration_style: DecorationStyle,
20 }
21
22 // More compact debug output, replace false/empty with lowercase and true with uppercase.
23 impl fmt::Debug for Style {
24 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
25 let ansi = if self.ansi_term_style.is_plain() {
26 "<a".into()
27 } else {
28 format!("ansi_term_style: {:?}, <", self.ansi_term_style)
29 };
30
31 let deco = if self.decoration_style == DecorationStyle::NoDecoration {
32 "d>".into()
33 } else {
34 format!(">, decoration_style: {:?}", self.decoration_style)
35 };
36
37 let is_set = |c: char, set: bool| -> String {
38 if set {
39 c.to_uppercase().to_string()
40 } else {
41 c.to_lowercase().to_string()
42 }
43 };
44
45 write!(
46 f,
47 "Style {{ {}{}{}{}{}{} }}",
48 ansi,
49 is_set('e', self.is_emph),
50 is_set('o', self.is_omitted),
51 is_set('r', self.is_raw),
52 is_set('s', self.is_syntax_highlighted),
53 deco
54 )
55 }
56 }
57
58 #[derive(Clone, Copy, Debug, PartialEq, Default)]
59 pub enum DecorationStyle {
60 Box(ansi_term::Style),
61 Underline(ansi_term::Style),
62 Overline(ansi_term::Style),
63 UnderOverline(ansi_term::Style),
64 BoxWithUnderline(ansi_term::Style),
65 BoxWithOverline(ansi_term::Style),
66 BoxWithUnderOverline(ansi_term::Style),
67 #[default]
68 NoDecoration,
69 }
70
71 impl Style {
72 pub fn new() -> Self {
73 Self {
74 ansi_term_style: ansi_term::Style::new(),
75 is_emph: false,
76 is_omitted: false,
77 is_raw: false,
78 is_syntax_highlighted: false,
79 decoration_style: DecorationStyle::NoDecoration,
80 }
81 }
82
83 pub fn from_colors(
84 foreground: Option<ansi_term::Color>,
85 background: Option<ansi_term::Color>,
86 ) -> Self {
87 Self {
88 ansi_term_style: ansi_term::Style {
89 foreground,
90 background,
91 ..ansi_term::Style::new()
92 },
93 ..Self::new()
94 }
95 }
96
97 pub fn paint<'a, I, S: 'a + ToOwned + ?Sized>(
98 self,
99 input: I,
•100 ) -> ansi_term::AnsiGenericString<'a, S>
101 where
102 I: Into<Cow<'a, S>>,
103 <S as ToOwned>::Owned: fmt::Debug,
104 {
105 self.ansi_term_style.paint(input)
106 }
107
108 pub fn get_background_color(&self) -> Option<ansi_term::Color> {
109 if self.ansi_term_style.is_reverse {
110 self.ansi_term_style.foreground
111 } else {
112 self.ansi_term_style.background
113 }
114 }
115
116 pub fn is_applied_to(&self, s: &str) -> bool {
117 match ansi::parse_first_style(s) {
118 Some(parsed_style) => ansi_term_style_equality(parsed_style, self.ansi_term_style),
119 None => false,
120 }
121 }
122
123 #[cfg(test)]
124 pub fn get_matching_substring<'a>(&self, s: &'a str) -> Option<&'a str> {
125 for (parsed_style, parsed_str) in ansi::parse_style_sections(s) {
126 if ansi_term_style_equality(parsed_style, self.ansi_term_style) {
127 return Some(parsed_str);
128 }
129 }
130 None
131 }
132
•133 pub fn to_painted_string(self) -> ansi_term::AnsiGenericString<'static, str> {
134 self.paint(self.to_string())
135 }
136 }
137
138 /// Interpret `color_string` as a color specifier and return it painted accordingly.
139 pub fn paint_color_string<'a>(
140 color_string: &'a str,
141 true_color: bool,
142 git_config: Option<&GitConfig>,
•143 ) -> ansi_term::AnsiGenericString<'a, str> {
144 if let Some(color) = color::parse_color(color_string, true_color, git_config) {
145 let style = ansi_term::Style {
146 background: Some(color),
147 ..ansi_term::Style::default()
148 };
149 style.paint(color_string)
150 } else {
•151 ansi_term::AnsiGenericString::from(color_string)
152 }
153 }
154
155 impl fmt::Display for Style {
156 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
157 if self.is_raw {
158 return write!(f, "raw");
159 }
160 let mut words = Vec::<String>::new();
161 if self.is_omitted {
162 words.push("omit".to_string());
163 }
164 if self.ansi_term_style.is_blink {
165 words.push("blink".to_string());
166 }
167 if self.ansi_term_style.is_bold {
168 words.push("bold".to_string());
169 }
170 if self.ansi_term_style.is_dimmed {
171 words.push("dim".to_string());
172 }
173 if self.ansi_term_style.is_italic {
174 words.push("italic".to_string());
175 }
176 if self.ansi_term_style.is_reverse {
177 words.push("reverse".to_string());
178 }
179 if self.ansi_term_style.is_strikethrough {
180 words.push("strike".to_string());
181 }
182 if self.ansi_term_style.is_underline {
183 words.push("ul".to_string());
184 }
185
186 match (self.is_syntax_highlighted, self.ansi_term_style.foreground) {
187 (true, _) => words.push("syntax".to_string()),
188 (false, Some(color)) => {
189 words.push(color::color_to_string(color));
190 }
191 (false, None) => words.push("normal".to_string()),
192 }
193 if let Some(color) = self.ansi_term_style.background {
194 words.push(color::color_to_string(color))
195 }
196 let style_str = words.join(" ");
197 write!(f, "{style_str}")
198 }
199 }
200
201 pub fn ansi_term_style_equality(a: ansi_term::Style, b: ansi_term::Style) -> bool {
202 let a_attrs = ansi_term::Style {
203 foreground: None,
204 background: None,
205 ..a
206 };
207 let b_attrs = ansi_term::Style {
208 foreground: None,
209 background: None,
210 ..b
211 };
212 if a_attrs != b_attrs {
213 false
214 } else {
215 ansi_term_color_equality(a.foreground, b.foreground)
216 & ansi_term_color_equality(a.background, b.background)
217 }
218 }
219
220 // TODO: The equality methods were implemented first, and the equality_key
221 // methods later. The former should be re-implemented in terms of the latter.
•222 // But why did the former not address equality of ansi_term::Color::Rgb values?
223 #[derive(Clone)]
224 pub struct AnsiTermStyleEqualityKey {
225 attrs_key: (bool, bool, bool, bool, bool, bool, bool, bool),
226 foreground_key: Option<(u8, u8, u8, u8)>,
227 background_key: Option<(u8, u8, u8, u8)>,
228 }
229
230 impl PartialEq for AnsiTermStyleEqualityKey {
231 fn eq(&self, other: &Self) -> bool {
232 let option_eq = |opt_a, opt_b| match (opt_a, opt_b) {
233 (Some(a), Some(b)) => a == b,
234 (None, None) => true,
235 _ => false,
236 };
237
238 if self.attrs_key != other.attrs_key {
239 false
240 } else {
241 option_eq(self.foreground_key, other.foreground_key)
242 && option_eq(self.background_key, other.background_key)
243 }
244 }
245 }
246
247 impl Eq for AnsiTermStyleEqualityKey {}
248
249 impl Hash for AnsiTermStyleEqualityKey {
250 fn hash<H: Hasher>(&self, state: &mut H) {
251 self.attrs_key.hash(state);
252 self.foreground_key.hash(state);
253 self.background_key.hash(state);
254 }
255 }
256
257 pub fn ansi_term_style_equality_key(style: ansi_term::Style) -> AnsiTermStyleEqualityKey {
258 let attrs_key = (
259 style.is_bold,
260 style.is_dimmed,
261 style.is_italic,
262 style.is_underline,
263 style.is_blink,
264 style.is_reverse,
265 style.is_hidden,
266 style.is_strikethrough,
267 );
268 AnsiTermStyleEqualityKey {
269 attrs_key,
270 foreground_key: style.foreground.map(ansi_term_color_equality_key),
271 background_key: style.background.map(ansi_term_color_equality_key),
272 }
273 }
274
275 impl fmt::Debug for AnsiTermStyleEqualityKey {
276 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
277 let is_set = |c: char, set: bool| -> String {
278 if set {
279 c.to_uppercase().to_string()
280 } else {
281 c.to_lowercase().to_string()
282 }
283 };
284
285 let (bold, dimmed, italic, underline, blink, reverse, hidden, strikethrough) =
286 self.attrs_key;
287 write!(
288 f,
289 "ansi_term::Style {{ {:?} {:?} {}{}{}{}{}{}{}{} }}",
290 self.foreground_key,
291 self.background_key,
292 is_set('b', bold),
293 is_set('d', dimmed),
294 is_set('i', italic),
295 is_set('u', underline),
296 is_set('l', blink),
297 is_set('r', reverse),
298 is_set('h', hidden),
299 is_set('s', strikethrough),
300 )
301 }
302 }
303
304 fn ansi_term_color_equality(a: Option<ansi_term::Color>, b: Option<ansi_term::Color>) -> bool {
305 match a.zip(b) {
306 Some((a, b)) => {
307 a == b || ansi_term_16_color_equality(a, b) || ansi_term_16_color_equality(b, a)
308 }
309 None => a.is_none() && b.is_none(),
310 }
311 }
312
313 fn ansi_term_16_color_equality(a: ansi_term::Color, b: ansi_term::Color) -> bool {
314 matches!(
315 (a, b),
316 (ansi_term::Color::Fixed(0), ansi_term::Color::Black)
317 | (ansi_term::Color::Fixed(1), ansi_term::Color::Red)
318 | (ansi_term::Color::Fixed(2), ansi_term::Color::Green)
319 | (ansi_term::Color::Fixed(3), ansi_term::Color::Yellow)
320 | (ansi_term::Color::Fixed(4), ansi_term::Color::Blue)
321 | (ansi_term::Color::Fixed(5), ansi_term::Color::Purple)
322 | (ansi_term::Color::Fixed(6), ansi_term::Color::Cyan)
323 | (ansi_term::Color::Fixed(7), ansi_term::Color::White)
•324 | (ansi_term::Color::Fixed(8), ansi_term::Color::DarkGray)
325 | (ansi_term::Color::Fixed(9), ansi_term::Color::LightRed)
326 | (ansi_term::Color::Fixed(10), ansi_term::Color::LightGreen)
327 | (ansi_term::Color::Fixed(11), ansi_term::Color::LightYellow)
328 | (ansi_term::Color::Fixed(12), ansi_term::Color::LightBlue)
329 | (ansi_term::Color::Fixed(13), ansi_term::Color::LightPurple)
330 | (ansi_term::Color::Fixed(14), ansi_term::Color::LightCyan)
331 | (ansi_term::Color::Fixed(15), ansi_term::Color::LightGray)
332 )
333 }
334
335 fn ansi_term_color_equality_key(color: ansi_term::Color) -> (u8, u8, u8, u8) {
336 // Same (r, g, b, a) encoding as in utils::bat::terminal::to_ansi_color.
337 // When a = 0xFF, then a 256-color number is stored in the red channel, and
338 // the green and blue channels are meaningless. But a=0 signifies an RGB
339 // color.
340 let default = 0xFF;
341 match color {
342 ansi_term::Color::Fixed(0) | ansi_term::Color::Black => (0, default, default, default),
343 ansi_term::Color::Fixed(1) | ansi_term::Color::Red => (1, default, default, default),
344 ansi_term::Color::Fixed(2) | ansi_term::Color::Green => (2, default, default, default),
345 ansi_term::Color::Fixed(3) | ansi_term::Color::Yellow => (3, default, default, default),
346 ansi_term::Color::Fixed(4) | ansi_term::Color::Blue => (4, default, default, default),
•347 ansi_term::Color::Fixed(5) | ansi_term::Color::Purple | ansi_term::Color::Magenta => {
348 (5, default, default, default)
349 }
350 ansi_term::Color::Fixed(6) | ansi_term::Color::Cyan => (6, default, default, default),
351 ansi_term::Color::Fixed(7) | ansi_term::Color::White => (7, default, default, default),
•352 ansi_term::Color::Fixed(8) | ansi_term::Color::DarkGray => (8, default, default, default),
353 ansi_term::Color::Fixed(9) | ansi_term::Color::LightRed => (9, default, default, default),
354 ansi_term::Color::Fixed(10) | ansi_term::Color::LightGreen => {
355 (10, default, default, default)
356 }
357 ansi_term::Color::Fixed(11) | ansi_term::Color::LightYellow => {
358 (11, default, default, default)
359 }
360 ansi_term::Color::Fixed(12) | ansi_term::Color::LightBlue => {
361 (12, default, default, default)
362 }
363 ansi_term::Color::Fixed(13)
364 | ansi_term::Color::LightPurple
365 | ansi_term::Color::LightMagenta => (13, default, default, default),
366 ansi_term::Color::Fixed(14) | ansi_term::Color::LightCyan => {
367 (14, default, default, default)
368 }
369 ansi_term::Color::Fixed(15) | ansi_term::Color::LightGray => {
370 (15, default, default, default)
371 }
372 ansi_term::Color::Fixed(n) => (n, default, default, default),
•373 ansi_term::Color::Rgb(r, g, b) => (r, g, b, 0),
374 ansi_term::Color::Default => todo!(),
375 }
376 }
377
378 lazy_static! {
379 pub static ref GIT_DEFAULT_MINUS_STYLE: Style = Style {
380 ansi_term_style: ansi_term::Color::Red.normal(),
381 ..Style::new()
382 };
383 pub static ref GIT_DEFAULT_PLUS_STYLE: Style = Style {
384 ansi_term_style: ansi_term::Color::Green.normal(),
385 ..Style::new()
386 };
387 }
388
389 pub fn line_has_style_other_than(line: &str, styles: &[Style]) -> bool {
390 if !ansi::string_starts_with_ansi_style_sequence(line) {
391 return false;
392 }
393 for style in styles {
394 if style.is_applied_to(line) {
395 return false;
396 }
397 }
398 true
399 }
400
401 #[cfg(test)]
402 pub mod tests {
403
404 use super::*;
405
406 // To add to these tests:
407 // 1. Stage a file with a single line containing the string "text"
408 // 2. git -c 'color.diff.new = $STYLE_STRING' diff --cached --color=always | cat -A
409
410 lazy_static! {
411 pub static ref GIT_STYLE_STRING_EXAMPLES: Vec<(&'static str, &'static str)> = vec![
412 // <git-default> "\x1b[32m+\x1b[m\x1b[32mtext\x1b[m\n"
413 ("0", "\x1b[30m+\x1b[m\x1b[30mtext\x1b[m\n"),
414 ("black", "\x1b[30m+\x1b[m\x1b[30mtext\x1b[m\n"),
415 ("1", "\x1b[31m+\x1b[m\x1b[31mtext\x1b[m\n"),
416 ("red", "\x1b[31m+\x1b[m\x1b[31mtext\x1b[m\n"),
417 ("0 1", "\x1b[30;41m+\x1b[m\x1b[30;41mtext\x1b[m\n"),
418 ("black red", "\x1b[30;41m+\x1b[m\x1b[30;41mtext\x1b[m\n"),
419 ("19", "\x1b[38;5;19m+\x1b[m\x1b[38;5;19mtext\x1b[m\n"),
420 ("black 19", "\x1b[30;48;5;19m+\x1b[m\x1b[30;48;5;19mtext\x1b[m\n"),
421 ("19 black", "\x1b[38;5;19;40m+\x1b[m\x1b[38;5;19;40mtext\x1b[m\n"),
422 ("19 20", "\x1b[38;5;19;48;5;20m+\x1b[m\x1b[38;5;19;48;5;20mtext\x1b[m\n"),
423 ("#aabbcc", "\x1b[38;2;170;187;204m+\x1b[m\x1b[38;2;170;187;204mtext\x1b[m\n"),
424 ("0 #aabbcc", "\x1b[30;48;2;170;187;204m+\x1b[m\x1b[30;48;2;170;187;204mtext\x1b[m\n"),
425 ("#aabbcc 0", "\x1b[38;2;170;187;204;40m+\x1b[m\x1b[38;2;170;187;204;40mtext\x1b[m\n"),
426 ("19 #aabbcc", "\x1b[38;5;19;48;2;170;187;204m+\x1b[m\x1b[38;5;19;48;2;170;187;204mtext\x1b[m\n"),
427 ("#aabbcc 19", "\x1b[38;2;170;187;204;48;5;19m+\x1b[m\x1b[38;2;170;187;204;48;5;19mtext\x1b[m\n"),
428 ("#aabbcc #ddeeff" , "\x1b[38;2;170;187;204;48;2;221;238;255m+\x1b[m\x1b[38;2;170;187;204;48;2;221;238;255mtext\x1b[m\n"),
429 ("bold #aabbcc #ddeeff" , "\x1b[1;38;2;170;187;204;48;2;221;238;255m+\x1b[m\x1b[1;38;2;170;187;204;48;2;221;238;255mtext\x1b[m\n"),
430 ("bold #aabbcc ul #ddeeff" , "\x1b[1;4;38;2;170;187;204;48;2;221;238;255m+\x1b[m\x1b[1;4;38;2;170;187;204;48;2;221;238;255mtext\x1b[m\n"),
431 ("bold #aabbcc ul #ddeeff strike" , "\x1b[1;4;9;38;2;170;187;204;48;2;221;238;255m+\x1b[m\x1b[1;4;9;38;2;170;187;204;48;2;221;238;255mtext\x1b[m\n"),
432 ("bold 0 ul 1 strike", "\x1b[1;4;9;30;41m+\x1b[m\x1b[1;4;9;30;41mtext\x1b[m\n"),
433 ("bold 0 ul 19 strike", "\x1b[1;4;9;30;48;5;19m+\x1b[m\x1b[1;4;9;30;48;5;19mtext\x1b[m\n"),
434 ("bold 19 ul 0 strike", "\x1b[1;4;9;38;5;19;40m+\x1b[m\x1b[1;4;9;38;5;19;40mtext\x1b[m\n"),
435 ("bold #aabbcc ul 0 strike", "\x1b[1;4;9;38;2;170;187;204;40m+\x1b[m\x1b[1;4;9;38;2;170;187;204;40mtext\x1b[m\n"),
436 ("bold #aabbcc ul 19 strike" , "\x1b[1;4;9;38;2;170;187;204;48;5;19m+\x1b[m\x1b[1;4;9;38;2;170;187;204;48;5;19mtext\x1b[m\n"),
437 ("bold 19 ul #aabbcc strike" , "\x1b[1;4;9;38;5;19;48;2;170;187;204m+\x1b[m\x1b[1;4;9;38;5;19;48;2;170;187;204mtext\x1b[m\n"),
438 ("bold 0 ul #aabbcc strike", "\x1b[1;4;9;30;48;2;170;187;204m+\x1b[m\x1b[1;4;9;30;48;2;170;187;204mtext\x1b[m\n"),
439 (r##"black "#ddeeff""##, "\x1b[30;48;2;221;238;255m+\x1b[m\x1b[30;48;2;221;238;255mtext\x1b[m\n"),
440 ("brightred", "\x1b[91m+\x1b[m\x1b[91mtext\x1b[m\n"),
441 ("normal", "\x1b[mtext\x1b[m\n"),
442 ("blink", "\x1b[5m+\x1b[m\x1b[5mtext\x1b[m\n"),
443 ];
444 }
445
446 #[test]
447 fn test_parse_git_style_string_and_ansi_code_iterator() {
448 for (git_style_string, git_output) in &*GIT_STYLE_STRING_EXAMPLES {
449 assert!(Style::from_git_str(git_style_string).is_applied_to(git_output));
450 }
451 }
452
453 #[test]
454 fn test_is_applied_to_negative_assertion() {
455 let style_string_from_24 = "bold #aabbcc ul 19 strike";
456 let git_output_from_25 = "\x1b[1;4;9;38;5;19;48;2;170;187;204m+\x1b[m\x1b[1;4;9;38;5;19;48;2;170;187;204mtext\x1b[m\n";
457 assert!(!Style::from_git_str(style_string_from_24).is_applied_to(git_output_from_25));
458 }
459
460 #[test]
461 fn test_git_default_styles() {
462 let minus_line_from_unconfigured_git = "\x1b[31m-____\x1b[m\n";
463 let plus_line_from_unconfigured_git = "\x1b[32m+\x1b[m\x1b[32m____\x1b[m\n";
464 assert!(GIT_DEFAULT_MINUS_STYLE.is_applied_to(minus_line_from_unconfigured_git));
465 assert!(!GIT_DEFAULT_MINUS_STYLE.is_applied_to(plus_line_from_unconfigured_git));
466
467 assert!(GIT_DEFAULT_PLUS_STYLE.is_applied_to(plus_line_from_unconfigured_git));
468 assert!(!GIT_DEFAULT_PLUS_STYLE.is_applied_to(minus_line_from_unconfigured_git));
469 }
470
471 #[test]
472 fn test_line_has_style_other_than() {
473 let minus_line_from_unconfigured_git = "\x1b[31m-____\x1b[m\n";
474 let plus_line_from_unconfigured_git = "\x1b[32m+\x1b[m\x1b[32m____\x1b[m\n";
475
476 // Unstyled lines should test negative, regardless of supplied styles.
477 assert!(!line_has_style_other_than("", &[]));
478 assert!(!line_has_style_other_than("", &[*GIT_DEFAULT_MINUS_STYLE]));
479
480 // Lines from git should test negative when corresponding default is supplied
481 assert!(!line_has_style_other_than(
482 minus_line_from_unconfigured_git,
483 &[*GIT_DEFAULT_MINUS_STYLE]
484 ));
485 assert!(!line_has_style_other_than(
486 plus_line_from_unconfigured_git,
487 &[*GIT_DEFAULT_PLUS_STYLE]
488 ));
489
490 // Styled lines should test positive when unless their style is supplied.
491 assert!(line_has_style_other_than(
492 minus_line_from_unconfigured_git,
493 &[*GIT_DEFAULT_PLUS_STYLE]
494 ));
495 assert!(line_has_style_other_than(
496 minus_line_from_unconfigured_git,
497 &[]
498 ));
499 assert!(line_has_style_other_than(
500 plus_line_from_unconfigured_git,
501 &[*GIT_DEFAULT_MINUS_STYLE]
502 ));
503 assert!(line_has_style_other_than(
504 plus_line_from_unconfigured_git,
505 &[]
506 ));
507 }
508
509 #[test]
510 fn test_style_compact_debug_fmt() {
511 let mut s = Style::new();
512 assert_eq!(format!("{s:?}"), "Style { <aeorsd> }");
513 s.is_emph = true;
514 assert_eq!(format!("{s:?}"), "Style { <aEorsd> }");
515 s.ansi_term_style = ansi_term::Style::new().bold();
516 assert_eq!(
517 format!("{s:?}"),
518 "Style { ansi_term_style: Style { bold }, <Eorsd> }"
519 );
520 s.decoration_style = DecorationStyle::Underline(s.ansi_term_style);
521 assert_eq!(
522 format!("{s:?}"),
523 "Style { ansi_term_style: Style { bold }, <Eors>, \
524 decoration_style: Underline(Style { bold }) }"
525 );
526 s.ansi_term_style = ansi_term::Style::default();
527 assert_eq!(
528 format!("{s:?}"),
529 "Style { <aEors>, decoration_style: Underline(Style { bold }) }"
530 );
531 }
532 }