Unverified Commit f6663b75 authored by Benjamin Woodruff's avatar Benjamin Woodruff Committed by GitHub

Turbopack: Dedupe our two filesystempath extension/extension_ref functions (#92048)

PR is AI-generated

- `extension` and `extension_ref` do the same thing.
- `extension_ref`'s API that returns an `Option` was better than
`extension`'s API that returns a potentially-empty string.
- In some places we were splitting into a stem and extension, and
joining them back to a filename, but those places could just get the
original path's filename.

---------
Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
Co-authored-by: 's avatarClaude <noreply@anthropic.com>
Co-authored-by: 's avatarBenjamin Woodruff <bgw@users.noreply.github.com>
parent 2bf38b01
...@@ -142,7 +142,7 @@ impl Asset for ServerNftJsonAsset { ...@@ -142,7 +142,7 @@ impl Asset for ServerNftJsonAsset {
let DirectoryEntry::File(file) = entry else { let DirectoryEntry::File(file) = entry else {
continue; continue;
}; };
if file.extension() == "js" { if file.extension() == Some("js") {
server_output_assets.push( server_output_assets.push(
base_dir base_dir
.get_relative_path_to(file) .get_relative_path_to(file)
......
...@@ -32,7 +32,6 @@ async fn dynamic_image_metadata_with_generator_source( ...@@ -32,7 +32,6 @@ async fn dynamic_image_metadata_with_generator_source(
) -> Result<Vc<Box<dyn Source>>> { ) -> Result<Vc<Box<dyn Source>>> {
let stem = path.file_stem(); let stem = path.file_stem();
let stem = stem.unwrap_or_default(); let stem = stem.unwrap_or_default();
let ext = path.extension();
let hash = path let hash = path
.read() .read()
...@@ -44,7 +43,7 @@ async fn dynamic_image_metadata_with_generator_source( ...@@ -44,7 +43,7 @@ async fn dynamic_image_metadata_with_generator_source(
let sizes = if use_numeric_sizes { let sizes = if use_numeric_sizes {
"data.width = size.width; data.height = size.height;".to_string() "data.width = size.width; data.height = size.height;".to_string()
} else { } else {
let sizes = if ext == "svg" { let sizes = if path.has_extension(".svg") {
"any" "any"
} else { } else {
"${size.width}x${size.height}" "${size.width}x${size.height}"
...@@ -86,7 +85,7 @@ async fn dynamic_image_metadata_with_generator_source( ...@@ -86,7 +85,7 @@ async fn dynamic_image_metadata_with_generator_source(
}} }}
"#, "#,
exported_fields_excluding_default = exported_fields_excluding_default, exported_fields_excluding_default = exported_fields_excluding_default,
resource_path = StringifyJs(&format!("./{stem}.{ext}")), resource_path = StringifyJs(&format!("./{}", path.file_name())),
pathname_prefix = StringifyJs(&page.to_string()), pathname_prefix = StringifyJs(&page.to_string()),
page_segment = StringifyJs(stem), page_segment = StringifyJs(stem),
sizes = sizes, sizes = sizes,
...@@ -110,7 +109,6 @@ async fn dynamic_image_metadata_without_generator_source( ...@@ -110,7 +109,6 @@ async fn dynamic_image_metadata_without_generator_source(
) -> Result<Vc<Box<dyn Source>>> { ) -> Result<Vc<Box<dyn Source>>> {
let stem = path.file_stem(); let stem = path.file_stem();
let stem = stem.unwrap_or_default(); let stem = stem.unwrap_or_default();
let ext = path.extension();
let hash = path let hash = path
.read() .read()
...@@ -122,7 +120,7 @@ async fn dynamic_image_metadata_without_generator_source( ...@@ -122,7 +120,7 @@ async fn dynamic_image_metadata_without_generator_source(
let sizes = if use_numeric_sizes { let sizes = if use_numeric_sizes {
"data.width = size.width; data.height = size.height;".to_string() "data.width = size.width; data.height = size.height;".to_string()
} else { } else {
let sizes = if ext == "svg" { let sizes = if path.has_extension(".svg") {
"any" "any"
} else { } else {
"${size.width}x${size.height}" "${size.width}x${size.height}"
...@@ -158,7 +156,7 @@ async fn dynamic_image_metadata_without_generator_source( ...@@ -158,7 +156,7 @@ async fn dynamic_image_metadata_without_generator_source(
}} }}
"#, "#,
exported_fields_excluding_default = exported_fields_excluding_default, exported_fields_excluding_default = exported_fields_excluding_default,
resource_path = StringifyJs(&format!("./{stem}.{ext}")), resource_path = StringifyJs(&format!("./{}", path.file_name())),
pathname_prefix = StringifyJs(&page.to_string()), pathname_prefix = StringifyJs(&page.to_string()),
page_segment = StringifyJs(stem), page_segment = StringifyJs(stem),
sizes = sizes, sizes = sizes,
......
...@@ -92,11 +92,11 @@ pub(crate) async fn get_content_type(path: FileSystemPath) -> Result<String> { ...@@ -92,11 +92,11 @@ pub(crate) async fn get_content_type(path: FileSystemPath) -> Result<String> {
let mut ext = path.extension(); let mut ext = path.extension();
let name = stem.unwrap_or_default(); let name = stem.unwrap_or_default();
if ext == "jpg" { if ext == Some("jpg") {
ext = "jpeg" ext = Some("jpeg");
} }
if name == "favicon" && ext == "ico" { if name == "favicon" && ext == Some("ico") {
return Ok("image/x-icon".to_string()); return Ok("image/x-icon".to_string());
} }
if name == "sitemap" { if name == "sitemap" {
...@@ -109,7 +109,9 @@ pub(crate) async fn get_content_type(path: FileSystemPath) -> Result<String> { ...@@ -109,7 +109,9 @@ pub(crate) async fn get_content_type(path: FileSystemPath) -> Result<String> {
return Ok("application/manifest+json".to_string()); return Ok("application/manifest+json".to_string());
} }
if ext == "png" || ext == "jpeg" || ext == "ico" || ext == "svg" { if let Some(ext) = ext
&& matches!(ext, "png" | "jpeg" | "ico" | "svg")
{
return Ok(mime_guess::from_ext(ext) return Ok(mime_guess::from_ext(ext)
.first_or_octet_stream() .first_or_octet_stream()
.to_string()); .to_string());
......
...@@ -215,7 +215,6 @@ async fn static_route_source(mode: NextMode, path: FileSystemPath) -> Result<Vc< ...@@ -215,7 +215,6 @@ async fn static_route_source(mode: NextMode, path: FileSystemPath) -> Result<Vc<
async fn dynamic_text_route_source(path: FileSystemPath) -> Result<Vc<Box<dyn Source>>> { async fn dynamic_text_route_source(path: FileSystemPath) -> Result<Vc<Box<dyn Source>>> {
let stem = path.file_stem(); let stem = path.file_stem();
let stem = stem.unwrap_or_default(); let stem = stem.unwrap_or_default();
let ext = path.extension();
let content_type = get_content_type(path.clone()).await?; let content_type = get_content_type(path.clone()).await?;
...@@ -250,7 +249,7 @@ async fn dynamic_text_route_source(path: FileSystemPath) -> Result<Vc<Box<dyn So ...@@ -250,7 +249,7 @@ async fn dynamic_text_route_source(path: FileSystemPath) -> Result<Vc<Box<dyn So
export * from {resource_path} export * from {resource_path}
"#, "#,
resource_path = StringifyJs(&format!("./{stem}.{ext}")), resource_path = StringifyJs(&format!("./{}", path.file_name())),
content_type = StringifyJs(&content_type), content_type = StringifyJs(&content_type),
file_type = StringifyJs(&stem), file_type = StringifyJs(&stem),
cache_control = StringifyJs(CACHE_HEADER_REVALIDATE), cache_control = StringifyJs(CACHE_HEADER_REVALIDATE),
...@@ -270,7 +269,6 @@ async fn dynamic_sitemap_route_with_generate_source( ...@@ -270,7 +269,6 @@ async fn dynamic_sitemap_route_with_generate_source(
) -> Result<Vc<Box<dyn Source>>> { ) -> Result<Vc<Box<dyn Source>>> {
let stem = path.file_stem(); let stem = path.file_stem();
let stem = stem.unwrap_or_default(); let stem = stem.unwrap_or_default();
let ext = path.extension();
let content_type = get_content_type(path.clone()).await?; let content_type = get_content_type(path.clone()).await?;
let code = formatdoc! { let code = formatdoc! {
...@@ -340,7 +338,7 @@ async fn dynamic_sitemap_route_with_generate_source( ...@@ -340,7 +338,7 @@ async fn dynamic_sitemap_route_with_generate_source(
return params return params
}} }}
"#, "#,
resource_path = StringifyJs(&format!("./{stem}.{ext}")), resource_path = StringifyJs(&format!("./{}", path.file_name())),
content_type = StringifyJs(&content_type), content_type = StringifyJs(&content_type),
file_type = StringifyJs(&stem), file_type = StringifyJs(&stem),
cache_control = StringifyJs(CACHE_HEADER_REVALIDATE), cache_control = StringifyJs(CACHE_HEADER_REVALIDATE),
...@@ -360,7 +358,6 @@ async fn dynamic_sitemap_route_without_generate_source( ...@@ -360,7 +358,6 @@ async fn dynamic_sitemap_route_without_generate_source(
) -> Result<Vc<Box<dyn Source>>> { ) -> Result<Vc<Box<dyn Source>>> {
let stem = path.file_stem(); let stem = path.file_stem();
let stem = stem.unwrap_or_default(); let stem = stem.unwrap_or_default();
let ext = path.extension();
let content_type = get_content_type(path.clone()).await?; let content_type = get_content_type(path.clone()).await?;
let code = formatdoc! { let code = formatdoc! {
...@@ -391,7 +388,7 @@ async fn dynamic_sitemap_route_without_generate_source( ...@@ -391,7 +388,7 @@ async fn dynamic_sitemap_route_without_generate_source(
export * from {resource_path} export * from {resource_path}
"#, "#,
resource_path = StringifyJs(&format!("./{stem}.{ext}")), resource_path = StringifyJs(&format!("./{}", path.file_name())),
content_type = StringifyJs(&content_type), content_type = StringifyJs(&content_type),
file_type = StringifyJs(&stem), file_type = StringifyJs(&stem),
cache_control = StringifyJs(CACHE_HEADER_REVALIDATE), cache_control = StringifyJs(CACHE_HEADER_REVALIDATE),
...@@ -423,7 +420,6 @@ async fn dynamic_image_route_with_metadata_source( ...@@ -423,7 +420,6 @@ async fn dynamic_image_route_with_metadata_source(
) -> Result<Vc<Box<dyn Source>>> { ) -> Result<Vc<Box<dyn Source>>> {
let stem = path.file_stem(); let stem = path.file_stem();
let stem = stem.unwrap_or_default(); let stem = stem.unwrap_or_default();
let ext = path.extension();
let code = formatdoc! { let code = formatdoc! {
r#" r#"
...@@ -478,7 +474,7 @@ async fn dynamic_image_route_with_metadata_source( ...@@ -478,7 +474,7 @@ async fn dynamic_image_route_with_metadata_source(
return staticParams return staticParams
}} }}
"#, "#,
resource_path = StringifyJs(&format!("./{stem}.{ext}")), resource_path = StringifyJs(&format!("./{}", path.file_name())),
}; };
let file = File::from(code); let file = File::from(code);
...@@ -495,7 +491,6 @@ async fn dynamic_image_route_without_metadata_source( ...@@ -495,7 +491,6 @@ async fn dynamic_image_route_without_metadata_source(
) -> Result<Vc<Box<dyn Source>>> { ) -> Result<Vc<Box<dyn Source>>> {
let stem = path.file_stem(); let stem = path.file_stem();
let stem = stem.unwrap_or_default(); let stem = stem.unwrap_or_default();
let ext = path.extension();
let code = formatdoc! { let code = formatdoc! {
r#" r#"
...@@ -512,7 +507,7 @@ async fn dynamic_image_route_without_metadata_source( ...@@ -512,7 +507,7 @@ async fn dynamic_image_route_without_metadata_source(
export * from {resource_path} export * from {resource_path}
"#, "#,
resource_path = StringifyJs(&format!("./{stem}.{ext}")), resource_path = StringifyJs(&format!("./{}", path.file_name())),
}; };
let file = File::from(code); let file = File::from(code);
......
...@@ -171,7 +171,7 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin { ...@@ -171,7 +171,7 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin {
) -> Result<FileType> { ) -> Result<FileType> {
// node.js only supports these file extensions // node.js only supports these file extensions
// mjs is an esm module and we can't bundle that yet // mjs is an esm module and we can't bundle that yet
Ok(match raw_fs_path.extension_ref() { Ok(match raw_fs_path.extension() {
Some("cjs" | "node" | "json") => FileType::CommonJs, Some("cjs" | "node" | "json") => FileType::CommonJs,
Some("mjs") => FileType::EcmaScriptModule, Some("mjs") => FileType::EcmaScriptModule,
Some("js") => { Some("js") => {
......
...@@ -1490,7 +1490,7 @@ impl FileSystemPath { ...@@ -1490,7 +1490,7 @@ impl FileSystemPath {
/// Returns true if this path has the given extension /// Returns true if this path has the given extension
/// ///
/// slightly faster than `self.extension_ref() == Some(extension)` as we can simply match a /// slightly faster than `self.extension() == Some(extension)` as we can simply match a
/// suffix /// suffix
pub fn has_extension(&self, extension: &str) -> bool { pub fn has_extension(&self, extension: &str) -> bool {
debug_assert!(!extension.contains('/') && extension.starts_with('.')); debug_assert!(!extension.contains('/') && extension.starts_with('.'));
...@@ -1498,7 +1498,7 @@ impl FileSystemPath { ...@@ -1498,7 +1498,7 @@ impl FileSystemPath {
} }
/// Returns the extension (without a leading `.`) /// Returns the extension (without a leading `.`)
pub fn extension_ref(&self) -> Option<&str> { pub fn extension(&self) -> Option<&str> {
let (_, extension) = self.split_extension(); let (_, extension) = self.split_extension();
extension extension
} }
...@@ -1676,10 +1676,6 @@ impl FileSystemPath { ...@@ -1676,10 +1676,6 @@ impl FileSystemPath {
*self.fs *self.fs
} }
pub fn extension(&self) -> &str {
self.extension_ref().unwrap_or_default()
}
pub fn is_inside(&self, other: &FileSystemPath) -> bool { pub fn is_inside(&self, other: &FileSystemPath) -> bool {
self.is_inside_ref(other) self.is_inside_ref(other)
} }
......
...@@ -653,7 +653,7 @@ impl ChunkingContext for BrowserChunkingContext { ...@@ -653,7 +653,7 @@ impl ChunkingContext for BrowserChunkingContext {
.as_ref() .as_ref()
.context("Missing content when trying to generate the content hash for static asset")?; .context("Missing content when trying to generate the content hash for static asset")?;
let short_hash = &hash[..length as usize]; let short_hash = &hash[..length as usize];
let asset_path = match source_path.extension_ref() { let asset_path = match source_path.extension() {
Some(ext) => format!( Some(ext) => format!(
"{basename}.{short_hash}.{ext}", "{basename}.{short_hash}.{ext}",
basename = &basename[..basename.len() - ext.len() - 1], basename = &basename[..basename.len() - ext.len() - 1],
......
...@@ -125,7 +125,7 @@ fn result_to_issue<T>(source: ResolvedVc<Box<dyn Source>>, result: Result<T>) -> ...@@ -125,7 +125,7 @@ fn result_to_issue<T>(source: ResolvedVc<Box<dyn Source>>, result: Result<T>) ->
fn load_image( fn load_image(
path: ResolvedVc<Box<dyn Source>>, path: ResolvedVc<Box<dyn Source>>,
bytes: &[u8], bytes: &[u8],
extension: &str, extension: Option<&str>,
) -> Option<(ImageBuffer, Option<ImageFormat>)> { ) -> Option<(ImageBuffer, Option<ImageFormat>)> {
result_to_issue(path, load_image_internal(path, bytes, extension)) result_to_issue(path, load_image_internal(path, bytes, extension))
} }
...@@ -140,7 +140,7 @@ enum ImageBuffer { ...@@ -140,7 +140,7 @@ enum ImageBuffer {
fn load_image_internal( fn load_image_internal(
image: ResolvedVc<Box<dyn Source>>, image: ResolvedVc<Box<dyn Source>>,
bytes: &[u8], bytes: &[u8],
extension: &str, extension: Option<&str>,
) -> Result<(ImageBuffer, Option<ImageFormat>)> { ) -> Result<(ImageBuffer, Option<ImageFormat>)> {
let reader = image::ImageReader::new(Cursor::new(&bytes)); let reader = image::ImageReader::new(Cursor::new(&bytes));
let mut reader = reader let mut reader = reader
...@@ -148,7 +148,8 @@ fn load_image_internal( ...@@ -148,7 +148,8 @@ fn load_image_internal(
.context("unable to determine image format from file content")?; .context("unable to determine image format from file content")?;
let mut format = reader.format(); let mut format = reader.format();
if format.is_none() if format.is_none()
&& let Some(new_format) = extension_to_image_format(extension) && let Some(ext) = extension
&& let Some(new_format) = extension_to_image_format(ext)
{ {
format = Some(new_format); format = Some(new_format);
reader.set_format(new_format); reader.set_format(new_format);
...@@ -350,7 +351,7 @@ pub async fn get_meta_data( ...@@ -350,7 +351,7 @@ pub async fn get_meta_data(
let path = image.ident().path().await?; let path = image.ident().path().await?;
let extension = path.extension(); let extension = path.extension();
if extension == "svg" { if extension == Some("svg") {
let content = result_to_issue( let content = result_to_issue(
image, image,
std::str::from_utf8(&bytes).context("Input image is not valid utf-8"), std::str::from_utf8(&bytes).context("Input image is not valid utf-8"),
......
...@@ -494,7 +494,7 @@ impl ChunkingContext for NodeJsChunkingContext { ...@@ -494,7 +494,7 @@ impl ChunkingContext for NodeJsChunkingContext {
.as_ref() .as_ref()
.context("Missing content when trying to generate the content hash for static asset")?; .context("Missing content when trying to generate the content hash for static asset")?;
let short_hash = &hash[..length as usize]; let short_hash = &hash[..length as usize];
let asset_path = match source_path.extension_ref() { let asset_path = match source_path.extension() {
Some(ext) => format!( Some(ext) => format!(
"{basename}.{short_hash}.{ext}", "{basename}.{short_hash}.{ext}",
basename = &basename[..basename.len() - ext.len() - 1], basename = &basename[..basename.len() - ext.len() - 1],
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment