oxc_diagnostics 0.155.0

A collection of JavaScript tools written in Rust.
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
use std::{
    borrow::Cow,
    io::{ErrorKind, Write},
    path::{Path, PathBuf},
    sync::{Arc, mpsc},
};

use cow_utils::CowUtils;
use percent_encoding::AsciiSet;
#[cfg(not(windows))]
use std::fs::canonicalize as strict_canonicalize;

use crate::{
    Error, NamedSource, OxcDiagnostic, Severity,
    reporter::{DiagnosticReporter, DiagnosticResult},
};

pub type DiagnosticSender = mpsc::Sender<Vec<Error>>;
type DiagnosticReceiver = mpsc::Receiver<Vec<Error>>;

/// Listens for diagnostics sent over a [channel](DiagnosticSender) by some job, and
/// formats/reports them to the user.
///
/// [`DiagnosticService`] is designed to support multi-threaded jobs that may produce
/// reports. These jobs can send messages to the service over its multi-producer,
/// single-consumer channel.
///
/// # Example
/// ```rust,ignore
/// use std::{io, thread};
/// use oxc_diagnostics::{OxcDiagnostic, DiagnosticService, GraphicalReportHandler};
///
/// // Create a service with a graphical reporter
/// let (mut service, sender) = DiagnosticService::new(Box::new(GraphicalReportHandler::new()));
///
/// // Spawn a thread that does work and reports diagnostics
/// thread::spawn(move || {
///     sender.send(vec![OxcDiagnostic::error("Something went wrong").into()]).unwrap();
///
///     // The service will stop listening when all senders are dropped.
///     // No explicit termination signal is needed.
/// });
///
/// // Listen for and process messages
/// service.run(&mut io::stdout().lock());
/// ```
pub struct DiagnosticService {
    reporter: Box<dyn DiagnosticReporter>,

    /// Whether to suppress warnings and report only errors.
    quiet: bool,

    /// Whether to suppress all diagnostics.
    silent: bool,

    /// Warning threshold used to determine the exit status.
    max_warnings: Option<usize>,

    receiver: DiagnosticReceiver,
}

impl DiagnosticService {
    /// Create a new [`DiagnosticService`] that will render and report diagnostics using the
    /// provided [`DiagnosticReporter`].
    pub fn new(reporter: Box<dyn DiagnosticReporter>) -> (Self, DiagnosticSender) {
        let (sender, receiver) = mpsc::channel();
        (Self { reporter, quiet: false, silent: false, max_warnings: None, receiver }, sender)
    }

    /// Set to `true` to only report errors and ignore warnings.
    ///
    /// Use [`with_silent`](DiagnosticService::with_silent) to disable reporting entirely.
    ///
    /// Default: `false`
    #[must_use]
    pub fn with_quiet(mut self, yes: bool) -> Self {
        self.quiet = yes;
        self
    }

    /// Set to `true` to disable reporting entirely.
    ///
    /// Use [`with_quiet`](DiagnosticService::with_quiet) to only disable reporting on warnings.
    ///
    /// Default is `false`.
    #[must_use]
    pub fn with_silent(mut self, yes: bool) -> Self {
        self.silent = yes;
        self
    }

    /// Specify a warning threshold, which can be used to force exit with an error status if there
    /// are too many warning-level rule violations in your project. Errors do not count towards the
    /// warning limit.
    ///
    /// Use [`DiagnosticResult`](DiagnosticResult::max_warnings_exceeded) to check if too
    /// many warnings have been received.
    ///
    /// Default: [`None`]
    #[must_use]
    pub fn with_max_warnings(mut self, max_warnings: Option<usize>) -> Self {
        self.max_warnings = max_warnings;
        self
    }

    /// Check if the max warning threshold, as set by
    /// [`with_max_warnings`](DiagnosticService::with_max_warnings), has been exceeded.
    fn max_warnings_exceeded(&self, warnings_count: usize) -> bool {
        self.max_warnings.is_some_and(|max_warnings| warnings_count > max_warnings)
    }

