vergen-pretty 10.0.1

Output vergen information in a formatted manner
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
// Copyright (c) 2022 vergen developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

// rkyv ArchiveWith wrappers for console::Style and tracing::Level

#[cfg(feature = "color")]
use console::Style;
use rkyv::{
    Place, SerializeUnsized,
    rancor::{Fallible, Source},
    string::{ArchivedString, StringResolver},
    with::{ArchiveWith, DeserializeWith, SerializeWith},
};
#[cfg(feature = "trace")]
use tracing::Level;

#[cfg(feature = "color")]
/// rkyv [`ArchiveWith`] wrapper for [`console::Style`].
///
/// Serializes a [`Style`] as its dotted attribute string (e.g.
/// `"bold.red.on_blue"`), reconstructable via [`Style::from_dotted_str`].
///
/// The conversion works by forcing ANSI escape code emission on a clone of
/// the style, extracting the codes from the output, and mapping them back to
/// their named dotted-format equivalents.  The roundtrip is functionally
/// lossless: the deserialized style produces identical terminal output, though
/// the internal representation may differ for edge cases such as 256-color
/// indices 8–15 which overlap with bright basic colors.
///
/// Use with `#[rkyv(with = rkyv::with::Map<StyleWith>)]` on `Option<Style>`
/// fields.
#[cfg(feature = "color")]
#[derive(Clone, Copy, Debug)]
pub struct StyleWith;

#[cfg(feature = "color")]
/// Convert a [`Style`] to its dotted attribute string representation.
///
/// Clones and forces styling so that ANSI escape sequences are always emitted
/// regardless of the current terminal, then parses those sequences back into
/// the `"bold.red.on_blue"` format understood by [`Style::from_dotted_str`].
fn style_to_dotted(style: &Style) -> String {
    #[allow(clippy::items_after_statements)]
    let raw = style.clone().force_styling(true).apply_to("").to_string();
    if raw.is_empty() {
        return String::new();
    }
    let mut parts: Vec<String> = Vec::new();
    let mut chars = raw.chars();
    while let Some(ch) = chars.next() {
        if ch != '\x1b' {
            continue;
        }
        if chars.next() != Some('[') {
            continue;
        }
        let mut code = String::new();
        for c in chars.by_ref() {
            if c == 'm' {
                break;
            }
            code.push(c);
        }
        // "0" is the reset marker that terminates the style prefix.
        if code == "0" {
            break;
        }
        push_dotted_parts(&code, &mut parts);
    }
    parts.join(".")
}

#[cfg(feature = "color")]
/// Parse one ANSI SGR parameter string (e.g. `"31"`, `"38;5;196"`,
/// `"48;2;255;0;128"`) and push the corresponding dotted format part(s).
fn push_dotted_parts(code: &str, parts: &mut Vec<String>) {
    #[allow(clippy::items_after_statements)]
    let segs: Vec<&str> = code.split(';').collect();
    match segs.as_slice() {
        // Single numeric code
        [n_str] => {
            let Ok(n) = n_str.parse::<u8>() else { return };
            match n {
                // Attributes: Bold=1 … StrikeThrough=9
                1..=9 => {
                    const ATTRS: [&str; 9] = [
                        "bold",
                        "dim",
                        "italic",
                        "underlined",
                        "blink",
                        "blink_fast",
                        "reverse",
                        "hidden",
                        "strikethrough",
                    ];
                    parts.push(ATTRS[(n - 1) as usize].to_string());
                }
                // Basic foreground colors: 30 (Black) … 37 (White)
                30..=37 => {
                    const FG: [&str; 8] = [
                        "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white",
                    ];
                    parts.push(FG[(n - 30) as usize].to_string());
                }
                // Basic background colors: 40 (Black) … 47 (White)
                40..=47 => {
                    const BG: [&str; 8] = [
                        "on_black",
                        "on_red",
                        "on_green",
                        "on_yellow",
                        "on_blue",
                        "on_magenta",
                        "on_cyan",
                        "on_white",
                    ];
                    parts.push(BG[(n - 40) as usize].to_string());
                }
                _ => {}
            }
        }
        // Foreground 256-color or bright-basic: ESC[38;5;Nm
        // Bright-basic (8–15) will be stored as their 256-color index, which
        // round-trips to the same visual output via `from_dotted_str`.
        ["38", "5", n_str] => {
            if let Ok(n) = n_str.parse::<u8>() {
                parts.push(n.to_string());
            }
        }
        // Foreground true-color: ESC[38;2;R;G;Bm  →  "#RRGGBB"
        ["38", "2", r_str, g_str, b_str] => {
            if let (Ok(r), Ok(g), Ok(b)) = (
                r_str.parse::<u8>(),
                g_str.parse::<u8>(),
                b_str.parse::<u8>(),
            ) {
                parts.push(format!("#{r:02X}{g:02X}{b:02X}"));
            }
        }
        // Background 256-color or bright-basic: ESC[48;5;Nm  →  "on_N"
        ["48", "5", n_str] => {
            if let Ok(n) = n_str.parse::<u8>() {
                parts.push(format!("on_{n}"));
            }
        }
        // Background true-color: ESC[48;2;R;G;Bm  →  "on_#RRGGBB"
        ["48", "2", r_str, g_str, b_str] => {
            if let (Ok(r), Ok(g), Ok(b)) = (
                r_str.parse::<u8>(),
                g_str.parse::<u8>(),
                b_str.parse::<u8>(),
            ) {
                parts.push(format!("on_#{r:02X}{g:02X}{b:02X}"));
            }
        }
        _ => {}
    }
}

