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
use clap::Args;
use heck::ToTitleCase;
use miette::IntoDiagnostic;
use std::fmt;
use tracing::{field::Field, Event, Level, Metadata, Subscriber};
use tracing_subscriber::{
    field::Visit,
    fmt::{format::Writer, FmtContext, FormatEvent, FormatFields, FormattedFields},
    registry::LookupSpan,
};

pub use owo_colors::{style, OwoColorize, Style};

#[derive(Clone, Debug, Args)]
#[command(next_help_heading = "Output Options")]
pub struct Options {
    /// Tracing filter for the bootimage builder.
    #[clap(
        long = "trace",
        alias = "log",
        env = "RUST_LOG",
        default_value = "info",
        global = true
    )]
    trace_filter: tracing_subscriber::filter::Targets,

    /// Whether to emit colors in output.
    #[clap(
            long,
            env = "CARGO_TERM_COLORS",
            default_value_t = ColorMode::Auto,
            global = true,
        )]
    color: ColorMode,
}

pub const CARGO_LOG_WIDTH: usize = 12;

#[derive(Copy, Clone, Debug, Eq, PartialEq, clap::ValueEnum)]
#[repr(u8)]
#[clap(rename_all = "lower")]
enum ColorMode {
    /// Determine whether to color output based on whether or not stderr is a
    /// TTY.
    Auto = 0,
    /// Always color output.
    Always = 1,
    /// Never color output.
    Never = 2,
}

// === impl OutputOptions ===

impl Options {
    pub fn init(&self) -> miette::Result<()> {
        use tracing_subscriber::prelude::*;
        let fmt = tracing_subscriber::fmt::layer()
            .event_format(CargoFormatter {
                styles: Styles::new(self.color),
            })
            .with_writer(std::io::stderr);

        tracing_subscriber::registry()
            .with(fmt)
            .with(self.trace_filter.clone())
            .try_init()
            .into_diagnostic()?;
        Ok(())
    }
}

// === impl ColorMode ===

impl fmt::Display for ColorMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.pad(self.as_str())
    }
}

impl ColorMode {
    fn if_color(self, style: owo_colors::Style) -> owo_colors::Style {
        if self.should_color_stderr() {
            style
        } else {
            owo_colors::style()
        }
    }

    fn as_str(&self) -> &'static str {
        match self {
            ColorMode::Auto => "auto",
            ColorMode::Always => "always",
            ColorMode::Never => "never",
        }
    }

    fn should_color_stderr(self) -> bool {
        match self {
            ColorMode::Auto => supports_color::on(supports_color::Stream::Stderr)
                .map(|c| c.has_basic)
                .unwrap_or(false),
            ColorMode::Always => true,
            ColorMode::Never => false,
        }
    }
}

#[derive(Debug)]
struct CargoFormatter {
    styles: Styles,
}

struct Visitor<'styles, 'writer, 'meta> {
    writer: Writer<'writer>,
    is_empty: bool,
    styles: &'styles Styles,
    did_cargo_format: bool,
    meta: &'meta Metadata<'meta>,
}

#[derive(Debug)]
struct Styles {
    error: Style,
    warn: Style,
    info: Style,
    debug: Style,
    trace: Style,
    pipes: Style,
    bold: Style,
}

struct Prefixed<T> {
    prefix: &'static str,
    val: T,
}

impl<S, N> FormatEvent<S, N> for CargoFormatter
where
    S: Subscriber + for<'a> LookupSpan<'a>,
    N: for<'a> FormatFields<'a> + 'static,
{
    fn format_event(
        &self,
        ctx: &FmtContext<'_, S, N>,
        mut writer: Writer<'_>,
        event: &Event<'_>,
    ) -> fmt::Result {
        use tracing_log::NormalizeEvent;

        let normalized_meta = event.normalized_metadata();
        let metadata = normalized_meta.as_ref().unwrap_or_else(|| event.metadata());

        let fmt_spans = {
            let mut visitor = self.visitor(metadata, writer.by_ref());
            event.record(&mut visitor);
            !visitor.did_cargo_format && ctx.lookup_current().is_some()
        };

        writer.write_char('\n')?;
        if fmt_spans {
            writeln!(
                writer,
                "   {} {}{}",
                "-->".style(self.styles.pipes),
                metadata.file().unwrap_or_else(|| metadata.target()),
                DisplayOpt(metadata.line().map(Prefixed::prefix(":"))),
            )?;
            ctx.visit_spans(|span| {
                let exts = span.extensions();
                let fields = exts
                    .get::<FormattedFields<N>>()
                    .map(|f| f.fields.as_str())
                    .unwrap_or("");
                writeln!(
                    writer,
                    "    {} {}{}{}",
                    "|".style(self.styles.pipes),
                    span.name().style(self.styles.bold),
                    if fields.is_empty() { "" } else { ": " },
                    fields
                )
            })?;

            writer.write_char('\n')?;
        }

        Ok(())
    }
}

