summaryrefslogtreecommitdiffstats
path: root/src/term.rs
blob: cd2db46b37c452fc9b147095d2e676530a168984 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use crossterm::style::{Color, Print, ResetColor, SetForegroundColor};
use crossterm::QueueableCommand;
use lazy_static::lazy_static;
use minimad::mad_inline;
use std::io::Write;
use termimad::{mad_write_inline, MadSkin};

pub fn prefix_err() -> Result<MadSkin, termimad::Error> {
    let mut skin = MadSkin::default();
    skin.paragraph.set_fg(Color::Red);
    mad_write_inline!(&mut std::io::stderr(), &skin, "✖ ")?;
    Ok(skin)
}

pub trait ColoredOutput {
    fn queue_general(&mut self, color: Color, prefix: &str, s: &str) -> &mut Self;

    // TODO is it cool to unwrap flushing some known text?
    fn unsafe_flush(&mut self);

    fn queue_error(&mut self, s: &str) -> &mut Self {
        self.queue_general(Color::Red, "✖ ", s)
    }

    fn queue_success(&mut self, s: &str) -> &mut Self {
        self.queue_general(Color::Green, "✔ ", s)
    }

    fn queue_notice(&mut self, s: &str) -> &mut Self {
        self.queue_general(Color::Yellow, "➜ ", s)
    }

    fn queue_notice_inline(&mut self, s: &str) -> &mut Self {
        self.queue_general(Color::Yellow, "", s)
    }

    fn queue_log(&mut self, s: &str) -> &mut Self {
        self.queue_general(Color::Blue, "• ", s)
    }

    fn queue_code(&mut self, s: &str) -> &mut Self {
        self.queue_general(Color::Cyan, "\t", s)
    }

    fn queue_code_inline(&mut self, s: &str) -> &mut Self {
        self.queue_general(Color::Cyan, "", s)
    }

    fn queue_warn(&mut self, s: &str) -> &mut Self {
        self.queue_general(Color::Magenta, "⚡", s)
    }
}

impl<T> ColoredOutput for T
where
    T: Write,
{
    fn queue_general(&mut self, color: Color, prefix: &str, s: &str) -> &mut Self {
        (|| -> Result<(), crossterm::ErrorKind> {
            self.queue(SetForegroundColor(color))?
                .queue(Print(prefix.to_string()))?
                .queue(Print(s.to_string()))?
                .queue(ResetColor)?;
            Ok(())
        })()
        .unwrap();
        self
    }

    fn unsafe_flush(&mut self) {
        self.flush().unwrap();
    }
}