    /// Attach the source code and path to diagnostics, converting them into [`Error`]s.
    pub fn wrap_diagnostics<C: AsRef<Path>, P: AsRef<Path>>(
        cwd: C,
        path: P,
        source_text: &str,
        diagnostics: Vec<OxcDiagnostic>,
    ) -> Vec<Error> {
        let source = Self::named_source(cwd, path, source_text);
        diagnostics
            .into_iter()
            .map(|diagnostic| diagnostic.with_source_code(Arc::clone(&source)))
            .collect()
    }

    /// The source code and display path [`wrap_diagnostics`](DiagnosticService::wrap_diagnostics) attaches. Each
    /// call copies `source_text`, so a caller that wraps one file's diagnostics a few at a time should build this once
    /// per file and share it with [`OxcDiagnostic::with_source_code`].
    pub fn named_source<C: AsRef<Path>, P: AsRef<Path>>(
        cwd: C,
        path: P,
        source_text: &str,
    ) -> Arc<NamedSource<String>> {
        // TODO: This causes snapshots to fail when running tests through a JetBrains terminal.
        let is_jetbrains =
            std::env::var("TERMINAL_EMULATOR").is_ok_and(|x| x.eq("JetBrains-JediTerm"));

        let path_ref = path.as_ref();
        let path_display = if is_jetbrains { from_file_path(path_ref) } else { None }
            .unwrap_or_else(|| {
                let relative_path =
                    path_ref.strip_prefix(cwd).unwrap_or(path_ref).to_string_lossy();
                let normalized_path = relative_path.cow_replace('\\', "/");
                normalized_path.to_string()
            });

        Arc::new(NamedSource::new(path_display, source_text.to_owned()))
    }

    /// # Panics
    ///
    /// * When the writer fails to write
    ///
    /// The result is also passed to the reporter, but remains part of this API because callers use
    /// it to determine their exit status.
    pub fn run(&mut self, writer: &mut dyn Write) -> DiagnosticResult {
        let mut warnings_count: usize = 0;
        let mut errors_count: usize = 0;
        let supports_minified_file_fallback = self.reporter.supports_minified_file_fallback();

        while let Ok(diagnostics) = self.receiver.recv() {
            let mut diagnostics_to_render = Vec::with_capacity(diagnostics.len());
            for diagnostic in diagnostics {
                match diagnostic.severity() {
                    Some(Severity::Warning) => {
                        warnings_count += 1;
                        // `--quiet` follows ESLint by suppressing warnings but not errors.
                        if self.quiet {
                            continue;
                        }
                    }
                    Some(Severity::Error) | None => {
                        errors_count += 1;
                    }
                    Some(Severity::Advice) => {}
                }

                if !self.silent {
                    diagnostics_to_render.push(diagnostic);
                }
            }

            if diagnostics_to_render.is_empty() {
                continue;
            }

            let mut is_minified = false;
            let mut path = None;
            if supports_minified_file_fallback {
                self.reporter.render_errors_until(
                    diagnostics_to_render,
                    &mut |source_name, rendered| {
                        // Setting to 1200 because graphical output may contain ansi escape codes
                        // and other decorations.
                        if rendered.lines().any(|line| line.len() >= 1200) {
                            is_minified = true;
                            path = source_name.map(ToString::to_string);
                            false
                        } else {
                            writer
                                .write_all(rendered.as_bytes())
                                .or_else(Self::check_for_writer_error)
                                .unwrap();
                            true
                        }
                    },
                );
            } else {
                self.reporter.render_errors(diagnostics_to_render, &mut |rendered| {
                    writer
                        .write_all(rendered.as_bytes())
                        .or_else(Self::check_for_writer_error)
                        .unwrap();
                });
            }

            if is_minified {
                let mut diagnostic = OxcDiagnostic::warn("File is too long to fit on the screen");
                if let Some(path) = path {
                    diagnostic = diagnostic.with_help(format!("{path} seems like a minified file"));
                }
                if let Some(err_str) = self.reporter.render_error(diagnostic.into()) {
                    writer
                        .write_all(err_str.as_bytes())
                        .or_else(Self::check_for_writer_error)
                        .unwrap();
                }
            }
        }

        let result = DiagnosticResult::new(
            warnings_count,
            errors_count,
            self.max_warnings_exceeded(warnings_count),
        );

        if let Some(finish_output) = self.reporter.finish(&result) {
            writer
                .write_all(finish_output.as_bytes())
                .or_else(Self::check_for_writer_error)
                .unwrap();
        }

        writer.flush().or_else(Self::check_for_writer_error).unwrap();

        result
    }

