nuts_tool/say.rs
1// MIT License
2//
3// Copyright (c) 2023,2024 Robin Doer
4//
5// Permission is hereby granted, free of charge, to any person obtaining a copy
6// of this software and associated documentation files (the "Software"), to
7// deal in the Software without restriction, including without limitation the
8// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9// sell copies of the Software, and to permit persons to whom the Software is
10// furnished to do so, subject to the following conditions:
11//
12// The above copyright notice and this permission notice shall be included in
13// all copies or substantial portions of the Software.
14//
15// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21// IN THE SOFTWARE.
22
23use colored::{Color, Colorize};
24use std::borrow::Cow;
25use std::fmt::Arguments;
26
27use crate::cli::global::GLOBALS;
28
29pub fn is_quiet() -> bool {
30 GLOBALS.with_borrow(|g| g.say.quiet)
31}
32
33#[derive(Clone, Copy)]
34pub enum Level {
35 Normal,
36 Warning,
37 Error,
38}
39
40impl Level {
41 fn into_color(self) -> Option<Color> {
42 match self {
43 Self::Normal => None,
44 Self::Warning => Some(Color::Yellow),
45 Self::Error => Some(Color::Red),
46 }
47 }
48}
49
50#[derive(Default)]
51pub struct Say {
52 quiet: bool,
53}
54
55impl Say {
56 pub fn set_quiet(&mut self, quiet: bool) {
57 self.quiet = quiet;
58 }
59
60 pub fn say(&self, level: Level, args: Arguments<'_>) {
61 if self.quiet {
62 return;
63 }
64
65 let msg = match args.as_str() {
66 Some(s) => Cow::Borrowed(s),
67 None => Cow::Owned(args.to_string()),
68 };
69
70 match level.into_color() {
71 Some(color) => println!("{}", msg.color(color)),
72 None => println!("{}", msg),
73 }
74 }
75}
76
77#[macro_export]
78macro_rules! say {
79 ($level:ident $($arg:tt)*) => {{
80 $crate::cli::global::GLOBALS.with_borrow(|g|
81 g.say.say($crate::say::Level::$level, format_args!($($arg)*))
82 )
83 }};
84
85 ($($arg:tt)*) => {
86 say!(Normal $($arg)*);
87 };
88}
89
90#[macro_export]
91macro_rules! say_warn {
92 ($($arg:tt)*) => {
93 say!(Warning $($arg)*);
94 };
95}
96
97#[macro_export]
98macro_rules! say_err {
99 ($($arg:tt)*) => {
100 say!(Error $($arg)*);
101 };
102}