swc_error_reporters/
handler.rs

1use std::{env, fmt, io::Write, mem::take, sync::Arc};
2
3use anyhow::Error;
4use miette::{GraphicalReportHandler, GraphicalTheme};
5use once_cell::sync::Lazy;
6use parking_lot::Mutex;
7use swc_common::{
8    errors::{ColorConfig, Emitter, Handler, HANDLER},
9    sync::Lrc,
10    SourceMap,
11};
12
13use crate::{
14    json_emitter::{JsonEmitter, JsonEmitterConfig},
15    PrettyEmitter, PrettyEmitterConfig,
16};
17
18#[derive(Clone, Default)]
19struct LockedWriter(Arc<Mutex<Vec<u8>>>);
20
21impl Write for LockedWriter {
22    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
23        let mut lock = self.0.lock();
24
25        lock.extend_from_slice(buf);
26
27        Ok(buf.len())
28    }
29
30    fn flush(&mut self) -> std::io::Result<()> {
31        Ok(())
32    }
33}
34
35impl fmt::Write for LockedWriter {
36    fn write_str(&mut self, s: &str) -> fmt::Result {
37        self.write(s.as_bytes()).map_err(|_| fmt::Error)?;
38
39        Ok(())
40    }
41}
42
43#[derive(Debug, Clone)]
44pub struct HandlerOpts {
45    /// [ColorConfig::Auto] is the default, and it will print colors unless the
46    /// environment variable `NO_COLOR` is not 1.
47    pub color: ColorConfig,
48
49    /// Defaults to `false`.
50    pub skip_filename: bool,
51}
52
53impl Default for HandlerOpts {
54    fn default() -> Self {
55        Self {
56            color: ColorConfig::Auto,
57            skip_filename: false,
58        }
59    }
60}
61
62fn to_miette_reporter(color: ColorConfig) -> GraphicalReportHandler {
63    match color {
64        ColorConfig::Auto => {
65            if cfg!(target_arch = "wasm32") {
66                return to_miette_reporter(ColorConfig::Always).with_context_lines(3);
67            }
68
69            static ENABLE: Lazy<bool> =
70                Lazy::new(|| !env::var("NO_COLOR").map(|s| s == "1").unwrap_or(false));
71
72            if *ENABLE {
73                to_miette_reporter(ColorConfig::Always)
74            } else {
75                to_miette_reporter(ColorConfig::Never)
76            }
77        }
78        ColorConfig::Always => GraphicalReportHandler::default(),
79        ColorConfig::Never => GraphicalReportHandler::default().with_theme(GraphicalTheme::none()),
80    }
81    .with_context_lines(3)
82}
83
84/// Try operation with a [Handler] and prints the errors as a [String] wrapped
85/// by [Err].
86pub fn try_with_handler<F, Ret>(
87    cm: Lrc<SourceMap>,
88    config: HandlerOpts,
89    op: F,
90) -> Result<Ret, Error>
91where
92    F: FnOnce(&Handler) -> Result<Ret, Error>,
93{
94    try_with_handler_inner(cm, config, op, false)
95}
96
97/// Try operation with a [Handler] and prints the errors as a [String] wrapped
98/// by [Err].
99pub fn try_with_json_handler<F, Ret>(
100    cm: Lrc<SourceMap>,
101    config: HandlerOpts,
102    op: F,
103) -> Result<Ret, Error>
104where
105    F: FnOnce(&Handler) -> Result<Ret, Error>,
106{
107    try_with_handler_inner(cm, config, op, true)
108}
109
110fn try_with_handler_inner<F, Ret>(
111    cm: Lrc<SourceMap>,
112    config: HandlerOpts,
113    op: F,
114    json: bool,
115) -> Result<Ret, Error>
116where
117    F: FnOnce(&Handler) -> Result<Ret, Error>,
118{
119    let wr = Box::<LockedWriter>::default();
120
121    let emitter: Box<dyn Emitter> = if json {
122        Box::new(JsonEmitter::new(
123            cm,
124            wr.clone(),
125            JsonEmitterConfig {
126                skip_filename: config.skip_filename,
127            },
128        ))
129    } else {
130        Box::new(PrettyEmitter::new(
131            cm,
132            wr.clone(),
133            to_miette_reporter(config.color),
134            PrettyEmitterConfig {
135                skip_filename: config.skip_filename,
136            },
137        ))
138    };
139    let handler = Handler::with_emitter(true, false, emitter);
140
141    let ret = HANDLER.set(&handler, || op(&handler));
142
143    if handler.has_errors() {
144        let mut lock = wr.0.lock();
145        let error = take(&mut *lock);
146
147        let msg = String::from_utf8(error).expect("error string should be utf8");
148
149        match ret {
150            Ok(_) => Err(anyhow::anyhow!(msg)),
151            Err(err) => Err(err.context(msg)),
152        }
153    } else {
154        ret
155    }
156}