    fn check_for_writer_error(error: std::io::Error) -> Result<(), std::io::Error> {
        // Do not panic when the process is killed (e.g. piping into `less`).
        if matches!(
            error.kind(),
            ErrorKind::Interrupted | ErrorKind::BrokenPipe | ErrorKind::WouldBlock
        ) {
            Ok(())
        } else {
            Err(error)
        }
    }
}

// The following from_file_path and strict_canonicalize implementations are from tower-lsp-community/tower-lsp-server
// available under the MIT License or Apache 2.0 License.
//
// Copyright (c) 2023 Eyal Kalderon
// https://github.com/tower-lsp-community/tower-lsp-server/blob/85506ddcbd108c514438e0b62e0eb858c812adcf/src/uri_ext.rs

const ASCII_SET: AsciiSet =
    // RFC3986 allows only alphanumeric characters, `-`, `.`, `_`, and `~` in the path.
    percent_encoding::NON_ALPHANUMERIC
        .remove(b'-')
        .remove(b'.')
        .remove(b'_')
        .remove(b'~')
        // we do not want path separators to be percent-encoded
        .remove(b'/');

fn from_file_path<A: AsRef<Path>>(path: A) -> Option<String> {
    let path = path.as_ref();

    let fragment = if path.is_absolute() {
        Cow::Borrowed(path)
    } else {
        match strict_canonicalize(path) {
            Ok(path) => Cow::Owned(path),
            Err(_) => return None,
        }
    };

    if cfg!(windows) {
        // we want to write a triple-slash path for Windows paths
        // it's a shorthand for `file://localhost/C:/Windows` with the `localhost` omitted.
        let mut components = fragment.components();
        let drive = components.next();

        if let Some(drive) = drive {
            Some(format!(
                "file:///{}{}",
                drive.as_os_str().to_string_lossy().cow_replace('\\', "/"),
                // Skip encoding ":" in the drive "C:/".
                percent_encoding::utf8_percent_encode(
                    &components.collect::<PathBuf>().to_string_lossy().cow_replace('\\', "/"),
                    &ASCII_SET
                )
            ))
        } else {
            Some(format!(
                "file:///{}",
                percent_encoding::utf8_percent_encode(
                    &components.collect::<PathBuf>().to_string_lossy().cow_replace('\\', "/"),
                    &ASCII_SET
                )
            ))
        }
    } else {
        Some(format!(
            "file://{}",
            percent_encoding::utf8_percent_encode(&fragment.to_string_lossy(), &ASCII_SET)
        ))
    }
}

/// On Windows, rewrites the wide path prefix `\\?\C:` to `C:`
/// Source: <https://stackoverflow.com/a/70970317>
#[inline]
#[cfg(windows)]
fn strict_canonicalize<P: AsRef<Path>>(path: P) -> std::io::Result<PathBuf> {
    use std::io;

    fn impl_(path: &Path) -> std::io::Result<PathBuf> {
        let head = path.components().next().ok_or(io::Error::other("empty path"))?;
        let disk_;
        let head = if let std::path::Component::Prefix(prefix) = head {
            if let std::path::Prefix::VerbatimDisk(disk) = prefix.kind() {
                disk_ = format!("{}:", disk as char);
                Path::new(&disk_)
                    .components()
                    .next()
                    .ok_or(io::Error::other("failed to parse disk component"))?
            } else {
                head
            }
        } else {
            head
        };
        Ok(std::iter::once(head).chain(path.components().skip(1)).collect())
    }

    let canon = std::fs::canonicalize(path)?;
    impl_(&canon)
}

