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