1pub const ANSICOLORS: &[(&str, &str)] = &[
6 ("BLACK", "\x1b[30m"),
7 ("RED", "\x1b[31m"),
8 ("GREEN", "\x1b[32m"),
9 ("YELLOW", "\x1b[33m"),
10 ("BLUE", "\x1b[34m"),
11 ("MAGENTA", "\x1b[35m"),
12 ("CYAN", "\x1b[36m"),
13 ("WHITE", "\x1b[37m"),
14 ("BOLD", "\x1b[1m"),
15 ("RESET", "\x1b[0m"),
16];
17
18pub const GREEN_START: &str = "\x1b[32m";
20pub const RED_START: &str = "\x1b[31m";
22pub const CYAN_START: &str = "\x1b[36m";
24pub const RESET: &str = "\x1b[0m";
26
27pub fn color_unified_diff_line(line: &str) -> String {
30 let start = |n: usize| line.get(..n).unwrap_or(line);
31 let color = if start(2) == "+ " || line == "+\n" {
32 GREEN_START
34 } else if start(2) == "- " || line == "-\n" {
35 RED_START
37 } else if start(3) == "@@ " {
38 CYAN_START
39 } else if start(4) == "--- " {
40 RED_START
41 } else if start(4) == "+++ " {
42 GREEN_START
43 } else {
44 return line.to_owned();
45 };
46 format!("{color}{line}{RESET}")
47}
48
49#[cfg(test)]
50mod tests {
51 use super::*;
52
53 #[test]
54 fn colors() {
55 assert_eq!(color_unified_diff_line("+ a\n"), "\x1b[32m+ a\n\x1b[0m");
56 assert_eq!(color_unified_diff_line("-\n"), "\x1b[31m-\n\x1b[0m");
57 assert_eq!(
58 color_unified_diff_line("@@ -1 +1 @@\n"),
59 "\x1b[36m@@ -1 +1 @@\n\x1b[0m"
60 );
61 assert_eq!(color_unified_diff_line("--- a\n"), "\x1b[31m--- a\n\x1b[0m");
62 assert_eq!(color_unified_diff_line("+++ b\n"), "\x1b[32m+++ b\n\x1b[0m");
63 assert_eq!(color_unified_diff_line("-<a/>\n"), "-<a/>\n");
65 assert_eq!(color_unified_diff_line(" a\n"), " a\n");
66 assert_eq!(color_unified_diff_line("é\n"), "é\n");
67 }
68}