#[cfg(feature = "color")]
impl ArchiveWith<Style> for StyleWith {
    type Archived = ArchivedString;
    type Resolver = StringResolver;

    fn resolve_with(field: &Style, resolver: Self::Resolver, out: Place<Self::Archived>) {
        ArchivedString::resolve_from_str(&style_to_dotted(field), resolver, out);
    }
}

#[cfg(feature = "color")]
impl<S> SerializeWith<Style, S> for StyleWith
where
    S: Fallible + ?Sized,
    S::Error: Source,
    str: SerializeUnsized<S>,
{
    fn serialize_with(field: &Style, serializer: &mut S) -> Result<Self::Resolver, S::Error> {
        ArchivedString::serialize_from_str(&style_to_dotted(field), serializer)
    }
}

#[cfg(feature = "color")]
impl<D> DeserializeWith<ArchivedString, Style, D> for StyleWith
where
    D: Fallible + ?Sized,
{
    fn deserialize_with(field: &ArchivedString, _: &mut D) -> Result<Style, D::Error> {
        Ok(Style::from_dotted_str(field.as_str()))
    }
}

// ── LevelWith ────────────────────────────────────────────────────────────────

/// rkyv [`ArchiveWith`] wrapper for [`tracing::Level`].
///
/// Serializes a [`Level`] as its uppercase name string (`"TRACE"`, `"DEBUG"`,
/// `"INFO"`, `"WARN"`, `"ERROR"`), reconstructable via a simple match.
///
/// Use with `#[rkyv(with = LevelWith)]` on `Level` fields.
#[cfg(feature = "trace")]
#[derive(Clone, Copy, Debug)]
pub(crate) struct LevelWith;

#[cfg(feature = "trace")]
impl ArchiveWith<Level> for LevelWith {
    type Archived = ArchivedString;
    type Resolver = StringResolver;

    fn resolve_with(field: &Level, resolver: Self::Resolver, out: Place<Self::Archived>) {
        ArchivedString::resolve_from_str(field.as_str(), resolver, out);
    }
}

#[cfg(feature = "trace")]
impl<S> SerializeWith<Level, S> for LevelWith
where
    S: Fallible + ?Sized,
    S::Error: Source,
    str: SerializeUnsized<S>,
{
    fn serialize_with(field: &Level, serializer: &mut S) -> Result<Self::Resolver, S::Error> {
        ArchivedString::serialize_from_str(field.as_str(), serializer)
    }
}

