mirror of
https://github.com/danbulant/oxc
synced 2026-05-19 12:19:15 +00:00
feat(span/source-type): impl Display and Error for UnknownExtension (#5240)
This commit is contained in:
parent
a6bb3b1b98
commit
f5e05db302
2 changed files with 37 additions and 9 deletions
29
crates/oxc_span/src/source_type/error.rs
Normal file
29
crates/oxc_span/src/source_type/error.rs
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
use std::{borrow::Cow, error::Error, fmt, ops::Deref};
|
||||
|
||||
/// Error returned by [`SourceType::from_path`] when the file extension is not
|
||||
/// found or recognized.
|
||||
///
|
||||
/// [`SourceType::from_path`]: `crate::SourceType::from_path`
|
||||
#[derive(Debug)]
|
||||
pub struct UnknownExtension(/* msg */ pub(crate) Cow<'static, str>);
|
||||
|
||||
impl Deref for UnknownExtension {
|
||||
type Target = str;
|
||||
fn deref(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
impl UnknownExtension {
|
||||
#[inline]
|
||||
pub(crate) fn new<S: Into<Cow<'static, str>>>(ext: S) -> Self {
|
||||
Self(ext.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for UnknownExtension {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "Unknown file extension: {}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for UnknownExtension {}
|
||||
|
|
@ -1,11 +1,10 @@
|
|||
use std::path::Path;
|
||||
|
||||
mod error;
|
||||
mod types;
|
||||
use oxc_allocator::{Allocator, CloneIn};
|
||||
pub use types::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct UnknownExtension(pub String);
|
||||
pub use error::UnknownExtension;
|
||||
use oxc_allocator::{Allocator, CloneIn};
|
||||
use std::path::Path;
|
||||
pub use types::*;
|
||||
|
||||
impl Default for SourceType {
|
||||
fn default() -> Self {
|
||||
|
|
@ -160,7 +159,7 @@ impl SourceType {
|
|||
.as_ref()
|
||||
.file_name()
|
||||
.and_then(std::ffi::OsStr::to_str)
|
||||
.ok_or_else(|| UnknownExtension("Please provide a valid file name.".to_string()))?;
|
||||
.ok_or_else(|| UnknownExtension::new("Please provide a valid file name."))?;
|
||||
|
||||
let extension = path
|
||||
.as_ref()
|
||||
|
|
@ -169,7 +168,7 @@ impl SourceType {
|
|||
.filter(|s| VALID_EXTENSIONS.contains(s))
|
||||
.ok_or_else(|| {
|
||||
let path = path.as_ref().to_string_lossy();
|
||||
UnknownExtension(
|
||||
UnknownExtension::new(
|
||||
format!("Please provide a valid file extension for {path}: .js, .mjs, .jsx or .cjs for JavaScript, or .ts, .d.ts, .mts, .cts or .tsx for TypeScript"),
|
||||
)
|
||||
})?;
|
||||
|
|
@ -192,7 +191,7 @@ impl SourceType {
|
|||
#[cfg(debug_assertions)]
|
||||
unreachable!();
|
||||
#[cfg(not(debug_assertions))]
|
||||
return Err(UnknownExtension(format!("Unknown extension: {}", extension)));
|
||||
return Err(UnknownExtension(format!("Unknown extension: {}", extension).into()));
|
||||
}
|
||||
};
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue