nbr 0.4.3

CLI for NoneBot2 - A Rust implementation
Documentation
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
use ansi_term::{Colour, Style};
use std::borrow::Cow;
use std::fmt::Write;
use tracing_core::Event;
use tracing_subscriber::fmt::format::Writer;
use tracing_subscriber::fmt::{FormatEvent, FormatFields};
use tracing_subscriber::registry::LookupSpan;
use tracing_subscriber::{EnvFilter, layer::SubscriberExt, util::SubscriberInitExt};
struct CustomFormatter;

impl<S, N> FormatEvent<S, N> for CustomFormatter
where
    S: tracing_core::Subscriber + for<'a> LookupSpan<'a>,
    N: for<'a> FormatFields<'a> + 'static,
{
    fn format_event(
        &self,
        _: &tracing_subscriber::fmt::FmtContext<'_, S, N>,
        mut writer: Writer<'_>,
        event: &Event<'_>,
    ) -> std::fmt::Result {
        // 获取日志级别
        let level = event.metadata().level();

        // 根据级别设置颜色
        let msg_style = match *level {
            tracing::Level::ERROR => Colour::Red.bold(),
            tracing::Level::WARN => Colour::Yellow.bold(),
            tracing::Level::INFO => Colour::Green.bold(),
            tracing::Level::DEBUG => Colour::Blue.normal(),
            tracing::Level::TRACE => Colour::Purple.normal(),
        };

        match *level {
            tracing::Level::INFO => {}
            tracing::Level::ERROR => {
                write!(writer, "")?;
            }
            tracing::Level::WARN => {
                write!(writer, "⚠️  ")?;
            }
            tracing::Level::DEBUG => {
                write!(
                    writer,
                    "{} ",
                    Style::new().bold().fg(Colour::Blue).paint("[DEBUG]")
                )?;
            }
            tracing::Level::TRACE => {
                write!(
                    writer,
                    "{} ",
                    Style::new().bold().fg(Colour::Purple).paint("[TRACE]")
                )?;
            }
        }

        // 格式化消息字段
        let mut visitor = MessageVisitor::default();
        event.record(&mut visitor);

        // 输出带颜色的消息
        if let Some(message) = visitor.message {
            write!(writer, "{}", msg_style.paint(message))?;
        }

        writeln!(writer)
    }
}

#[derive(Default)]
struct MessageVisitor {
    message: Option<String>,
}

impl tracing::field::Visit for MessageVisitor {
    fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
        if field.name() == "message" {
            self.message = Some(value.to_string());
        }
    }

    fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
        if field.name() == "message" {
            self.message = Some(format!("{:?}", value));
        }
    }
}

pub fn init_logging(verbose_level: u8) {
    let filter = match verbose_level {
        0 => "INFO",
        1 => "DEBUG",
        _ => "TRACE",
    };
    // 创建自定义格式化层
    let formatting_layer = tracing_subscriber::fmt::layer()
        .event_format(CustomFormatter)
        .with_ansi(true);

    // 初始化订阅者
    tracing_subscriber::registry()
        .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(filter)))
        .with(formatting_layer)
        .init();
}

