1use crate::App;
9
10const RESET: &str = "\x1b[0m";
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub struct Style {
15 color: bool,
16}
17
18impl Style {
19 pub fn stdout() -> Self {
21 Self::new(crate::color_on_stdout())
22 }
23
24 pub fn stderr() -> Self {
26 Self::new(crate::color_on_stderr())
27 }
28
29 pub fn plain() -> Self {
31 Self::new(false)
32 }
33
34 pub fn new(color: bool) -> Self {
35 Self { color }
36 }
37
38 pub fn enabled(&self) -> bool {
40 self.color
41 }
42
43 pub fn bold(&self, s: &str) -> String {
44 self.wrap("\x1b[1m", s)
45 }
46
47 pub fn dim(&self, s: &str) -> String {
48 self.wrap("\x1b[2m", s)
49 }
50
51 pub fn ok(&self, s: &str) -> String {
53 self.wrap("\x1b[32m", s)
54 }
55
56 pub fn warn(&self, s: &str) -> String {
58 self.wrap("\x1b[33m", s)
59 }
60
61 pub fn err(&self, s: &str) -> String {
63 self.wrap("\x1b[31m", s)
64 }
65
66 pub fn mark_line(&self, app: &App, text: &str) -> String {
68 format!("{} {text}", self.bold(app.mark()))
69 }
70
71 fn wrap(&self, code: &str, s: &str) -> String {
72 if self.color {
73 format!("{code}{s}{RESET}")
74 } else {
75 s.to_string()
76 }
77 }
78}
79
80#[cfg(test)]
81mod tests {
82 use super::*;
83
84 #[test]
85 fn plain_has_no_escapes() {
86 let style = Style::plain();
87 assert!(!style.enabled());
88 assert_eq!(style.bold("x"), "x");
89 assert_eq!(style.dim("x"), "x");
90 assert_eq!(style.ok("x"), "x");
91 assert_eq!(style.warn("x"), "x");
92 assert_eq!(style.err("x"), "x");
93 assert!(!style.bold("x").contains('\x1b'));
94 }
95
96 #[test]
97 fn wraps_with_ansi() {
98 let style = Style::new(true);
99 assert!(style.enabled());
100 assert_eq!(style.bold("x"), "\x1b[1mx\x1b[0m");
101 assert_eq!(style.dim("x"), "\x1b[2mx\x1b[0m");
102 assert_eq!(style.ok("x"), "\x1b[32mx\x1b[0m");
103 assert_eq!(style.warn("x"), "\x1b[33mx\x1b[0m");
104 assert_eq!(style.err("x"), "\x1b[31mx\x1b[0m");
105 }
106
107 #[test]
108 fn mark_line_plain() {
109 let style = Style::plain();
110 assert_eq!(style.mark_line(&App::OPSH, "opsh doctor"), "❯ opsh doctor");
111 }
112
113 #[test]
114 fn mark_line_color() {
115 let style = Style::new(true);
116 assert_eq!(
117 style.mark_line(&App::OPSH, "doctor"),
118 "\x1b[1m❯\x1b[0m doctor"
119 );
120 }
121}