Skip to main content

fontoxide_diff/
color.rs

1//! Port of `fontTools.diff.color`: coloring the lines of a unified diff with
2//! ANSI escape codes.
3
4/// `ansicolors`: the ANSI escape codes by name.
5pub 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
18/// `green_start`.
19pub const GREEN_START: &str = "\x1b[32m";
20/// `red_start`.
21pub const RED_START: &str = "\x1b[31m";
22/// `cyan_start`.
23pub const CYAN_START: &str = "\x1b[36m";
24/// `reset`.
25pub const RESET: &str = "\x1b[0m";
26
27/// `color_unified_diff_line`: the line colored according to its type in a
28/// unified diff: added lines green, removed lines red, hunk headers cyan.
29pub 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		// A lone "+" is an added empty line.
33		GREEN_START
34	} else if start(2) == "- " || line == "-\n" {
35		// A lone "-" is a deleted empty line.
36		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		// Only lines whose text starts with a space are colored.
64		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}