agent_tui/common/
color.rs1use std::io::IsTerminal;
2use std::sync::OnceLock;
3
4static NO_COLOR: OnceLock<bool> = OnceLock::new();
5
6pub fn init(no_color_flag: bool) {
7 let _ = NO_COLOR.set(
8 no_color_flag || std::env::var("NO_COLOR").is_ok() || !std::io::stdout().is_terminal(),
9 );
10}
11
12pub fn is_disabled() -> bool {
13 *NO_COLOR.get().unwrap_or(&false)
14}
15
16mod codes {
17 pub const RESET: &str = "\x1b[0m";
18 pub const GREEN: &str = "\x1b[32m";
19 pub const RED: &str = "\x1b[31m";
20 pub const YELLOW: &str = "\x1b[33m";
21 pub const CYAN: &str = "\x1b[36m";
22 pub const DIM: &str = "\x1b[90m";
23 pub const BOLD: &str = "\x1b[1m";
24}
25
26pub struct Colors;
27
28impl Colors {
29 pub fn success(text: &str) -> String {
30 if is_disabled() {
31 text.to_string()
32 } else {
33 format!("{}{}{}", codes::GREEN, text, codes::RESET)
34 }
35 }
36
37 pub fn error(text: &str) -> String {
38 if is_disabled() {
39 text.to_string()
40 } else {
41 format!("{}{}{}", codes::RED, text, codes::RESET)
42 }
43 }
44
45 pub fn info(text: &str) -> String {
46 if is_disabled() {
47 text.to_string()
48 } else {
49 format!("{}{}{}", codes::CYAN, text, codes::RESET)
50 }
51 }
52
53 pub fn warning(text: &str) -> String {
54 if is_disabled() {
55 text.to_string()
56 } else {
57 format!("{}{}{}", codes::YELLOW, text, codes::RESET)
58 }
59 }
60
61 pub fn dim(text: &str) -> String {
62 if is_disabled() {
63 text.to_string()
64 } else {
65 format!("{}{}{}", codes::DIM, text, codes::RESET)
66 }
67 }
68
69 pub fn bold(text: &str) -> String {
70 if is_disabled() {
71 text.to_string()
72 } else {
73 format!("{}{}{}", codes::BOLD, text, codes::RESET)
74 }
75 }
76
77 pub fn element_ref(text: &str) -> String {
78 if is_disabled() {
79 text.to_string()
80 } else {
81 format!("{}{}{}", codes::CYAN, text, codes::RESET)
82 }
83 }
84
85 pub fn session_id(text: &str) -> String {
86 if is_disabled() {
87 text.to_string()
88 } else {
89 format!("{}{}{}{}", codes::BOLD, codes::CYAN, text, codes::RESET)
90 }
91 }
92}
93
94#[cfg(test)]
95mod tests {
96 use super::*;
97
98 #[test]
99 fn test_colors_disabled() {
100 let _ = NO_COLOR.set(true);
101 assert_eq!(Colors::success("test"), "test");
102 assert_eq!(Colors::error("test"), "test");
103 assert_eq!(Colors::element_ref("@inp1"), "@inp1");
104 }
105}