fencryption_lib/
log.rs

1//! Log utilities.
2
3use colored::Colorize;
4
5enum LogKind {
6    Success,
7    Error,
8    Warn,
9    Info,
10}
11
12/// Adds a "start line pattern" at the start of every line in
13/// the given text.
14pub fn with_start_line<T, L>(text: T, line_start: L) -> String
15where
16    T: AsRef<str>,
17    L: AsRef<str>,
18{
19    format!(
20        "{} {}",
21        line_start.as_ref(),
22        text.as_ref()
23            .replace("\n", &["\n", line_start.as_ref(), " "].concat())
24    )
25}
26
27/// Styles a message.
28fn style_message<M>(message: M, kind: LogKind) -> String
29where
30    M: AsRef<str>,
31{
32    if supports_color::on(supports_color::Stream::Stdout).is_some() && cfg!(target_family = "unix")
33    {
34        with_start_line(
35            message,
36            match kind {
37                LogKind::Success => " ".on_bright_green(),
38                LogKind::Error => " ".on_bright_red(),
39                LogKind::Warn => " ".on_bright_yellow(),
40                LogKind::Info => " ".on_white(),
41            }
42            .to_string(),
43        )
44    } else {
45        message.as_ref().to_string()
46    }
47}
48
49/// Formats message with the "info" style.
50pub fn format_info<M>(message: M) -> String
51where
52    M: AsRef<str>,
53{
54    style_message(message, LogKind::Info)
55}
56
57/// Prints message with the "info" style.
58pub fn println_info<M>(message: M)
59where
60    M: AsRef<str>,
61{
62    println!("{}", format_info(message));
63}
64
65/// Formats message with the "success" style.
66pub fn format_success<M>(message: M) -> String
67where
68    M: AsRef<str>,
69{
70    style_message(message, LogKind::Success)
71}
72
73/// Prints message with the "success" style.
74pub fn println_success<M>(message: M)
75where
76    M: AsRef<str>,
77{
78    println!("{}", format_success(message))
79}
80
81/// Formats message with the "error" style.
82pub fn format_error<M>(message: M) -> String
83where
84    M: AsRef<str>,
85{
86    style_message(message, LogKind::Error)
87}
88
89/// Prints message with the "error" style.
90pub fn println_error<M>(message: M)
91where
92    M: AsRef<str>,
93{
94    println!("{}", format_error(message))
95}
96
97/// Formats message with the "warn" style.
98pub fn format_warn<M>(message: M) -> String
99where
100    M: AsRef<str>,
101{
102    style_message(message, LogKind::Warn)
103}
104
105/// Prints message with the "warn" style.
106pub fn println_warn<M>(message: M)
107where
108    M: AsRef<str>,
109{
110    println!("{}", format_warn(message))
111}
112
113// pub fn prompt<M>(message: M) -> io::Result<String>
114// where
115//     M: AsRef<str>,
116// {
117//     print!("{}", format_info(message));
118//     stdout().flush()?;
119//     let mut out = String::new();
120//     stdin().read_line(&mut out)?;
121//     Ok(out)
122// }