1use std::fmt::Display;
5use std::io::Write;
6
7use crate::Env;
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum ColorChoice {
13 Auto,
15 Always,
17 Never,
19}
20
21const RESET: &str = "\x1b[0m";
22const BOLD_RED: &str = "\x1b[1;31m";
23const BOLD_YELLOW: &str = "\x1b[1;33m";
24const BOLD_CYAN: &str = "\x1b[1;36m";
25const BOLD_GREEN: &str = "\x1b[1;32m";
26
27pub fn colors(
33 given: Option<ColorChoice>,
34 configured: Option<ColorChoice>,
35 no_color: bool,
36 terminal: bool,
37) -> bool {
38 match given.or(configured) {
39 Some(ColorChoice::Always) => true,
40 Some(ColorChoice::Never) => false,
41 Some(ColorChoice::Auto) => terminal,
42 None => terminal && !no_color,
43 }
44}
45
46#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
51pub enum Verbosity {
52 Quiet,
54 #[default]
56 Normal,
57 Verbose,
59}
60
61pub struct Shell {
64 out: Box<dyn Write>,
65 given: Option<ColorChoice>,
67 no_color: bool,
69 terminal: bool,
71 color: bool,
72 verbosity: Verbosity,
73}
74
75impl Shell {
76 pub fn new(
86 out: Box<dyn Write>,
87 choice: Option<ColorChoice>,
88 env: &Env,
89 out_is_terminal: bool,
90 ) -> Shell {
91 let mut shell = Shell {
92 out,
93 given: choice,
94 no_color: env.get("NO_COLOR").is_some(),
95 terminal: out_is_terminal,
96 color: false,
97 verbosity: Verbosity::Normal,
98 };
99 shell.configure(None, false);
100 shell
101 }
102
103 pub fn configure(&mut self, configured: Option<ColorChoice>, verbose: bool) {
107 self.color = colors(self.given, configured, self.no_color, self.terminal);
108 if verbose && self.verbosity == Verbosity::Normal {
109 self.verbosity = Verbosity::Verbose;
110 }
111 }
112
113 pub fn set_verbosity(&mut self, verbosity: Verbosity) {
118 self.verbosity = verbosity;
119 }
120
121 pub fn verbose(&self) -> bool {
123 self.verbosity == Verbosity::Verbose
124 }
125
126 pub fn uses_color(&self) -> bool {
128 self.color
129 }
130
131 pub fn error(&mut self, message: impl Display) {
133 self.line(BOLD_RED, "error", message);
134 }
135
136 pub fn warning(&mut self, message: impl Display) {
138 self.line(BOLD_YELLOW, "warning", message);
139 }
140
141 pub fn help(&mut self, message: impl Display) {
143 self.line(BOLD_CYAN, "help", message);
144 }
145
146 pub fn status(&mut self, verb: &str, message: impl Display) {
150 if self.verbosity == Verbosity::Quiet {
151 return;
152 }
153 let verb = self.paint(BOLD_GREEN, &format!("{verb:>12}"));
154 self.write(format_args!("{verb} {message}"));
155 }
156
157 pub fn raw(&mut self, bytes: &[u8]) {
161 let _ = self.out.write_all(bytes);
163 let _ = self.out.flush();
164 }
165
166 fn line(&mut self, style: &str, label: &str, message: impl Display) {
167 let label = self.paint(style, label);
168 self.write(format_args!("{label}: {message}"));
169 }
170
171 fn write(&mut self, line: std::fmt::Arguments<'_>) {
172 let _ = writeln!(self.out, "{line}");
174 }
175
176 fn paint(&self, style: &str, text: &str) -> String {
177 if self.color {
178 format!("{style}{text}{RESET}")
179 } else {
180 text.to_owned()
181 }
182 }
183}
184
185#[cfg(test)]
186mod tests {
187 use super::*;
188 use crate::env::NameCase;
189 use std::sync::{Arc, Mutex};
190
191 #[derive(Clone, Default)]
193 struct Captured(Arc<Mutex<Vec<u8>>>);
194
195 impl Write for Captured {
196 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
197 self.0.lock().unwrap().write(buf)
198 }
199 fn flush(&mut self) -> std::io::Result<()> {
200 Ok(())
201 }
202 }
203
204 impl Captured {
205 fn text(&self) -> String {
206 String::from_utf8(self.0.lock().unwrap().clone()).unwrap()
207 }
208 }
209
210 fn shell(
211 choice: Option<ColorChoice>,
212 env: &[(&str, &str)],
213 terminal: bool,
214 ) -> (Shell, Captured) {
215 let out = Captured::default();
216 let env = Env::from_pairs(
217 env.iter().map(|(n, v)| (n.into(), v.into())),
218 NameCase::Sensitive,
219 );
220 (
221 Shell::new(Box::new(out.clone()), choice, &env, terminal),
222 out,
223 )
224 }
225
226 #[test]
234 fn configured_verbose_ranks_below_the_command_line() {
235 let (fresh, _) = shell(Some(ColorChoice::Never), &[], false);
237 assert!(!fresh.verbose());
238 for (given, configured, verbose, quiet) in [
239 (Verbosity::Normal, true, true, false),
240 (Verbosity::Normal, false, false, false),
241 (Verbosity::Quiet, true, false, true),
242 (Verbosity::Verbose, false, true, false),
243 ] {
244 let (mut sh, out) = shell(Some(ColorChoice::Never), &[], false);
245 sh.set_verbosity(given);
246 sh.configure(None, configured);
247 assert_eq!(sh.verbose(), verbose, "{given:?}, configured {configured}");
248 sh.status("Compiling", "app");
249 assert_eq!(
250 out.text().is_empty(),
251 quiet,
252 "{given:?}, configured {configured}"
253 );
254 }
255 }
256
257 #[test]
263 fn quiet_leaves_out_status_lines_only() {
264 let (mut sh, out) = shell(Some(ColorChoice::Never), &[], false);
265 sh.set_verbosity(Verbosity::Quiet);
266 sh.status("Compiling", "mygame v0.1.0");
267 sh.error("no compiler found");
268 sh.help("install Build Tools");
269 sh.warning("unused key");
270 sh.raw(
271 b"main.cpp(1): note
272",
273 );
274 assert_eq!(
275 out.text(),
276 "error: no compiler found
277help: install Build Tools
278warning: unused key
279main.cpp(1): note
280"
281 );
282 }
283
284 #[test]
287 fn lines_without_color() {
288 let (mut sh, out) = shell(Some(ColorChoice::Never), &[], false);
289 sh.error("no compiler found");
290 sh.help("install Build Tools");
291 sh.warning("unused key");
292 sh.status("Compiling", "mygame v0.1.0");
293 assert_eq!(
294 out.text(),
295 "error: no compiler found\nhelp: install Build Tools\nwarning: unused key\n Compiling mygame v0.1.0\n"
296 );
297 }
298
299 #[test]
304 fn raw_output_is_written_as_produced() {
305 let (mut sh, out) = shell(Some(ColorChoice::Always), &[], false);
306 let cp932 = [0x83, 0x81, 0x83, 0x82, 0x0d, 0x0a];
307 sh.raw(&cp932);
308 sh.raw(b"x");
309 assert_eq!(*out.0.lock().unwrap(), [&cp932[..], b"x"].concat());
310 }
311
312 #[test]
315 fn lines_with_color_paint_only_the_label() {
316 let (mut sh, out) = shell(Some(ColorChoice::Always), &[], false);
317 sh.error("e");
318 sh.help("h");
319 sh.warning("w");
320 sh.status("Compiling", "m");
321 assert_eq!(
322 out.text(),
323 "\x1b[1;31merror\x1b[0m: e\n\
324 \x1b[1;36mhelp\x1b[0m: h\n\
325 \x1b[1;33mwarning\x1b[0m: w\n\
326 \x1b[1;32m Compiling\x1b[0m m\n"
327 );
328 }
329
330 #[test]
334 fn color_follows_the_choice_the_terminal_and_no_color() {
335 let on =
336 |choice, env: &[(&str, &str)], terminal| shell(choice, env, terminal).0.uses_color();
337 let no_color: &[(&str, &str)] = &[("NO_COLOR", "")];
338 assert!(on(None, &[], true));
341 assert!(!on(None, &[], false));
342 assert!(!on(None, no_color, true));
343 assert!(on(Some(ColorChoice::Auto), no_color, true));
345 assert!(!on(Some(ColorChoice::Auto), &[], false));
346 assert!(on(Some(ColorChoice::Always), no_color, false));
347 assert!(!on(Some(ColorChoice::Never), &[], true));
348 }
349
350 #[test]
356 fn colors_follows_the_order() {
357 use ColorChoice::{Always, Auto, Never};
358 assert!(colors(Some(Always), Some(Never), true, false));
360 assert!(!colors(Some(Never), Some(Always), false, true));
361 assert!(colors(None, Some(Always), true, false));
362 assert!(!colors(None, Some(Never), false, true));
363 assert!(colors(Some(Auto), None, true, true));
365 assert!(!colors(Some(Auto), Some(Always), false, false));
366 assert!(colors(None, Some(Auto), true, true));
367 assert!(!colors(None, None, true, true));
369 assert!(colors(None, None, false, true));
370 assert!(!colors(None, None, false, false));
371 }
372
373 #[test]
379 fn the_configured_choice_ranks_between_the_flag_and_no_color() {
380 let on = |given, configured, env: &[(&str, &str)], terminal| {
381 let mut shell = shell(given, env, terminal).0;
382 shell.configure(configured, false);
383 shell.uses_color()
384 };
385 let no_color: &[(&str, &str)] = &[("NO_COLOR", "")];
386 let (always, never) = (Some(ColorChoice::Always), Some(ColorChoice::Never));
387 assert!(on(None, always, no_color, false));
388 assert!(!on(None, never, &[], true));
389 assert!(on(None, Some(ColorChoice::Auto), no_color, true));
390 assert!(!on(never, always, &[], true));
391 assert!(on(always, never, &[], false));
392 assert!(!on(None, None, no_color, true));
393 assert!(on(None, None, &[], true));
394 }
395}