impl CargoFormatter {
    fn visitor<'styles, 'writer, 'meta>(
        &'styles self,
        meta: &'meta Metadata<'meta>,
        writer: Writer<'writer>,
    ) -> Visitor<'styles, 'writer, 'meta> {
        Visitor {
            meta,
            writer,
            is_empty: true,
            styles: &self.styles,
            did_cargo_format: false,
        }
    }
}

// === impl Visitor ===

impl<'styles, 'writer, 'meta> Visitor<'styles, 'writer, 'meta> {
    const MESSAGE: &'static str = "message";
    const INDENT: usize = 12;
}

impl<'styles, 'writer, 'meta> Visit for Visitor<'styles, 'writer, 'meta> {
    fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
        // Skip metadata from the `log` crate.
        if field.name().starts_with("log.") {
            return;
        }
        let level = *self.meta.level();

        // If we're writing the first field of the event, either emit cargo
        // formatting, or a level header.
        if self.is_empty {
            // If the level is `INFO` and it has a message that's
            // shaped like a cargo log tag, emit the cargo tag followed by the
            // rest of the message.
            if field.name() == Self::MESSAGE {
                let message = format!("{value:?}");
                if let Some((tag, message)) = message.as_str().split_once(' ') {
                    if level >= Level::INFO
                        && tag.len() <= Self::INDENT
                        && (level == Level::INFO || (tag.ends_with("ed") || tag.ends_with("ing")))
                    {
                        let tag = tag.to_title_case();
                        let style = match level {
                            Level::TRACE => self.styles.trace,
                            Level::DEBUG => self.styles.debug,
                            _ => self.styles.info,
                        };

                        let _ = write!(
                            self.writer,
                            "{:>indent$} ",
                            tag.style(style),
                            indent = Self::INDENT
                        );

                        let _ = self.writer.write_str(message);
                        self.is_empty = false;
                        self.did_cargo_format = true;
                        return;
                    }
                }
            }

            // Otherwise, emit a level tag.
            let target = self.meta.target();
            let (level_tag, style) = match level {
                Level::ERROR => ("error", self.styles.error),
                Level::WARN => ("warning", self.styles.warn),
                Level::INFO => ("info", self.styles.info),
                Level::DEBUG => ("debug", self.styles.debug),
                Level::TRACE => ("trace", self.styles.trace),
            };
            let _ = write!(
                self.writer,
                "{}{}{}{}{} ",
                level_tag.style(style),
                "[".style(style),
                target.style(style),
                "]".style(style),
                ":".style(self.styles.bold),
            );
        } else {
            // If this is *not* the first field of the event, prefix it with a
            // comma for the preceding field, instead of a cargo tag or level tag.
            let _ = self.writer.write_str(", ");
        }

        if field.name() == Self::MESSAGE {
            let _ = write!(self.writer, "{value:?}");
        } else {
            let _ = write!(
                self.writer,
                "{}{} {:?}",
                field.name().style(self.styles.bold),
                ":".style(self.styles.bold),
                value
            );
        }

        self.is_empty = false;
    }
}

// === impl Styles ===

impl Styles {
    fn new(colors: ColorMode) -> Self {
        Self {
            error: colors.if_color(style().red().bold()),
            warn: colors.if_color(style().yellow().bold()),
            info: colors.if_color(style().green().bold()),
            debug: colors.if_color(style().blue().bold()),
            trace: colors.if_color(style().purple().bold()),
            bold: colors.if_color(style().bold()),
            pipes: colors.if_color(style().blue().bold()),
        }
    }
}

impl<T> Prefixed<T> {
    fn prefix(prefix: &'static str) -> impl Fn(T) -> Prefixed<T> {
        move |val| Prefixed { val, prefix }
    }
}

impl<T> fmt::Display for Prefixed<T>
where
    T: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}{}", self.prefix, self.val)
    }
}

impl<T> fmt::Debug for Prefixed<T>
where
    T: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}{:?}", self.prefix, self.val)
    }
}

struct DisplayOpt<T>(Option<T>);

impl<T> fmt::Display for DisplayOpt<T>
where
    T: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(ref val) = self.0 {
            fmt::Display::fmt(val, f)?;
        }

        Ok(())
    }
}