#[cfg(test)]
mod tests {
    use std::{
        path::PathBuf,
        sync::{
            Arc, Mutex,
            atomic::{AtomicUsize, Ordering},
        },
    };

    use crate::{
        Error, NamedSource, OxcDiagnostic,
        reporter::{DiagnosticReporter, DiagnosticResult},
        service::from_file_path,
    };

    use super::DiagnosticService;

    fn with_schema(path: &str) -> String {
        const EXPECTED_SCHEMA: &str = if cfg!(windows) { "file:///" } else { "file://" };
        format!("{EXPECTED_SCHEMA}{path}")
    }

    #[test]
    #[cfg(windows)]
    fn test_idempotent_canonicalization() {
        use crate::service::strict_canonicalize;
        use std::path::Path;

        let lhs = strict_canonicalize(Path::new(".")).unwrap();
        let rhs = strict_canonicalize(&lhs).unwrap();
        assert_eq!(lhs, rhs);
    }

    #[test]
    #[cfg(unix)]
    fn test_path_to_uri() {
        let paths = [
            PathBuf::from("/some/path/to/file.txt"),
            PathBuf::from("/some/path/to/file with spaces.txt"),
            PathBuf::from("/some/path/[[...rest]]/file.txt"),
            PathBuf::from("/some/path/to/файл.txt"),
            PathBuf::from("/some/path/to/文件.txt"),
        ];

        let expected = [
            with_schema("/some/path/to/file.txt"),
            with_schema("/some/path/to/file%20with%20spaces.txt"),
            with_schema("/some/path/%5B%5B...rest%5D%5D/file.txt"),
            with_schema("/some/path/to/%D1%84%D0%B0%D0%B9%D0%BB.txt"),
            with_schema("/some/path/to/%E6%96%87%E4%BB%B6.txt"),
        ];

        for (path, expected) in paths.iter().zip(expected) {
            let uri = from_file_path(path).unwrap();
            assert_eq!(uri.clone(), expected);
        }
    }

    #[test]
    #[cfg(windows)]
    fn test_path_to_uri_windows() {
        let paths = [
            PathBuf::from("C:\\some\\path\\to\\file.txt"),
            PathBuf::from("C:\\some\\path\\to\\file with spaces.txt"),
            PathBuf::from("C:\\some\\path\\[[...rest]]\\file.txt"),
            PathBuf::from("C:\\some\\path\\to\\файл.txt"),
            PathBuf::from("C:\\some\\path\\to\\文件.txt"),
        ];

        let expected = [
            with_schema("C:/some/path/to/file.txt"),
            with_schema("C:/some/path/to/file%20with%20spaces.txt"),
            with_schema("C:/some/path/%5B%5B...rest%5D%5D/file.txt"),
            with_schema("C:/some/path/to/%D1%84%D0%B0%D0%B9%D0%BB.txt"),
            with_schema("C:/some/path/to/%E6%96%87%E4%BB%B6.txt"),
        ];

        for (path, expected) in paths.iter().zip(expected) {
            let uri = from_file_path(path).unwrap();
            assert_eq!(uri, expected);
        }
    }

