error_forge/
console_theme.rs1use std::io::IsTerminal;
10
11pub struct ConsoleTheme {
17 error_color: &'static str,
18 warning_color: &'static str,
19 info_color: &'static str,
20 success_color: &'static str,
21 caption_color: &'static str,
22 reset: &'static str,
23 bold: &'static str,
24 dim: &'static str,
25}
26
27fn terminal_supports_ansi() -> bool {
29 static SUPPORTS_ANSI: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
34
35 *SUPPORTS_ANSI.get_or_init(|| {
36 if !std::io::stderr().is_terminal() {
38 return false;
39 }
40
41 if let Ok(term) = std::env::var("TERM") {
43 if term == "dumb" {
44 return false;
45 }
46 }
47
48 if no_color_requested(std::env::var_os("NO_COLOR").as_deref()) {
49 return false;
50 }
51
52 #[cfg(windows)]
54 {
55 if std::env::var_os("WT_SESSION").is_some() {
56 return true;
57 }
58 }
59
60 true
63 })
64}
65
66fn no_color_requested(value: Option<&std::ffi::OsStr>) -> bool {
72 value.is_some_and(|v| !v.is_empty())
73}
74
75impl Default for ConsoleTheme {
76 fn default() -> Self {
77 if terminal_supports_ansi() {
78 Self::with_colors()
79 } else {
80 Self::plain()
81 }
82 }
83}
84
85impl ConsoleTheme {
86 pub fn new() -> Self {
90 Self::default()
91 }
92
93 pub const fn with_colors() -> Self {
96 Self {
97 error_color: "\x1b[31m", warning_color: "\x1b[33m", info_color: "\x1b[34m", success_color: "\x1b[32m", caption_color: "\x1b[36m", reset: "\x1b[0m",
103 bold: "\x1b[1m",
104 dim: "\x1b[2m",
105 }
106 }
107
108 pub const fn plain() -> Self {
111 Self {
112 error_color: "",
113 warning_color: "",
114 info_color: "",
115 success_color: "",
116 caption_color: "",
117 reset: "",
118 bold: "",
119 dim: "",
120 }
121 }
122
123 pub fn error(&self, text: &str) -> String {
125 format!("{}{}{}", self.error_color, text, self.reset)
126 }
127
128 pub fn warning(&self, text: &str) -> String {
130 format!("{}{}{}", self.warning_color, text, self.reset)
131 }
132
133 pub fn info(&self, text: &str) -> String {
135 format!("{}{}{}", self.info_color, text, self.reset)
136 }
137
138 pub fn success(&self, text: &str) -> String {
140 format!("{}{}{}", self.success_color, text, self.reset)
141 }
142
143 pub fn caption(&self, text: &str) -> String {
145 format!("{}{}{}", self.caption_color, text, self.reset)
146 }
147
148 pub fn bold(&self, text: &str) -> String {
150 format!("{}{}{}", self.bold, text, self.reset)
151 }
152
153 pub fn dim(&self, text: &str) -> String {
155 format!("{}{}{}", self.dim, text, self.reset)
156 }
157
158 pub fn format_error<E: crate::error::ForgeError>(&self, err: &E) -> String {
164 use std::fmt::Write as _;
165 let mut buf = String::with_capacity(160);
166
167 let _ = writeln!(buf, "{}", self.caption(&format!("⚠️ {}", err.caption())));
170
171 let _ = writeln!(buf, "{}", self.error(&err.to_string()));
173
174 let marker = if err.is_retryable() {
176 self.success("Yes")
177 } else {
178 self.error("No")
179 };
180 let _ = writeln!(buf, "{}Retryable: {}{}", self.dim, marker, self.reset);
181
182 if let Some(source) = err.source() {
184 let _ = writeln!(
185 buf,
186 "{}Caused by: {}{}",
187 self.dim,
188 self.error(&source.to_string()),
189 self.reset
190 );
191 }
192
193 buf
194 }
195}
196
197pub fn print_error<E: crate::error::ForgeError>(err: &E) {
203 static DEFAULT_THEME: std::sync::OnceLock<ConsoleTheme> = std::sync::OnceLock::new();
204 let theme = DEFAULT_THEME.get_or_init(ConsoleTheme::default);
205 eprintln!("{}", theme.format_error(err));
206}
207
208pub fn install_panic_hook() {
210 let theme = ConsoleTheme::default();
211 std::panic::set_hook(Box::new(move |panic_info| {
212 let message = match panic_info.payload().downcast_ref::<&str>() {
213 Some(s) => *s,
214 None => match panic_info.payload().downcast_ref::<String>() {
215 Some(s) => s.as_str(),
216 None => "Unknown panic",
217 },
218 };
219
220 let location = if let Some(location) = panic_info.location() {
221 format!("at {}:{}", location.file(), location.line())
222 } else {
223 "at unknown location".to_string()
224 };
225
226 eprintln!("{}", theme.caption("💥 PANIC"));
227 eprintln!(
228 "{}",
229 theme.error(&format!("{} {}", message, theme.dim(&location)))
230 );
231 }));
232}
233
234#[cfg(test)]
235mod tests {
236 use super::no_color_requested;
237 use std::ffi::OsStr;
238
239 #[test]
240 fn test_no_color_follows_spec() {
241 assert!(!no_color_requested(None));
244 assert!(!no_color_requested(Some(OsStr::new(""))));
245 assert!(no_color_requested(Some(OsStr::new("1"))));
246 assert!(no_color_requested(Some(OsStr::new("0"))));
247 assert!(no_color_requested(Some(OsStr::new("false"))));
248 }
249}