fix(linter) Report error instead of panicing if the file fails to open (#1098)

closes #1093


e.g.

```
RUST_BACKTRACE=full cargo run  --bin=oxc_cli lint -D=suspicious -D=style -D=restriction -D=pedantic -D=nursery -D=correctness -A=no-useless-escape ./tasks/coverage/typescript/tests/cases/compiler/corrupted.ts
```

Results in:
```

  × Failed to open file
  help: Failed to open file "./tasks/coverage/typescript/tests/cases/compiler/corrupted.ts" with error "stream did not contain valid UTF-8"

Finished in 10ms on 1 file with 126 rules using 12 threads.
Found 0 warnings and 1 error.
```
This commit is contained in:
Cameron 2023-10-30 01:53:28 +00:00 committed by GitHub
parent 0194dbd79d
commit cef075df17
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 3 deletions

View file

@ -25,3 +25,8 @@ use thiserror::Error;
#[error("File is too long to fit on the screen")]
#[diagnostic(help("{0:?} seems like a minified file"))]
pub struct MinifiedFileError(pub PathBuf);
#[derive(Debug, Error, Diagnostic)]
#[error("Failed to open file")]
#[diagnostic(help("Failed to open file {0:?} with error \"{1}\""))]
pub struct FailedToOpenFileError(pub PathBuf, pub std::io::Error);

View file

@ -11,7 +11,7 @@ use rayon::{iter::ParallelBridge, prelude::ParallelIterator};
use rustc_hash::FxHashSet;
use oxc_allocator::Allocator;
use oxc_diagnostics::{DiagnosticSender, DiagnosticService};
use oxc_diagnostics::{DiagnosticSender, DiagnosticService, Error, FailedToOpenFileError};
use oxc_parser::Parser;
use oxc_resolver::{ResolveOptions, Resolver};
use oxc_semantic::{ModuleRecord, SemanticBuilder};
@ -140,8 +140,18 @@ impl Runtime {
}
let allocator = Allocator::default();
let source_text =
fs::read_to_string(path).unwrap_or_else(|_| panic!("Failed to read {path:?}"));
let source_text = match fs::read_to_string(path) {
Ok(source_text) => source_text,
Err(e) => {
tx_error
.send(Some((
path.to_path_buf(),
vec![Error::new(FailedToOpenFileError(path.to_path_buf(), e))],
)))
.unwrap();
return;
}
};
let mut messages =
self.process_source(path, &allocator, &source_text, source_type, true, tx_error);