    #[test]
    fn preserves_long_lines_for_single_line_reporters() {
        #[derive(Default)]
        struct LongLineReporter {
            fallback_enabled: bool,
        }

        impl DiagnosticReporter for LongLineReporter {
            fn finish(&mut self, _result: &DiagnosticResult) -> Option<String> {
                None
            }

            fn supports_minified_file_fallback(&self) -> bool {
                self.fallback_enabled
            }

            fn render_error(&mut self, error: Error) -> Option<String> {
                let message = error.to_string();
                if message == "original diagnostic" {
                    Some(format!("{}\n", "x".repeat(1200)))
                } else {
                    Some(format!("{message}\n"))
                }
            }
        }
        let (mut service, sender) =
            DiagnosticService::new(Box::new(LongLineReporter { fallback_enabled: false }));
        sender.send(vec![OxcDiagnostic::warn("original diagnostic").into()]).unwrap();
        drop(sender);

        let mut output = Vec::new();
        service.run(&mut output);
        let output = String::from_utf8(output).unwrap();

        assert_eq!(output, format!("{}\n", "x".repeat(1200)));
    }

    struct BatchReporter(Arc<Mutex<Vec<usize>>>);

    impl DiagnosticReporter for BatchReporter {
        fn finish(&mut self, _result: &DiagnosticResult) -> Option<String> {
            None
        }

        fn render_errors(&mut self, errors: Vec<Error>, emit: &mut dyn FnMut(&str)) {
            self.0.lock().unwrap().push(errors.len());
            let output =
                errors.into_iter().map(|error| error.to_string()).collect::<Vec<_>>().join(",");
            emit(&output);
        }

        fn supports_minified_file_fallback(&self) -> bool {
            false
        }

        fn render_error(&mut self, _error: Error) -> Option<String> {
            None
        }
    }

    #[test]
    fn renders_a_filtered_batch() {
        let batch_sizes = Arc::new(Mutex::new(Vec::new()));
        let (service, sender) =
            DiagnosticService::new(Box::new(BatchReporter(Arc::clone(&batch_sizes))));
        let mut service = service.with_quiet(true);
        sender
            .send(vec![
                OxcDiagnostic::warn("hidden warning").into(),
                OxcDiagnostic::error("visible error").into(),
            ])
            .unwrap();
        drop(sender);

        let mut output = Vec::new();
        let result = service.run(&mut output);

        assert_eq!(String::from_utf8(output).unwrap(), "visible error");
        assert_eq!(*batch_sizes.lock().unwrap(), [1]);
        assert_eq!(result.warnings_count(), 1);
        assert_eq!(result.errors_count(), 1);
    }

    struct MinifiedBatchReporter(Arc<AtomicUsize>);

    impl DiagnosticReporter for MinifiedBatchReporter {
        fn finish(&mut self, _result: &DiagnosticResult) -> Option<String> {
            None
        }

        fn render_error(&mut self, error: Error) -> Option<String> {
            let message = error.to_string();
            if message == "File is too long to fit on the screen" {
                Some(format!("{message}: {}\n", error.help().unwrap_or_default()))
            } else {
                self.0.fetch_add(1, Ordering::Relaxed);
                Some(if message == "second" {
                    format!("{}\n", "x".repeat(1200))
                } else {
                    format!("{message}\n")
                })
            }
        }
    }

    #[test]
    fn stops_an_oversized_batch_at_the_minified_file_diagnostic() {
        let rendered = Arc::new(AtomicUsize::new(0));
        let (mut service, sender) =
            DiagnosticService::new(Box::new(MinifiedBatchReporter(Arc::clone(&rendered))));
        sender
            .send(vec![
                OxcDiagnostic::warn("first")
                    .with_source_code(NamedSource::new("normal.js", "source")),
                OxcDiagnostic::warn("second")
                    .with_source_code(NamedSource::new("minified.js", "source")),
                OxcDiagnostic::warn("third").into(),
            ])
            .unwrap();
        drop(sender);

        let mut output = Vec::new();
        let result = service.run(&mut output);

        assert_eq!(
            String::from_utf8(output).unwrap(),
            "first\nFile is too long to fit on the screen: minified.js seems like a minified file\n"
        );
        assert_eq!(rendered.load(Ordering::Relaxed), 2);
        assert_eq!(result.warnings_count(), 3);
    }
}