#[cfg(feature = "trace")]
impl<D: Fallible + ?Sized> DeserializeWith<ArchivedString, Level, D> for LevelWith {
    fn deserialize_with(field: &ArchivedString, _: &mut D) -> Result<Level, D::Error> {
        Ok(match field.as_str() {
            "TRACE" => Level::TRACE,
            "DEBUG" => Level::DEBUG,
            "WARN" => Level::WARN,
            "ERROR" => Level::ERROR,
            _ => Level::INFO,
        })
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    #[cfg(feature = "color")]
    use super::style_to_dotted;
    #[cfg(feature = "color")]
    use console::Style;

    #[cfg(feature = "color")]
    #[test]
    fn empty_style_round_trips() {
        let s = Style::new();
        assert_eq!(style_to_dotted(&s), "");
        let _ = Style::from_dotted_str(&style_to_dotted(&s));
    }

    #[cfg(feature = "color")]
    #[test]
    fn basic_fg_color_round_trips() {
        for (style, expected) in [
            (Style::new().black(), "black"),
            (Style::new().red(), "red"),
            (Style::new().green(), "green"),
            (Style::new().yellow(), "yellow"),
            (Style::new().blue(), "blue"),
            (Style::new().magenta(), "magenta"),
            (Style::new().cyan(), "cyan"),
            (Style::new().white(), "white"),
        ] {
            assert_eq!(style_to_dotted(&style), expected);
        }
    }

    #[cfg(feature = "color")]
    #[test]
    fn basic_bg_color_round_trips() {
        assert_eq!(style_to_dotted(&Style::new().on_red()), "on_red");
        assert_eq!(style_to_dotted(&Style::new().on_blue()), "on_blue");
    }

    #[cfg(feature = "color")]
    #[test]
    fn attrs_round_trips() {
        assert_eq!(style_to_dotted(&Style::new().bold()), "bold");
        assert_eq!(style_to_dotted(&Style::new().underlined()), "underlined");
        assert_eq!(style_to_dotted(&Style::new().italic()), "italic");
        assert_eq!(
            style_to_dotted(&Style::new().strikethrough()),
            "strikethrough"
        );
    }

    #[cfg(feature = "color")]
    #[test]
    fn compound_style_round_trips() {
        // bold + green; serialized as "green.bold" (fg first, attrs second)
        let s = Style::new().bold().green();
        let dotted = style_to_dotted(&s);
        assert!(dotted.contains("green"));
        assert!(dotted.contains("bold"));
        let restored = Style::from_dotted_str(&dotted);
        // both styles should produce the same ANSI output
        assert_eq!(
            s.force_styling(true).apply_to("x").to_string(),
            restored.force_styling(true).apply_to("x").to_string(),
        );
    }

    #[cfg(feature = "color")]
    #[test]
    fn true_color_round_trips() {
        let s = Style::new().true_color(0xFF, 0x00, 0x80);
        let dotted = style_to_dotted(&s);
        assert_eq!(dotted, "#FF0080");
        let restored = Style::from_dotted_str(&dotted);
        assert_eq!(
            s.force_styling(true).apply_to("x").to_string(),
            restored.force_styling(true).apply_to("x").to_string(),
        );
    }

    #[cfg(feature = "color")]
    #[test]
    fn color256_round_trips() {
        let s = Style::new().color256(200);
        let dotted = style_to_dotted(&s);
        assert_eq!(dotted, "200");
        let restored = Style::from_dotted_str(&dotted);
        assert_eq!(
            s.force_styling(true).apply_to("x").to_string(),
            restored.force_styling(true).apply_to("x").to_string(),
        );
    }

    #[cfg(feature = "trace")]
    #[test]
    fn level_as_str_round_trips() {
        use tracing::Level;
        for (level, expected) in [
            (Level::TRACE, "TRACE"),
            (Level::DEBUG, "DEBUG"),
            (Level::INFO, "INFO"),
            (Level::WARN, "WARN"),
            (Level::ERROR, "ERROR"),
        ] {
            assert_eq!(level.as_str(), expected);
        }
    }

    #[cfg(feature = "trace")]
    #[test]
    fn level_default_fallback() {
        use super::LevelWith;
        use tracing::Level;
        let levels = [
            Level::TRACE,
            Level::DEBUG,
            Level::INFO,
            Level::WARN,
            Level::ERROR,
        ];
        for level in levels {
            assert_eq!(level.as_str().parse::<Level>().unwrap(), level);
        }
        let _ = LevelWith;
    }

    // ── Additional branch-coverage tests ────────────────────────────────────

    #[cfg(feature = "color")]
    #[test]
    fn all_bg_colors_round_trips() {
        for (style, expected) in [
            (Style::new().on_black(), "on_black"),
            (Style::new().on_green(), "on_green"),
            (Style::new().on_yellow(), "on_yellow"),
            (Style::new().on_magenta(), "on_magenta"),
            (Style::new().on_cyan(), "on_cyan"),
            (Style::new().on_white(), "on_white"),
        ] {
            assert_eq!(style_to_dotted(&style), expected);
        }
    }

    #[cfg(feature = "color")]
    #[test]
    fn remaining_attrs_round_trips() {
        for (style, expected) in [
            (Style::new().dim(), "dim"),
            (Style::new().blink(), "blink"),
            (Style::new().blink_fast(), "blink_fast"),
            (Style::new().reverse(), "reverse"),
            (Style::new().hidden(), "hidden"),
        ] {
            assert_eq!(style_to_dotted(&style), expected);
        }
    }

    #[cfg(feature = "color")]
    #[test]
    fn bg_color256_round_trips() {
        let s = Style::new().on_color256(196);
        let dotted = style_to_dotted(&s);
        assert_eq!(dotted, "on_196");
        let restored = Style::from_dotted_str(&dotted);
        assert_eq!(
            s.force_styling(true).apply_to("x").to_string(),
            restored.force_styling(true).apply_to("x").to_string(),
        );
    }

    #[cfg(feature = "color")]
    #[test]
    fn bg_true_color_round_trips() {
        let s = Style::new().on_true_color(0x12, 0x34, 0x56);
        let dotted = style_to_dotted(&s);
        assert_eq!(dotted, "on_#123456");
        let restored = Style::from_dotted_str(&dotted);
        assert_eq!(
            s.force_styling(true).apply_to("x").to_string(),
            restored.force_styling(true).apply_to("x").to_string(),
        );
    }

    /// Directly exercises the `_ => {}` arms in [`push_dotted_parts`] that
    /// silently discard unrecognised / out-of-range SGR codes.
    #[cfg(feature = "color")]
    #[test]
    fn push_dotted_parts_unrecognised_codes_are_ignored() {
        use super::push_dotted_parts;

        let mut parts: Vec<String> = Vec::new();

        // Single numeric code outside the handled ranges (1-9, 30-37, 40-47)
        // → hits the inner `_ => {}` in `match n`
        push_dotted_parts("10", &mut parts); // between attrs and fg basic
        push_dotted_parts("28", &mut parts); // between attrs and fg basic
        push_dotted_parts("50", &mut parts); // between bg basic and 256
        assert!(parts.is_empty(), "unexpected parts: {parts:?}");

        // Multi-segment slices that don't match any known pattern
        // → hit the outer `_ => {}` arm
        push_dotted_parts("38;5", &mut parts); // incomplete fg-256 (missing N)
        push_dotted_parts("99;99;99", &mut parts); // 3 segs, not 38;2 or 48;2
        push_dotted_parts("38;5;196;extra", &mut parts); // 4 segs
        assert!(parts.is_empty(), "unexpected parts: {parts:?}");
    }

    // ── End-to-end rkyv round-trip tests ─────────────────────────────────────

    /// A minimal struct that exercises `StyleWith` through rkyv's derive
    /// machinery: `resolve_with`, `serialize_with`, and `deserialize_with` are
    /// all exercised by the serialize + deserialize cycle below.
    #[cfg(feature = "color")]
    #[derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
    struct StyleWrap {
        #[rkyv(with = rkyv::with::Map<super::StyleWith>)]
        style: Option<Style>,
    }

    #[cfg(feature = "color")]
    #[test]
    fn style_with_rkyv_round_trip_some() {
        let original = StyleWrap {
            style: Some(Style::new().bold().red()),
        };
        let bytes = rkyv::to_bytes::<rkyv::rancor::Error>(&original).unwrap();
        let restored = rkyv::from_bytes::<StyleWrap, rkyv::rancor::Error>(&bytes).unwrap();
        let orig_ansi = original
            .style
            .as_ref()
            .unwrap()
            .clone()
            .force_styling(true)
            .apply_to("x")
            .to_string();
        let rest_ansi = restored
            .style
            .as_ref()
            .unwrap()
            .clone()
            .force_styling(true)
            .apply_to("x")
            .to_string();
        assert_eq!(orig_ansi, rest_ansi);
    }

    #[cfg(feature = "color")]
    #[test]
    fn style_with_rkyv_round_trip_none() {
        let original = StyleWrap { style: None };
        let bytes = rkyv::to_bytes::<rkyv::rancor::Error>(&original).unwrap();
        let restored = rkyv::from_bytes::<StyleWrap, rkyv::rancor::Error>(&bytes).unwrap();
        assert!(restored.style.is_none());
    }

    /// A minimal struct that exercises `LevelWith` through rkyv's derive
    /// machinery.
    ///
    /// `Level::INFO` serialises to `"INFO"` which hits the `_ => Level::INFO`
    /// fallback arm in `deserialize_with`, so running all five levels gives
    /// full branch coverage.
    #[cfg(feature = "trace")]
    #[derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
    struct LevelWrap {
        #[rkyv(with = super::LevelWith)]
        level: tracing::Level,
    }

    #[cfg(feature = "trace")]
    #[test]
    fn level_with_rkyv_round_trip() {
        use tracing::Level;
        for level in [
            Level::TRACE,
            Level::DEBUG,
            Level::INFO, // falls to `_ => Level::INFO` in deserialize_with
            Level::WARN,
            Level::ERROR,
        ] {
            let original = LevelWrap { level };
            let bytes = rkyv::to_bytes::<rkyv::rancor::Error>(&original).unwrap();
            let restored = rkyv::from_bytes::<LevelWrap, rkyv::rancor::Error>(&bytes).unwrap();
            assert_eq!(restored.level, level);
        }
    }

    // ── Derived-trait coverage ────────────────────────────────────────────────

    #[cfg(feature = "color")]
    #[test]
    fn style_with_clone_and_debug() {
        use super::StyleWith;
        let sw = StyleWith;
        let cloned = sw;
        let _unused = format!("{cloned:?}");
    }

    #[cfg(feature = "trace")]
    #[test]
    fn level_with_clone_and_debug() {
        use super::LevelWith;
        let lw = LevelWith;
        let cloned = lw;
        let _unused = format!("{cloned:?}");
    }
}