/// 样式部件枚举,存储样式信息而不是预格式化的字符串
#[derive(Debug, Clone)]
enum StylePart<'a> {
    /// 纯文本
    Text(Cow<'a, str>),
    /// 带颜色的文本
    Colored { text: Cow<'a, str>, color: Colour },
    /// 带样式的文本
    Styled { text: Cow<'a, str>, style: Style },
    /// 带颜色和样式的文本
    ColoredStyled {
        text: Cow<'a, str>,
        color: Colour,
        style: Style,
    },
}

pub struct StyledText<'a> {
    parts: Vec<StylePart<'a>>,
    sep: &'a str,
}

// 更新宏定义:支持静态字符串和动态字符串
macro_rules! color_method {
    ($name:ident, $color:expr) => {
        pub fn $name(&mut self, text: impl Into<Cow<'a, str>>) -> &mut Self {
            self.parts.push(StylePart::Colored {
                text: text.into(),
                color: $color,
            });
            self
        }
    };
}

macro_rules! style_method {
    ($name:ident, $style:expr) => {
        pub fn $name(&mut self, text: impl Into<Cow<'a, str>>) -> &mut Self {
            self.parts.push(StylePart::Styled {
                text: text.into(),
                style: $style,
            });
            self
        }
    };
}

macro_rules! color_style_method {
    ($name:ident, $color:expr, $style:expr) => {
        pub fn $name(&mut self, text: impl Into<Cow<'a, str>>) -> &mut Self {
            self.parts.push(StylePart::ColoredStyled {
                text: text.into(),
                color: $color,
                style: $style,
            });
            self
        }
    };
}

macro_rules! print_style_method {
    ($fmt:ident, $print:ident, $style:ident) => {
        pub fn $print(&self) {
            let msg = self.$fmt().expect("Failed to format styled text");
            println!("{}", msg);
        }

        pub fn $fmt(&self) -> Result<String, std::fmt::Error> {
            let mut result = String::new();
            let mut iter = self.parts.iter().peekable();

            while let Some(part) = iter.next() {
                let styled_text = match part {
                    StylePart::Text(text) => Style::new().$style().paint(text.as_ref()),
                    StylePart::Colored { text, color } => {
                        Style::new().$style().fg(*color).paint(text.as_ref())
                    }
                    StylePart::Styled { text, style } => style.$style().paint(text.as_ref()),
                    StylePart::ColoredStyled { text, color, style } => {
                        style.$style().fg(*color).paint(text.as_ref())
                    }
                };

                write!(result, "{}", styled_text)?;

                if iter.peek().is_some() {
                    write!(result, "{}", self.sep)?;
                }
            }
            Ok(result)
        }
    };
}

impl<'a> std::fmt::Display for StyledText<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut iter = self.parts.iter().peekable();

        while let Some(part) = iter.next() {
            match part {
                StylePart::Text(text) => write!(f, "{}", text)?,
                StylePart::Colored { text, color } => write!(f, "{}", color.paint(text.as_ref()))?,
                StylePart::Styled { text, style } => write!(f, "{}", style.paint(text.as_ref()))?,
                StylePart::ColoredStyled { text, color, style } => {
                    write!(f, "{}", style.fg(*color).paint(text.as_ref()))?
                }
            }
            if iter.peek().is_some() {
                write!(f, "{}", self.sep)?;
            }
        }
        Ok(())
    }
}

impl<'a> StyledText<'a> {
    pub fn new(sep: &'a str) -> Self {
        let parts = Vec::new();
        Self { parts, sep }
    }

    pub fn println(&self) {
        println!("{self}");
    }

    print_style_method!(fmt_bold, println_bold, bold);
    print_style_method!(fmt_blink, println_blink, blink);
    print_style_method!(fmt_italic, println_italic, italic);
    print_style_method!(fmt_hidden, println_hidden, hidden);
    print_style_method!(fmt_reverse, println_reverse, reverse);
    print_style_method!(fmt_underline, println_underline, underline);
    print_style_method!(fmt_strikethrough, println_strikethrough, strikethrough);

    /// 接收闭包
    pub fn with(&mut self, closure: impl FnOnce(&mut Self)) -> &mut Self {
        closure(self);
        self
    }

    pub fn text(&mut self, text: impl Into<Cow<'a, str>>) -> &mut Self {
        self.parts.push(StylePart::Text(text.into()));
        self
    }

    // 基本颜色方法
    color_method!(white, Colour::White);
    color_method!(red, Colour::Red);
    color_method!(green, Colour::Green);
    color_method!(blue, Colour::Blue);
    color_method!(purple, Colour::Purple);
    color_method!(yellow, Colour::Yellow);
    color_method!(cyan, Colour::Cyan);
    color_method!(black, Colour::Black);

    // 基本样式方法
    style_method!(bold, Style::new().bold());
    style_method!(dimmed, Style::new().dimmed());
    style_method!(italic, Style::new().italic());
    style_method!(underline, Style::new().underline());
    style_method!(blink, Style::new().blink());
    style_method!(reverse, Style::new().reverse());
    style_method!(hidden, Style::new().hidden());
    style_method!(strikethrough, Style::new().strikethrough());

    // 颜色+粗体组合
    color_style_method!(white_bold, Colour::White, Style::new().bold());
    color_style_method!(red_bold, Colour::Red, Style::new().bold());
    color_style_method!(green_bold, Colour::Green, Style::new().bold());
    color_style_method!(blue_bold, Colour::Blue, Style::new().bold());
    color_style_method!(purple_bold, Colour::Purple, Style::new().bold());
    color_style_method!(yellow_bold, Colour::Yellow, Style::new().bold());
    color_style_method!(cyan_bold, Colour::Cyan, Style::new().bold());
    color_style_method!(black_bold, Colour::Black, Style::new().bold());

