Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions crates/oxc_span/src/source_type/error.rs
Original file line number Diff line number Diff line change
@@ -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 {}
15 changes: 7 additions & 8 deletions crates/oxc_span/src/source_type/mod.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
use std::path::Path;

mod error;
mod types;

pub use error::UnknownExtension;
use oxc_allocator::{Allocator, CloneIn};
use std::path::Path;
pub use types::*;

#[derive(Debug)]
pub struct UnknownExtension(pub String);

impl Default for SourceType {
fn default() -> Self {
Self {
Expand Down Expand Up @@ -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()
Expand All @@ -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"),
)
})?;
Expand All @@ -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()));
}
};

Expand Down