1use comfy_table::{Attribute, Cell, Color};
2use std::io::IsTerminal;
3
4pub struct Theme {
5 pub red: &'static str,
6 pub green: &'static str,
7 pub yellow: &'static str,
8 pub blue: &'static str,
9 pub bold: &'static str,
10 pub reset: &'static str,
11}
12
13const ON: Theme = Theme {
14 red: "\x1b[31m",
15 green: "\x1b[32m",
16 yellow: "\x1b[33m",
17 blue: "\x1b[34m",
18 bold: "\x1b[1m",
19 reset: "\x1b[0m",
20};
21
22const OFF: Theme = Theme {
23 red: "",
24 green: "",
25 yellow: "",
26 blue: "",
27 bold: "",
28 reset: "",
29};
30
31fn use_color(is_tty: bool) -> bool {
32 std::env::var_os("NO_COLOR").is_none() && is_tty
33}
34
35/// Colour theme for stdout.
36pub fn stdout_theme() -> &'static Theme {
37 if use_color(std::io::stdout().is_terminal()) {
38 &ON
39 } else {
40 &OFF
41 }
42}
43
44/// Colour theme for stderr.
45pub fn stderr_theme() -> &'static Theme {
46 if use_color(std::io::stderr().is_terminal()) {
47 &ON
48 } else {
49 &OFF
50 }
51}
52
53/// Whether stdout should use colour.
54pub fn stdout_use_color() -> bool {
55 use_color(std::io::stdout().is_terminal())
56}
57
58/// A table cell with bold text.
59pub fn cell_bold(text: impl ToString, use_color: bool) -> Cell {
60 let cell = Cell::new(text);
61 if use_color {
62 cell.add_attribute(Attribute::Bold)
63 } else {
64 cell
65 }
66}
67
68/// A table cell with a coloured foreground.
69pub fn cell_fg(text: impl ToString, color: Color, use_color: bool) -> Cell {
70 let cell = Cell::new(text);
71 if use_color {
72 cell.fg(color)
73 } else {
74 cell
75 }
76}