    // 颜色+下划线组合
    color_style_method!(white_underline, Colour::White, Style::new().underline());
    color_style_method!(red_underline, Colour::Red, Style::new().underline());
    color_style_method!(green_underline, Colour::Green, Style::new().underline());
    color_style_method!(blue_underline, Colour::Blue, Style::new().underline());
    color_style_method!(purple_underline, Colour::Purple, Style::new().underline());
    color_style_method!(yellow_underline, Colour::Yellow, Style::new().underline());
    color_style_method!(cyan_underline, Colour::Cyan, Style::new().underline());
    color_style_method!(black_underline, Colour::Black, Style::new().underline());

    // RGB 颜色方法
    pub fn rgb(&mut self, r: u8, g: u8, b: u8, text: impl Into<Cow<'a, str>>) -> &mut Self {
        self.parts.push(StylePart::Colored {
            text: text.into(),
            color: Colour::RGB(r, g, b),
        });
        self
    }

    pub fn rgb_bold(&mut self, r: u8, g: u8, b: u8, text: impl Into<Cow<'a, str>>) -> &mut Self {
        self.parts.push(StylePart::ColoredStyled {
            text: text.into(),
            color: Colour::RGB(r, g, b),
            style: Style::new().bold(),
        });
        self
    }

    // 固定颜色编号方法
    pub fn fixed(&mut self, color_num: u8, text: impl Into<Cow<'a, str>>) -> &mut Self {
        self.parts.push(StylePart::Colored {
            text: text.into(),
            color: Colour::Fixed(color_num),
        });
        self
    }

    pub fn fixed_bold(&mut self, color_num: u8, text: impl Into<Cow<'a, str>>) -> &mut Self {
        self.parts.push(StylePart::ColoredStyled {
            text: text.into(),
            color: Colour::Fixed(color_num),
            style: Style::new().bold(),
        });
        self
    }

    /// 获取部件数量
    pub fn len(&self) -> usize {
        self.parts.len()
    }

    /// 检查是否为空
    pub fn is_empty(&self) -> bool {
        self.parts.is_empty()
    }

    /// 清空所有部件
    pub fn clear(&mut self) {
        self.parts.clear();
    }
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn test_log() {
        init_logging(1);

        tracing::info!(
            "test {} {}",
            Colour::Yellow.paint("info"),
            Colour::Cyan.paint("info")
        );
        tracing::debug!("test {}", 123);
        tracing::trace!("test {}", 123);
        tracing::warn!("test {}", 123);
        tracing::error!("test {}", 123);
    }

    #[test]
    fn test_styled_text() {
        let mut styled_text = StyledText::new(" ");
        styled_text
            .text("plain")
            .text("owned".to_string()) // 测试 String 输入
            .white("white")
            .red("red")
            .green("green")
            .blue("blue")
            .purple("purple")
            .yellow("yellow")
            .cyan("cyan")
            .black("black")
            .bold("bold")
            .dimmed("dimmed")
            .italic("italic")
            .underline("underline")
            .blink("blink")
            .reverse("reverse")
            .hidden("hidden")
            .strikethrough("strikethrough")
            .white_bold("white_bold")
            .red_bold("red_bold")
            .green_bold("green_bold")
            .blue_bold("blue_bold")
            .purple_bold("purple_bold")
            .yellow_bold("yellow_bold")
            .cyan_bold("cyan_bold")
            .black_bold("black_bold")
            .white_underline("white_underline")
            .red_underline("red_underline")
            .green_underline("green_underline")
            .blue_underline("blue_underline")
            .purple_underline("purple_underline")
            .yellow_underline("yellow_underline")
            .cyan_underline("cyan_underline")
            .black_underline("black_underline")
            .rgb(255, 100, 100, "rgb_pink")
            .rgb_bold(100, 255, 100, "rgb_green_bold")
            .fixed(202, "fixed_orange")
            .fixed_bold(45, "fixed_blue_bold")
            .with(|t| {
                t.green("with_closure");
            });

        assert!(!styled_text.is_empty());

        // 测试直接输出方法
        styled_text.println();
        println!();
        styled_text.println_bold();

        styled_text.clear();
        assert!(styled_text.is_empty());
        assert_eq!(styled_text.len(), 0);
    }
}