1use crate::git::RepoInfo;
4
5const RESET: &str = "\x1b[0m";
6const BOLD: &str = "\x1b[1m";
7const GREEN: &str = "\x1b[32m";
8const YELLOW: &str = "\x1b[33m";
9const RED: &str = "\x1b[31m";
10const CYAN: &str = "\x1b[36m";
11
12pub fn print_table(infos: &[RepoInfo]) {
13 let headers = ["#", "REPO", "ORG", "BRANCH", "AUTHOR", "SHA", "STATUS"];
14 let rows: Vec<[String; 7]> = infos
15 .iter()
16 .enumerate()
17 .map(|(i, info)| {
18 [
19 (i + 1).to_string(),
20 info.name.clone(),
21 info.org.clone(),
22 info.branch.clone(),
23 info.author.clone(),
24 info.sha.clone(),
25 format_status_ansi(info),
26 ]
27 })
28 .collect();
29
30 let mut widths = [0usize; 7];
31 for (c, h) in headers.iter().enumerate() {
32 widths[c] = vlen(h);
33 }
34 for row in &rows {
35 for c in 0..7 {
36 widths[c] = widths[c].max(vlen(&row[c]));
37 }
38 }
39
40 let format_row = |row: &[String]| -> String {
41 row.iter()
42 .enumerate()
43 .map(|(c, cell)| {
44 let pad = widths[c].saturating_sub(vlen(cell));
45 format!("{}{}", cell, " ".repeat(pad))
46 })
47 .collect::<Vec<_>>()
48 .join(" ")
49 };
50
51 let header_row: Vec<String> = headers.iter().map(|s| s.to_string()).collect();
52 eprintln!("{BOLD}{}{RESET}", format_row(&header_row));
53 eprintln!(
54 "{}",
55 widths
56 .iter()
57 .map(|w| "-".repeat(*w))
58 .collect::<Vec<_>>()
59 .join(" ")
60 );
61 for row in &rows {
62 eprintln!("{}", format_row(row));
63 }
64}
65
66pub fn format_status_ansi(info: &RepoInfo) -> String {
67 let mut parts: Vec<String> = Vec::new();
68 if info.dirty > 0 {
69 parts.push(format!("{YELLOW}{} changed{RESET}", info.dirty));
70 } else {
71 parts.push(format!("{GREEN}clean{RESET}"));
72 }
73 if info.ahead > 0 {
74 parts.push(format!("{CYAN}\u{2191}{}{RESET}", info.ahead));
75 }
76 if info.behind > 0 {
77 parts.push(format!("{RED}\u{2193}{}{RESET}", info.behind));
78 }
79 parts.join(" ")
80}
81
82pub fn strip_ansi(s: &str) -> String {
83 let mut result = String::with_capacity(s.len());
84 let mut chars = s.chars().peekable();
85 while let Some(c) = chars.next() {
86 if c == '\u{1b}' && chars.peek() == Some(&'[') {
87 chars.next();
88 for nc in chars.by_ref() {
89 if nc == 'm' {
90 break;
91 }
92 }
93 continue;
94 }
95 result.push(c);
96 }
97 result
98}
99
100pub fn vlen(s: &str) -> usize {
101 strip_ansi(s).chars().count()
102}
103
104#[cfg(test)]
105mod tests {
106 use super::*;
107
108 #[test]
109 fn strip_removes_ansi_sequences() {
110 assert_eq!(strip_ansi("\x1b[31mred\x1b[0m"), "red");
111 assert_eq!(strip_ansi("plain"), "plain");
112 assert_eq!(
113 strip_ansi("\x1b[1;33mbold-yellow\x1b[0mtail"),
114 "bold-yellowtail"
115 );
116 }
117
118 #[test]
119 fn vlen_ignores_ansi() {
120 assert_eq!(vlen("\x1b[31mabc\x1b[0m"), 3);
121 }
122}