diff --git a/crates/node_binding/src/dependencies/entry_dependency.rs b/crates/node_binding/src/dependencies/entry_dependency.rs index 4ea3d8b909d9..a4145f6b0cb4 100644 --- a/crates/node_binding/src/dependencies/entry_dependency.rs +++ b/crates/node_binding/src/dependencies/entry_dependency.rs @@ -15,8 +15,7 @@ impl EntryDependency { match &self.dependency_id { Some(dependency_id) => { Err(napi::Error::from_reason(format!( - "Dependency with id = {:?} has already been resolved. Reusing EntryDependency is not allowed because Rust requires its ownership.", - dependency_id + "Dependency with id = {dependency_id:?} has already been resolved. Reusing EntryDependency is not allowed because Rust requires its ownership." ))) } None => { diff --git a/crates/node_binding/src/lib.rs b/crates/node_binding/src/lib.rs index 9e0c023844ee..adf1f1bd080c 100644 --- a/crates/node_binding/src/lib.rs +++ b/crates/node_binding/src/lib.rs @@ -415,7 +415,7 @@ fn init() { .thread_name_fn(|| { static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0); let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst); - format!("tokio-{}", id) + format!("tokio-{id}") }) .enable_all() .build() diff --git a/crates/node_binding/src/panic.rs b/crates/node_binding/src/panic.rs index 64775ff38588..eaa1a0d305f6 100644 --- a/crates/node_binding/src/panic.rs +++ b/crates/node_binding/src/panic.rs @@ -54,7 +54,7 @@ pub fn install_panic_handler() { { use rspack_core::debug_info::DEBUG_INFO; if let Ok(info) = DEBUG_INFO.lock() { - eprintln!("{}", info); + eprintln!("{info}"); } } panic_handler(panic); diff --git a/crates/node_binding/src/raw_options/raw_builtins/raw_lazy_compilation.rs b/crates/node_binding/src/raw_options/raw_builtins/raw_lazy_compilation.rs index 32ad83385f38..a924494622c0 100644 --- a/crates/node_binding/src/raw_options/raw_builtins/raw_lazy_compilation.rs +++ b/crates/node_binding/src/raw_options/raw_builtins/raw_lazy_compilation.rs @@ -70,7 +70,7 @@ impl From for LazyCompilationTest match value.0 { Either::A(regex) => Self::Regex( RspackRegex::with_flags(®ex.source, ®ex.flags).unwrap_or_else(|_| { - let msg = format!("[lazyCompilation]incorrect regex {:?}", regex); + let msg = format!("[lazyCompilation]incorrect regex {regex:?}"); panic!("{msg}"); }), ), diff --git a/crates/node_binding/src/raw_options/raw_builtins/raw_lightning_css_minimizer.rs b/crates/node_binding/src/raw_options/raw_builtins/raw_lightning_css_minimizer.rs index ff94012daa06..d77ca05d20e2 100644 --- a/crates/node_binding/src/raw_options/raw_builtins/raw_lightning_css_minimizer.rs +++ b/crates/node_binding/src/raw_options/raw_builtins/raw_lightning_css_minimizer.rs @@ -88,7 +88,7 @@ impl TryFrom for PluginOptions { .targets .map(browserslist_to_lightningcss_targets) .transpose() - .to_rspack_result_with_message(|e| format!("Failed to parse browserslist: {}", e))? + .to_rspack_result_with_message(|e| format!("Failed to parse browserslist: {e}"))? .flatten(), include: value.minimizer_options.include, exclude: value.minimizer_options.exclude, diff --git a/crates/node_binding/src/raw_options/raw_module/mod.rs b/crates/node_binding/src/raw_options/raw_module/mod.rs index 58fef2f7d1c0..864c07f671c2 100644 --- a/crates/node_binding/src/raw_options/raw_module/mod.rs +++ b/crates/node_binding/src/raw_options/raw_module/mod.rs @@ -52,10 +52,10 @@ pub enum RawRuleSetCondition { impl Debug for RawRuleSetCondition { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - RawRuleSetCondition::string(s) => write!(f, "RawRuleSetCondition::string({:?})", s), - RawRuleSetCondition::regexp(r) => write!(f, "RawRuleSetCondition::regexp({:?})", r), - RawRuleSetCondition::logical(l) => write!(f, "RawRuleSetCondition::logical({:?})", l), - RawRuleSetCondition::array(a) => write!(f, "RawRuleSetCondition::array({:?})", a), + RawRuleSetCondition::string(s) => write!(f, "RawRuleSetCondition::string({s:?})"), + RawRuleSetCondition::regexp(r) => write!(f, "RawRuleSetCondition::regexp({r:?})"), + RawRuleSetCondition::logical(l) => write!(f, "RawRuleSetCondition::logical({l:?})"), + RawRuleSetCondition::array(a) => write!(f, "RawRuleSetCondition::array({a:?})"), RawRuleSetCondition::func(_) => write!(f, "RawRuleSetCondition::func(...)"), } } diff --git a/crates/node_binding/src/resolver.rs b/crates/node_binding/src/resolver.rs index 35c21b6db72e..d2d6fbe1fd3e 100644 --- a/crates/node_binding/src/resolver.rs +++ b/crates/node_binding/src/resolver.rs @@ -50,7 +50,7 @@ impl JsResolver { Ok(Either::A(ResourceData::from(resource).into())) } Ok(rspack_core::ResolveResult::Ignored) => Ok(Either::B(false)), - Err(err) => Err(napi::Error::from_reason(format!("{:?}", err))), + Err(err) => Err(napi::Error::from_reason(format!("{err:?}"))), } }) } @@ -74,7 +74,7 @@ impl JsResolver { Either::::A(ResourceData::from(resource).into()), ), Ok(rspack_core::ResolveResult::Ignored) => Ok(Either::B(false)), - Err(err) => Err(napi::Error::from_reason(format!("{:?}", err))), + Err(err) => Err(napi::Error::from_reason(format!("{err:?}"))), } }, || {}, diff --git a/crates/node_binding/src/resolver_factory.rs b/crates/node_binding/src/resolver_factory.rs index 58a5655bab53..ded118bbf904 100644 --- a/crates/node_binding/src/resolver_factory.rs +++ b/crates/node_binding/src/resolver_factory.rs @@ -82,7 +82,7 @@ impl JsResolverFactory { Ok(JsResolver::new(resolver_factory, options)) } _ => { - Err(napi::Error::from_reason(format!("Invalid resolver type '{}' specified. Rspack only supports 'normal', 'context', and 'loader' types.", r#type))) + Err(napi::Error::from_reason(format!("Invalid resolver type '{type}' specified. Rspack only supports 'normal', 'context', and 'loader' types."))) } } } diff --git a/crates/node_binding/src/swc.rs b/crates/node_binding/src/swc.rs index 6bfece8d458a..e6095c30d64c 100644 --- a/crates/node_binding/src/swc.rs +++ b/crates/node_binding/src/swc.rs @@ -36,7 +36,7 @@ pub async fn transform(source: String, options: String) -> napi::Result napi::Result>() .join("\n"); diff --git a/crates/rspack_cacheable/src/deserialize.rs b/crates/rspack_cacheable/src/deserialize.rs index 2e57b6970ef9..aacf19f07929 100644 --- a/crates/rspack_cacheable/src/deserialize.rs +++ b/crates/rspack_cacheable/src/deserialize.rs @@ -26,7 +26,7 @@ impl std::fmt::Display for DeserializeError { match self { Self::BoxedError(error) => error.fmt(f), Self::MessageError(msg) => { - write!(f, "{}", msg) + write!(f, "{msg}") } Self::DynCheckBytesNotRegister => { write!(f, "cacheable_dyn check bytes not register") diff --git a/crates/rspack_cacheable/src/serialize.rs b/crates/rspack_cacheable/src/serialize.rs index ae4efab1114e..3b17362f373c 100644 --- a/crates/rspack_cacheable/src/serialize.rs +++ b/crates/rspack_cacheable/src/serialize.rs @@ -27,7 +27,7 @@ impl std::fmt::Display for SerializeError { match self { Self::BoxedError(error) => error.fmt(f), Self::MessageError(msg) => { - write!(f, "{}", msg) + write!(f, "{msg}") } Self::NoContext => { write!(f, "no context") diff --git a/crates/rspack_core/src/exports/utils.rs b/crates/rspack_core/src/exports/utils.rs index 1b2fb8136fe0..52cce5514dd7 100644 --- a/crates/rspack_core/src/exports/utils.rs +++ b/crates/rspack_core/src/exports/utils.rs @@ -147,7 +147,8 @@ impl DependencyConditionFn for UsedByExportsDependencyCondition { .expect("should have parent module"); let exports_info = mg.get_exports_info(module_identifier); for export_name in self.used_by_exports.iter() { - if exports_info.get_used(mg, &[export_name.clone()], runtime) != UsageState::Unused { + if exports_info.get_used(mg, std::slice::from_ref(export_name), runtime) != UsageState::Unused + { return ConnectionState::Active(true); } } diff --git a/crates/rspack_core/src/resolver/mod.rs b/crates/rspack_core/src/resolver/mod.rs index 4fd1dd65a211..fc85a44703fe 100644 --- a/crates/rspack_core/src/resolver/mod.rs +++ b/crates/rspack_core/src/resolver/mod.rs @@ -223,11 +223,9 @@ which tries to resolve these kind of requests in the current directory too.", Err(_) => normalized_path.parent(), }; - if file_name.is_some() && parent_path.is_some() { - let file_name = file_name.expect("fail to get the filename of the current resolved module"); - let parent_path = - parent_path.expect("fail to get the parent path of the current resolved module"); - + if let Some(file_name) = file_name + && let Some(parent_path) = parent_path + { // read the files in the parent directory if let Ok(files) = fs::read_dir(parent_path) { let mut requested_names = vec![file_name diff --git a/crates/rspack_error/src/graphical.rs b/crates/rspack_error/src/graphical.rs index 344a7acead66..b5bbc32f8959 100644 --- a/crates/rspack_error/src/graphical.rs +++ b/crates/rspack_error/src/graphical.rs @@ -183,7 +183,7 @@ impl GraphicalReportHandler { if self.links == LinkStyle::Link && diagnostic.url().is_some() { let url = diagnostic.url().unwrap(); // safe let code = if let Some(code) = diagnostic.code() { - format!("{} ", code) + format!("{code} ") } else { "".to_string() }; @@ -193,8 +193,8 @@ impl GraphicalReportHandler { code.style(severity_style), "(link)".style(self.theme.styles.link) ); - write!(header, "{}", link)?; - writeln!(f, "{}", header)?; + write!(header, "{link}")?; + writeln!(f, "{header}")?; writeln!(f)?; } else if let Some(code) = diagnostic.code() { write!(header, "{}", code.style(severity_style),)?; @@ -202,7 +202,7 @@ impl GraphicalReportHandler { let url = diagnostic.url().unwrap(); // safe write!(header, " ({})", url.style(self.theme.styles.link))?; } - writeln!(f, "{}", header)?; + writeln!(f, "{header}")?; writeln!(f)?; } Ok(()) @@ -443,11 +443,11 @@ impl GraphicalReportHandler { if let Some(source_name) = contents.name() { let source_name = source_name.style(self.theme.styles.link); - writeln!(f, "[{}:{}:{}]", source_name, source_line, source_col)?; + writeln!(f, "[{source_name}:{source_line}:{source_col}]")?; } else if lines.len() <= 1 { writeln!(f, "{}", self.theme.characters.hbar.to_string().repeat(3))?; } else { - writeln!(f, "[{}:{}]", source_line, source_col)?; + writeln!(f, "[{source_line}:{source_col}]")?; } // Now it's time for the fun part--actually rendering everything! @@ -722,7 +722,7 @@ impl GraphicalReportHandler { (hl, vbar_offset) }) .collect(); - writeln!(f, "{}", underlines)?; + writeln!(f, "{underlines}")?; for hl in single_liners.iter().rev() { if let Some(label) = hl.label() { diff --git a/crates/rspack_ids/src/id_helpers.rs b/crates/rspack_ids/src/id_helpers.rs index eb1564dd0af9..9f761820e5f2 100644 --- a/crates/rspack_ids/src/id_helpers.rs +++ b/crates/rspack_ids/src/id_helpers.rs @@ -208,7 +208,7 @@ pub fn get_short_chunk_name( .map(|id| { module_graph .module_by_identifier(id) - .unwrap_or_else(|| panic!("Module not found {}", id)) + .unwrap_or_else(|| panic!("Module not found {id}")) }) .collect::>(); let short_module_names = modules diff --git a/crates/rspack_loader_lightningcss/src/config.rs b/crates/rspack_loader_lightningcss/src/config.rs index aaec61460736..06ff58f53aba 100644 --- a/crates/rspack_loader_lightningcss/src/config.rs +++ b/crates/rspack_loader_lightningcss/src/config.rs @@ -73,7 +73,7 @@ impl TryFrom for Config { .targets .map(browserslist_to_lightningcss_targets) .transpose() - .to_rspack_result_with_message(|e| format!("Failed to parse browserslist: {}", e))? + .to_rspack_result_with_message(|e| format!("Failed to parse browserslist: {e}"))? .flatten(), include: value.include, exclude: value.exclude, diff --git a/crates/rspack_macros/src/cacheable_dyn.rs b/crates/rspack_macros/src/cacheable_dyn.rs index 64487939ede4..5fd049edc86e 100644 --- a/crates/rspack_macros/src/cacheable_dyn.rs +++ b/crates/rspack_macros/src/cacheable_dyn.rs @@ -168,7 +168,7 @@ pub fn impl_impl(mut input: ItemImpl) -> TokenStream { panic!("cacheable_dyn unsupported this target") } }; - let archived_target_ident = Ident::new(&format!("Archived{}", target_ident_str), input.span()); + let archived_target_ident = Ident::new(&format!("Archived{target_ident_str}"), input.span()); #[allow(clippy::disallowed_methods)] let dyn_id_ident = Ident::new( &format!( diff --git a/crates/rspack_macros/src/plugin.rs b/crates/rspack_macros/src/plugin.rs index 5b1e79c77fef..558ace6fe31d 100644 --- a/crates/rspack_macros/src/plugin.rs +++ b/crates/rspack_macros/src/plugin.rs @@ -91,7 +91,7 @@ pub fn expand_struct(mut input: syn::ItemStruct) -> proc_macro::TokenStream { } fn plugin_inner_ident(ident: &syn::Ident) -> syn::Ident { - let inner_name = format!("{}Inner", ident); + let inner_name = format!("{ident}Inner"); syn::Ident::new(&inner_name, ident.span()) } diff --git a/crates/rspack_napi_macros/src/tagged_union.rs b/crates/rspack_napi_macros/src/tagged_union.rs index c0c66031243e..fbbd83f6f4af 100644 --- a/crates/rspack_napi_macros/src/tagged_union.rs +++ b/crates/rspack_napi_macros/src/tagged_union.rs @@ -56,7 +56,7 @@ pub fn expand(tokens: TokenStream) -> TokenStream { }) .collect::>(); - let union_type_name = Ident::new(&format!("{}Type", original_name), Span::call_site()); + let union_type_name = Ident::new(&format!("{original_name}Type"), Span::call_site()); let as_str_impl = { let arms = field_idents @@ -140,6 +140,6 @@ pub fn expand(tokens: TokenStream) -> TokenStream { } fn get_intermediate_ident(name: &str) -> Ident { - let new_name = format!("__rspack_napi__{}", name); + let new_name = format!("__rspack_napi__{name}"); Ident::new(&new_name, Span::call_site()) } diff --git a/crates/rspack_plugin_banner/src/lib.rs b/crates/rspack_plugin_banner/src/lib.rs index ea5d719f55f1..97ff7011ec37 100644 --- a/crates/rspack_plugin_banner/src/lib.rs +++ b/crates/rspack_plugin_banner/src/lib.rs @@ -95,7 +95,7 @@ fn wrap_comment(str: &str) -> String { let result = TRIALING_WHITESPACE.replace_all(&result, "\n"); let result = result.trim_end(); - format!("/*!\n * {}\n */", result) + format!("/*!\n * {result}\n */") } #[plugin] diff --git a/crates/rspack_plugin_copy/src/lib.rs b/crates/rspack_plugin_copy/src/lib.rs index 801293e521ac..8ec6d529f7cf 100644 --- a/crates/rspack_plugin_copy/src/lib.rs +++ b/crates/rspack_plugin_copy/src/lib.rs @@ -266,7 +266,7 @@ impl CopyRspackPlugin { // TODO cache - logger.debug(format!("reading '{}'...", absolute_filename)); + logger.debug(format!("reading '{absolute_filename}'...")); // TODO inputFileSystem #[cfg(not(target_family = "wasm"))] @@ -276,7 +276,7 @@ impl CopyRspackPlugin { let source_vec = match data { Ok(data) => { - logger.debug(format!("read '{}'...", absolute_filename)); + logger.debug(format!("read '{absolute_filename}'...")); data } @@ -293,10 +293,7 @@ impl CopyRspackPlugin { let mut source = RawSource::from(source_vec.clone()); if let Some(transformer) = &pattern.transform_fn { - logger.debug(format!( - "transforming content for '{}'...", - absolute_filename - )); + logger.debug(format!("transforming content for '{absolute_filename}'...")); // TODO: support cache in the future. handle_transform( transformer, @@ -310,8 +307,7 @@ impl CopyRspackPlugin { let filename = if matches!(&to_type, ToType::Template) { logger.log(format!( - "interpolating template '{}' for '${}'...`", - filename, source_filename + "interpolating template '{filename}' for '${source_filename}'...`" )); let content_hash = Self::get_content_hash( @@ -332,8 +328,7 @@ impl CopyRspackPlugin { .await?; logger.log(format!( - "interpolated template '{template_str}' for '{}'", - filename + "interpolated template '{template_str}' for '{filename}'" )); template_str @@ -376,8 +371,7 @@ impl CopyRspackPlugin { }; logger.log(format!( - "starting to process a pattern from '{}' using '{:?}' context", - normalized_orig_from, pattern_context + "starting to process a pattern from '{normalized_orig_from}' using '{pattern_context:?}' context" )); let mut context = @@ -389,21 +383,21 @@ impl CopyRspackPlugin { context.join(&normalized_orig_from) }; - logger.debug(format!("getting stats for '{}'...", abs_from)); + logger.debug(format!("getting stats for '{abs_from}'...")); let from_type = if let Ok(meta) = fs::metadata(&abs_from) { if meta.is_dir() { - logger.debug(format!("determined '{}' is a directory", abs_from)); + logger.debug(format!("determined '{abs_from}' is a directory")); FromType::Dir } else if meta.is_file() { - logger.debug(format!("determined '{}' is a file", abs_from)); + logger.debug(format!("determined '{abs_from}' is a file")); FromType::File } else { - logger.debug(format!("determined '{}' is a unknown", abs_from)); + logger.debug(format!("determined '{abs_from}' is a unknown")); FromType::Glob } } else { - logger.debug(format!("determined '{}' is a glob", abs_from)); + logger.debug(format!("determined '{abs_from}' is a glob")); FromType::Glob }; @@ -417,7 +411,7 @@ impl CopyRspackPlugin { let mut need_add_context_to_dependency = false; let glob_query = match from_type { FromType::Dir => { - logger.debug(format!("added '{}' as a context dependency", abs_from)); + logger.debug(format!("added '{abs_from}' as a context dependency")); context_dependencies.insert(abs_from.clone().into_std_path_buf()); context = abs_from.as_path().into(); @@ -430,7 +424,7 @@ impl CopyRspackPlugin { escaped.as_str().to_string() } FromType::File => { - logger.debug(format!("added '{}' as a file dependency", abs_from)); + logger.debug(format!("added '{abs_from}' as a file dependency")); file_dependencies.insert(abs_from.clone().into_std_path_buf()); context = abs_from.parent().unwrap_or(Utf8Path::new("")).into(); @@ -681,28 +675,25 @@ async fn process_assets(&self, compilation: &mut Compilation) -> Result<()> { // Make sure the output directory exists if let Some(parent) = dest_path.parent() { fs::create_dir_all(parent).unwrap_or_else(|e| { - logger.warn(format!("Failed to create directory {:?}: {}", parent, e)); + logger.warn(format!("Failed to create directory {parent:?}: {e}")); }); } // Make sure the file exists before trying to set permissions if !dest_path.exists() { logger.warn(format!( - "Destination file {:?} does not exist, cannot copy permissions", - dest_path + "Destination file {dest_path:?} does not exist, cannot copy permissions" )); continue; } if let Err(e) = fs::set_permissions(dest_path, permissions) { logger.warn(format!( - "Failed to copy permissions from {:?} to {:?}: {}", - source_path, dest_path, e + "Failed to copy permissions from {source_path:?} to {dest_path:?}: {e}" )); } else { logger.log(format!( - "Successfully copied permissions from {:?} to {:?}", - source_path, dest_path + "Successfully copied permissions from {source_path:?} to {dest_path:?}" )); } } diff --git a/crates/rspack_plugin_css/src/parser_and_generator/mod.rs b/crates/rspack_plugin_css/src/parser_and_generator/mod.rs index f876c95f229f..e4a099607afe 100644 --- a/crates/rspack_plugin_css/src/parser_and_generator/mod.rs +++ b/crates/rspack_plugin_css/src/parser_and_generator/mod.rs @@ -631,9 +631,11 @@ impl ParserAndGenerator for CssParserAndGenerator { ns_obj, left, right, - with_hmr - .then_some("module.hot.accept();\n") - .unwrap_or_default() + if with_hmr { + "module.hot.accept();\n" + } else { + Default::default() + } ) } }; diff --git a/crates/rspack_plugin_css/src/plugin/impl_plugin_for_css_plugin.rs b/crates/rspack_plugin_css/src/plugin/impl_plugin_for_css_plugin.rs index 1d84e331bb05..1e60ae7c6666 100644 --- a/crates/rspack_plugin_css/src/plugin/impl_plugin_for_css_plugin.rs +++ b/crates/rspack_plugin_css/src/plugin/impl_plugin_for_css_plugin.rs @@ -187,12 +187,12 @@ impl CssPlugin { // TODO: use PrefixSource to create indent if let Some(media) = data.get::() { num_close_bracket += 1; - container_source.add(RawSource::from(format!("@media {}{{\n", media))); + container_source.add(RawSource::from(format!("@media {media}{{\n"))); } if let Some(supports) = data.get::() { num_close_bracket += 1; - container_source.add(RawSource::from(format!("@supports ({}) {{\n", supports))); + container_source.add(RawSource::from(format!("@supports ({supports}) {{\n"))); } if let Some(layer) = data.get::() { @@ -200,7 +200,7 @@ impl CssPlugin { container_source.add(RawSource::from(format!( "@layer{} {{\n", if let CssLayer::Named(layer) = &layer { - Cow::Owned(format!(" {}", layer)) + Cow::Owned(format!(" {layer}")) } else { Cow::Borrowed("") } diff --git a/crates/rspack_plugin_css/src/runtime/mod.rs b/crates/rspack_plugin_css/src/runtime/mod.rs index 997b9fa9d2db..c29cd6b6891f 100644 --- a/crates/rspack_plugin_css/src/runtime/mod.rs +++ b/crates/rspack_plugin_css/src/runtime/mod.rs @@ -127,7 +127,11 @@ installedChunks[chunkId] = 0; RuntimeGlobals::MODULE_FACTORIES )) .unwrap_or_default(), - with_hmr.then_some("return moduleIds").unwrap_or_default(), + if with_hmr { + "return moduleIds" + } else { + Default::default() + }, ), ); let load_initial_chunk_data = if initial_chunk_ids.len() > 2 { @@ -202,7 +206,7 @@ installedChunks[chunkId] = 0; let cross_origin_content = if let CrossOriginLoading::Enable(cross_origin) = &compilation.options.output.cross_origin_loading { - format!("link.crossOrigin = '{}';", cross_origin) + format!("link.crossOrigin = '{cross_origin}';") } else { "".to_string() }; diff --git a/crates/rspack_plugin_css/src/utils.rs b/crates/rspack_plugin_css/src/utils.rs index b2214acc15e3..d53b3f3795d4 100644 --- a/crates/rspack_plugin_css/src/utils.rs +++ b/crates/rspack_plugin_css/src/utils.rs @@ -235,7 +235,7 @@ pub fn stringified_exports<'a>( let decl_name = "exports"; Ok(( decl_name, - format!("var {} = {{\n{}}};", decl_name, stringified_exports), + format!("var {decl_name} = {{\n{stringified_exports}}};"), )) } @@ -336,7 +336,7 @@ pub fn unescape(s: &str) -> Cow { if m.len() > 2 { if let Ok(r_u32) = u32::from_str_radix(m[1..].trim(), 16) { if let Some(ch) = char::from_u32(r_u32) { - return Some(format!("{}", ch)); + return Some(format!("{ch}")); } } None diff --git a/crates/rspack_plugin_devtool/src/eval_dev_tool_module_plugin.rs b/crates/rspack_plugin_devtool/src/eval_dev_tool_module_plugin.rs index efa3ff25ba17..d87c9b5d0002 100644 --- a/crates/rspack_plugin_devtool/src/eval_dev_tool_module_plugin.rs +++ b/crates/rspack_plugin_devtool/src/eval_dev_tool_module_plugin.rs @@ -281,7 +281,7 @@ fn encode_uri(string: &str) -> Cow { if let Cow::Owned(mut inner) = r { let mut b = [0u8; 4]; for &octet in c.encode_utf8(&mut b).as_bytes() { - write!(&mut inner, "%{:02X}", octet).unwrap(); + write!(&mut inner, "%{octet:02X}").expect("write failed"); } r = Cow::Owned(inner); } diff --git a/crates/rspack_plugin_devtool/src/module_filename_helpers.rs b/crates/rspack_plugin_devtool/src/module_filename_helpers.rs index c8f06edbec58..63d130924010 100644 --- a/crates/rspack_plugin_devtool/src/module_filename_helpers.rs +++ b/crates/rspack_plugin_devtool/src/module_filename_helpers.rs @@ -66,10 +66,7 @@ impl ModuleFilenameHelpers { let module = module_graph .module_by_identifier(module_identifier) .unwrap_or_else(|| { - panic!( - "failed to find a module for the given identifier '{}'", - module_identifier - ) + panic!("failed to find a module for the given identifier '{module_identifier}'") }); let short_identifier = module.readable_identifier(context).to_string(); diff --git a/crates/rspack_plugin_ensure_chunk_conditions/src/lib.rs b/crates/rspack_plugin_ensure_chunk_conditions/src/lib.rs index 05e7398711db..b90283facffd 100644 --- a/crates/rspack_plugin_ensure_chunk_conditions/src/lib.rs +++ b/crates/rspack_plugin_ensure_chunk_conditions/src/lib.rs @@ -76,7 +76,7 @@ async fn optimize_chunks(&self, compilation: &mut Compilation) -> Result>) -> Vec { meta - .iter() - .map(|(_, value)| HtmlPluginTag { + .values() + .map(|value| HtmlPluginTag { tag_name: "meta".to_string(), attributes: value .iter() @@ -265,7 +265,7 @@ impl fmt::Display for HtmlPluginTag { String::new() } ); - write!(f, "{}", res) + write!(f, "{res}") } } diff --git a/crates/rspack_plugin_javascript/src/dependency/amd/amd_define_dependency.rs b/crates/rspack_plugin_javascript/src/dependency/amd/amd_define_dependency.rs index 2f841a12634e..6122fc16b8d2 100644 --- a/crates/rspack_plugin_javascript/src/dependency/amd/amd_define_dependency.rs +++ b/crates/rspack_plugin_javascript/src/dependency/amd/amd_define_dependency.rs @@ -68,22 +68,22 @@ impl Branch { a_o if a_o == (Branch::A | Branch::O) => "".to_string(), a_o_f if a_o_f == (Branch::A | Branch::O | Branch::F) => "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;".to_string(), l_f if l_f == (Branch::L | Branch::F) => { - format!("var {}, {}module;", name, name) + format!("var {name}, {name}module;") }, l_o if l_o == (Branch::L | Branch::O) => { - format!("var {};", name) + format!("var {name};") }, l_o_f if l_o_f == (Branch::L | Branch::O | Branch::F) => { - format!("var {}, {}factory, {}module;", name, name, name) + format!("var {name}, {name}factory, {name}module;") }, l_a_f if l_a_f == (Branch::L | Branch::A | Branch::F) => { - format!("var __WEBPACK_AMD_DEFINE_ARRAY__, {}, {}exports;", name, name) + format!("var __WEBPACK_AMD_DEFINE_ARRAY__, {name}, {name}exports;") }, l_a_o if l_a_o == (Branch::L | Branch::A | Branch::O)=> { - format!("var {};", name) + format!("var {name};") }, l_a_o_f if l_a_o_f == (Branch::L | Branch::A | Branch::O | Branch::F) => { - format!("var {}array, {}factory, {}exports, {};", name, name, name, name) + format!("var {name}array, {name}factory, {name}exports, {name};") }, _ => "".to_string(), } @@ -138,7 +138,7 @@ impl Branch { require = RuntimeGlobals::REQUIRE.name(), ) } - l_o if l_o == (Branch::L | Branch::O) => format!("!({} = #)", local_module_var), + l_o if l_o == (Branch::L | Branch::O) => format!("!({local_module_var} = #)"), l_o_f if l_o_f == (Branch::L | Branch::O | Branch::F) => { format!( "!({var_name}factory = (#), (typeof {var_name}factory === 'function' ? (({var_name}module = {{ id: {module_id}, exports: {{}}, loaded: false }}), ({var_name} = {var_name}factory.call({var_name}module.exports, {require}, {var_name}module.exports, {var_name}module)), ({var_name}module.loaded = true), {var_name} === undefined && ({var_name} = {var_name}module.exports)) : {var_name} = {var_name}factory))", @@ -147,15 +147,14 @@ impl Branch { require = RuntimeGlobals::REQUIRE.name(), ) } - l_a_f if l_a_f == (Branch::L | Branch::A | Branch::F) => format!("!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, {} = (#).apply({}exports = {{}}, __WEBPACK_AMD_DEFINE_ARRAY__), {} === undefined && ({} = {}exports))", local_module_var, local_module_var, local_module_var, local_module_var, local_module_var), - l_a_o if l_a_o == (Branch::L | Branch::A | Branch::O) => format!("!(#, {} = #)", local_module_var), + l_a_f if l_a_f == (Branch::L | Branch::A | Branch::F) => format!("!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, {local_module_var} = (#).apply({local_module_var}exports = {{}}, __WEBPACK_AMD_DEFINE_ARRAY__), {local_module_var} === undefined && ({local_module_var} = {local_module_var}exports))"), + l_a_o if l_a_o == (Branch::L | Branch::A | Branch::O) => format!("!(#, {local_module_var} = #)"), l_a_o_f if l_a_o_f == (Branch::L | Branch::A | Branch::O | Branch::F) => format!( - "!({var_name}array = #, {var_name}factory = (#), - (typeof {var_name}factory === 'function' ? - (({var_name} = {var_name}factory.apply({var_name}exports = {{}}, {var_name}array)), {var_name} === undefined && ({var_name} = {var_name}exports)) : - ({var_name} = {var_name}factory) + "!({local_module_var}array = #, {local_module_var}factory = (#), + (typeof {local_module_var}factory === 'function' ? + (({local_module_var} = {local_module_var}factory.apply({local_module_var}exports = {{}}, {local_module_var}array)), {local_module_var} === undefined && ({local_module_var} = {local_module_var}exports)) : + ({local_module_var} = {local_module_var}factory) ))", - var_name = local_module_var, ), _ => "".to_string(), } diff --git a/crates/rspack_plugin_javascript/src/dependency/commonjs/common_js_export_require_dependency.rs b/crates/rspack_plugin_javascript/src/dependency/commonjs/common_js_export_require_dependency.rs index 854fa327fdf0..e1adcbb30e25 100644 --- a/crates/rspack_plugin_javascript/src/dependency/commonjs/common_js_export_require_dependency.rs +++ b/crates/rspack_plugin_javascript/src/dependency/commonjs/common_js_export_require_dependency.rs @@ -431,7 +431,7 @@ impl DependencyTemplate for CommonJsExportRequireDependencyTemplate { exports_argument.to_string() } else if dep.base.is_module_exports() { runtime_requirements.insert(RuntimeGlobals::MODULE); - format!("{}.exports", module_argument) + format!("{module_argument}.exports") } else if dep.base.is_this() { runtime_requirements.insert(RuntimeGlobals::THIS_AS_EXPORTS); "this".to_string() @@ -477,7 +477,7 @@ impl DependencyTemplate for CommonJsExportRequireDependencyTemplate { 0 ) ), - None => format!("/* unused reexport */ {}", require_expr), + None => format!("/* unused reexport */ {require_expr}"), }; source.replace(dep.range.start, dep.range.end, expr.as_str(), None) } else if dep.base.is_define_property() { diff --git a/crates/rspack_plugin_javascript/src/dependency/commonjs/common_js_exports_dependency.rs b/crates/rspack_plugin_javascript/src/dependency/commonjs/common_js_exports_dependency.rs index cc3738740626..b130e2ef69c8 100644 --- a/crates/rspack_plugin_javascript/src/dependency/commonjs/common_js_exports_dependency.rs +++ b/crates/rspack_plugin_javascript/src/dependency/commonjs/common_js_exports_dependency.rs @@ -174,7 +174,7 @@ impl DependencyTemplate for CommonJsExportsDependencyTemplate { exports_argument.to_string() } else if dep.base.is_module_exports() { runtime_requirements.insert(RuntimeGlobals::MODULE); - format!("{}.exports", module_argument) + format!("{module_argument}.exports") } else if dep.base.is_this() { runtime_requirements.insert(RuntimeGlobals::THIS_AS_EXPORTS); "this".to_string() diff --git a/crates/rspack_plugin_javascript/src/dependency/commonjs/common_js_self_reference_dependency.rs b/crates/rspack_plugin_javascript/src/dependency/commonjs/common_js_self_reference_dependency.rs index 7cd537d6631a..f8a296d9c0ca 100644 --- a/crates/rspack_plugin_javascript/src/dependency/commonjs/common_js_self_reference_dependency.rs +++ b/crates/rspack_plugin_javascript/src/dependency/commonjs/common_js_self_reference_dependency.rs @@ -157,7 +157,7 @@ impl DependencyTemplate for CommonJsSelfReferenceDependencyTemplate { exports_argument.to_string() } else if dep.base.is_module_exports() { runtime_requirements.insert(RuntimeGlobals::MODULE); - format!("{}.exports", module_argument) + format!("{module_argument}.exports") } else if dep.base.is_this() { runtime_requirements.insert(RuntimeGlobals::THIS_AS_EXPORTS); "this".to_string() diff --git a/crates/rspack_plugin_javascript/src/dependency/commonjs/require_ensure_dependency.rs b/crates/rspack_plugin_javascript/src/dependency/commonjs/require_ensure_dependency.rs index fc1c4d754247..a91bf444657f 100644 --- a/crates/rspack_plugin_javascript/src/dependency/commonjs/require_ensure_dependency.rs +++ b/crates/rspack_plugin_javascript/src/dependency/commonjs/require_ensure_dependency.rs @@ -96,7 +96,7 @@ impl DependencyTemplate for RequireEnsureDependencyTemplate { source.replace( dep.range.start, dep.content_range.start, - &format!("{}.then((", promise), + &format!("{promise}.then(("), None, ); code_generatable_context diff --git a/crates/rspack_plugin_javascript/src/dependency/context/mod.rs b/crates/rspack_plugin_javascript/src/dependency/context/mod.rs index f9323ae2efdd..2c584203d72c 100644 --- a/crates/rspack_plugin_javascript/src/dependency/context/mod.rs +++ b/crates/rspack_plugin_javascript/src/dependency/context/mod.rs @@ -61,13 +61,13 @@ fn create_resource_identifier_for_context_dependency( } group_options += " {"; if let Some(o) = group.prefetch_order { - group_options.push_str(&format!("prefetchOrder: {},", o)); + group_options.push_str(&format!("prefetchOrder: {o},")); } if let Some(o) = group.preload_order { - group_options.push_str(&format!("preloadOrder: {},", o)); + group_options.push_str(&format!("preloadOrder: {o},")); } if let Some(o) = group.fetch_priority { - group_options.push_str(&format!("fetchPriority: {},", o)); + group_options.push_str(&format!("fetchPriority: {o},")); } group_options += "}"; } diff --git a/crates/rspack_plugin_javascript/src/dependency/esm/esm_export_imported_specifier_dependency.rs b/crates/rspack_plugin_javascript/src/dependency/esm/esm_export_imported_specifier_dependency.rs index 7b47aade56bd..e6684cb79094 100644 --- a/crates/rspack_plugin_javascript/src/dependency/esm/esm_export_imported_specifier_dependency.rs +++ b/crates/rspack_plugin_javascript/src/dependency/esm/esm_export_imported_specifier_dependency.rs @@ -142,7 +142,7 @@ impl ESMExportImportedSpecifierDependency { let exports_info = module_graph.get_exports_info(parent_module); let is_name_unused = if let Some(ref name) = name { - exports_info.get_used(module_graph, &[name.clone()], runtime) == UsageState::Unused + exports_info.get_used(module_graph, std::slice::from_ref(name), runtime) == UsageState::Unused } else { !exports_info.is_used(module_graph, runtime) }; @@ -611,9 +611,11 @@ impl ESMExportImportedSpecifierDependency { continue; } - let used_name = - mg.get_exports_info(&module_identifier) - .get_used_name(mg, None, &[name.clone()]); + let used_name = mg.get_exports_info(&module_identifier).get_used_name( + mg, + None, + std::slice::from_ref(&name), + ); let key = render_used_name(used_name.as_ref()); if checked { @@ -735,10 +737,7 @@ impl ESMExportImportedSpecifierDependency { runtime_requirements.insert(RuntimeGlobals::EXPORTS); runtime_requirements.insert(RuntimeGlobals::DEFINE_PROPERTY_GETTERS); let mut export_map = vec![]; - export_map.push(( - key.into(), - format!("/* {} */ {}", comment, return_value).into(), - )); + export_map.push((key.into(), format!("/* {comment} */ {return_value}").into())); let module_graph = compilation.get_module_graph(); let module = module_graph .module_by_identifier(&module.identifier()) @@ -797,7 +796,7 @@ impl ESMExportImportedSpecifierDependency { fn get_return_value(name: String, value_key: ValueKey) -> String { match value_key { ValueKey::False => "/* unused export */ undefined".to_string(), - ValueKey::Null => format!("{}_default.a", name), + ValueKey::Null => format!("{name}_default.a"), ValueKey::Name => name, ValueKey::Vec(value_key) => format!("{}{}", name, property_access(value_key, 0)), } @@ -1220,7 +1219,7 @@ impl Dependency for ESMExportImportedSpecifierDependency { self .name .as_ref() - .map(|name| format!("(reexported as '{}')", name)) + .map(|name| format!("(reexported as '{name}')")) .unwrap_or_default(), should_error, ) { diff --git a/crates/rspack_plugin_javascript/src/dependency/esm/esm_export_specifier_dependency.rs b/crates/rspack_plugin_javascript/src/dependency/esm/esm_export_specifier_dependency.rs index 5508b735513d..b3f523469931 100644 --- a/crates/rspack_plugin_javascript/src/dependency/esm/esm_export_specifier_dependency.rs +++ b/crates/rspack_plugin_javascript/src/dependency/esm/esm_export_specifier_dependency.rs @@ -141,7 +141,8 @@ impl DependencyTemplate for ESMExportSpecifierDependencyTemplate { let used_name = { let exports_info = module_graph.get_exports_info(&module.identifier()); - let used_name = exports_info.get_used_name(&module_graph, *runtime, &[dep.name.clone()]); + let used_name = + exports_info.get_used_name(&module_graph, *runtime, std::slice::from_ref(&dep.name)); used_name.map(|item| match item { UsedName::Normal(vec) => { // only have one value for export specifier dependency diff --git a/crates/rspack_plugin_javascript/src/dependency/esm/esm_import_dependency.rs b/crates/rspack_plugin_javascript/src/dependency/esm/esm_import_dependency.rs index bcc500096ef6..0095936ab37b 100644 --- a/crates/rspack_plugin_javascript/src/dependency/esm/esm_import_dependency.rs +++ b/crates/rspack_plugin_javascript/src/dependency/esm/esm_import_dependency.rs @@ -159,7 +159,7 @@ pub fn esm_import_dependency_apply( let module_key = ref_module .map(|i| i.as_str()) .unwrap_or(module_dependency.request()); - let key = format!("ESM import {}", module_key); + let key = format!("ESM import {module_key}"); // The import emitted map is consumed by ESMAcceptDependency which enabled by HotModuleReplacementPlugin if let Some(import_emitted_map) = import_emitted_runtime::get_map() { @@ -206,7 +206,7 @@ pub fn esm_import_dependency_apply( content.1, InitFragmentStage::StageAsyncESMImports, source_order, - InitFragmentKey::ESMImport(format!("{} compat", key)), + InitFragmentKey::ESMImport(format!("{key} compat")), None, runtime_condition, ))); diff --git a/crates/rspack_plugin_javascript/src/dependency/esm/esm_import_specifier_dependency.rs b/crates/rspack_plugin_javascript/src/dependency/esm/esm_import_specifier_dependency.rs index 5407e10685f6..d2c175affc84 100644 --- a/crates/rspack_plugin_javascript/src/dependency/esm/esm_import_specifier_dependency.rs +++ b/crates/rspack_plugin_javascript/src/dependency/esm/esm_import_specifier_dependency.rs @@ -449,7 +449,7 @@ impl DependencyTemplate for ESMImportSpecifierDependencyTemplate { } let comment = Template::to_normal_comment(prop.id.as_str()); - let key = format!("{}{}", comment, new_name); + let key = format!("{comment}{new_name}"); let content = if prop.shorthand { format!("{key}: {}", prop.id) } else { diff --git a/crates/rspack_plugin_javascript/src/dependency/hmr/esm_accept_dependency.rs b/crates/rspack_plugin_javascript/src/dependency/hmr/esm_accept_dependency.rs index 04e0a9697d88..3b4b50db91e5 100644 --- a/crates/rspack_plugin_javascript/src/dependency/hmr/esm_accept_dependency.rs +++ b/crates/rspack_plugin_javascript/src/dependency/hmr/esm_accept_dependency.rs @@ -119,7 +119,7 @@ impl DependencyTemplate for ESMAcceptDependencyTemplate { content.push_str(stmts.0.as_str()); content.push_str(stmts.1.as_str()); } else { - content.push_str(format!("if ({}) {{\n", condition).as_str()); + content.push_str(format!("if ({condition}) {{\n").as_str()); content.push_str(stmts.0.as_str()); content.push_str(stmts.1.as_str()); content.push_str("\n}\n"); diff --git a/crates/rspack_plugin_javascript/src/dependency/pure_expression_dependency.rs b/crates/rspack_plugin_javascript/src/dependency/pure_expression_dependency.rs index 40522553e89f..775122c76718 100644 --- a/crates/rspack_plugin_javascript/src/dependency/pure_expression_dependency.rs +++ b/crates/rspack_plugin_javascript/src/dependency/pure_expression_dependency.rs @@ -42,7 +42,8 @@ impl PureExpressionDependency { let exports_info = module_graph.get_exports_info(&self.module_identifier); filter_runtime(runtime, |cur_runtime| { set.iter().any(|id| { - exports_info.get_used(&module_graph, &[id.clone()], cur_runtime) != UsageState::Unused + exports_info.get_used(&module_graph, std::slice::from_ref(id), cur_runtime) + != UsageState::Unused }) }) } diff --git a/crates/rspack_plugin_javascript/src/plugin/mod.rs b/crates/rspack_plugin_javascript/src/plugin/mod.rs index 9be578fd0425..590b34890d21 100644 --- a/crates/rspack_plugin_javascript/src/plugin/mod.rs +++ b/crates/rspack_plugin_javascript/src/plugin/mod.rs @@ -1122,7 +1122,7 @@ impl JsPlugin { let high = span.real_hi(); if identifier.shorthand { - replace_source.insert(high, &format!(": {}", new_name), None); + replace_source.insert(high, &format!(": {new_name}"), None); continue; } diff --git a/crates/rspack_plugin_javascript/src/plugin/module_concatenation_plugin.rs b/crates/rspack_plugin_javascript/src/plugin/module_concatenation_plugin.rs index 4df077fd5725..0c804d960009 100644 --- a/crates/rspack_plugin_javascript/src/plugin/module_concatenation_plugin.rs +++ b/crates/rspack_plugin_javascript/src/plugin/module_concatenation_plugin.rs @@ -24,7 +24,7 @@ use rspack_util::itoa; use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet}; fn format_bailout_reason(msg: &str) -> String { - format!("ModuleConcatenation bailout: {}", msg) + format!("ModuleConcatenation bailout: {msg}") } #[derive(Clone, Debug)] @@ -102,9 +102,7 @@ pub struct ModuleConcatenationPlugin { impl ModuleConcatenationPlugin { fn format_bailout_warning(&self, module: ModuleIdentifier, warning: &Warning) -> String { match warning { - Warning::Problem(id) => { - format_bailout_reason(&format!("Cannot concat with {}: {}", module, id)) - } + Warning::Problem(id) => format_bailout_reason(&format!("Cannot concat with {module}: {id}")), Warning::Id(id) => { let reason = self.get_inner_bailout_reason(id); let reason_with_prefix = match reason { @@ -112,14 +110,10 @@ impl ModuleConcatenationPlugin { None => "".to_string(), }; if id == &module { - format_bailout_reason(&format!( - "Cannot concat with {}{}", - module, reason_with_prefix - )) + format_bailout_reason(&format!("Cannot concat with {module}{reason_with_prefix}")) } else { format_bailout_reason(&format!( - "Cannot concat with {} because of {}{}", - module, id, reason_with_prefix + "Cannot concat with {module} because of {id}{reason_with_prefix}" )) } } @@ -286,8 +280,7 @@ impl ModuleConcatenationPlugin { // let mut explanations: Vec<_> = importing_explanations.into_iter().collect(); // explanations.sort(); format!( - "Module {} is referenced", - module_readable_identifier, + "Module {module_readable_identifier} is referenced", // if !explanations.is_empty() { // format!("by: {}", explanations.join(", ")) // } else { @@ -594,7 +587,7 @@ impl ModuleConcatenationPlugin { .map(|id| { let module = module_graph .module_by_identifier(id) - .unwrap_or_else(|| panic!("should have module {}", id)); + .unwrap_or_else(|| panic!("should have module {id}")); let inner_module = ConcatenatedInnerModule { id: *id, size: module.size( diff --git a/crates/rspack_plugin_javascript/src/webpack_comment.rs b/crates/rspack_plugin_javascript/src/webpack_comment.rs index f2ca03198f54..d5c09c3a0803 100644 --- a/crates/rspack_plugin_javascript/src/webpack_comment.rs +++ b/crates/rspack_plugin_javascript/src/webpack_comment.rs @@ -508,7 +508,7 @@ mod tests_extract_regex { let captures = WEBPACK_MAGIC_COMMENT_REGEXP.captures(raw)?; let item_name = captures.name("_0").map(|x| x.as_str().to_string())?; let item_value = captures - .name(&format!("_{}", index)) + .name(&format!("_{index}")) .map(|x| x.as_str().to_string())?; Some((item_name, item_value)) } diff --git a/crates/rspack_plugin_json/src/lib.rs b/crates/rspack_plugin_json/src/lib.rs index de3452a46f2e..6e422cd3e14e 100644 --- a/crates/rspack_plugin_json/src/lib.rs +++ b/crates/rspack_plugin_json/src/lib.rs @@ -211,7 +211,7 @@ impl ParserAndGenerator for JsonParserAndGenerator { generate_context .runtime_requirements .insert(RuntimeGlobals::MODULE); - format!(r#"module.exports = {}"#, json_expr) + format!(r#"module.exports = {json_expr}"#) }; Ok(RawStringSource::from(content).boxed()) } diff --git a/crates/rspack_plugin_lazy_compilation/src/module.rs b/crates/rspack_plugin_lazy_compilation/src/module.rs index b89b83b987f6..69315ae626c1 100644 --- a/crates/rspack_plugin_lazy_compilation/src/module.rs +++ b/crates/rspack_plugin_lazy_compilation/src/module.rs @@ -265,7 +265,7 @@ impl Module for LazyCompilationProxyModule { )) } else { RawStringSource::from(format!( - "{} + "{client} var resolveSelf, onError; module.exports = new Promise(function(resolve, reject) {{ resolveSelf = resolve; onError = reject; }}); if (module.hot) {{ @@ -273,10 +273,8 @@ impl Module for LazyCompilationProxyModule { if (module.hot.data && module.hot.data.resolveSelf) module.hot.data.resolveSelf(module.exports); module.hot.dispose(function(data) {{ data.resolveSelf = resolveSelf; dispose(data); }}); }} - {} - ", - client, - keep_active + {keep_active} + " )) }; diff --git a/crates/rspack_plugin_library/src/modern_module_library_plugin.rs b/crates/rspack_plugin_library/src/modern_module_library_plugin.rs index 5a696b3e31c7..57aa60f3abe2 100644 --- a/crates/rspack_plugin_library/src/modern_module_library_plugin.rs +++ b/crates/rspack_plugin_library/src/modern_module_library_plugin.rs @@ -190,7 +190,7 @@ async fn render_startup( } else if info_name == final_name { exports.push(info_name.to_string()); } else { - exports.push(format!("{} as {}", final_name, info_name)); + exports.push(format!("{final_name} as {info_name}")); } } } @@ -199,11 +199,10 @@ async fn render_startup( let var_name = format!("__webpack_exports__{}", to_identifier(info_name)); source.add(RawStringSource::from(format!( - "var {var_name} = {};\n", - final_name + "var {var_name} = {final_name};\n" ))); - exports.push(format!("{} as {}", var_name, info_name)); + exports.push(format!("{var_name} as {info_name}")); } } diff --git a/crates/rspack_plugin_library/src/module_library_plugin.rs b/crates/rspack_plugin_library/src/module_library_plugin.rs index d9620f93d748..6c4496518153 100644 --- a/crates/rspack_plugin_library/src/module_library_plugin.rs +++ b/crates/rspack_plugin_library/src/module_library_plugin.rs @@ -110,7 +110,7 @@ async fn render_startup( property_access(vec![used_name], 0) ))); } - exports.push(format!("{var_name} as {}", info_name)); + exports.push(format!("{var_name} as {info_name}")); } if !exports.is_empty() { source.add(RawStringSource::from(format!( diff --git a/crates/rspack_plugin_library/src/system_library_plugin.rs b/crates/rspack_plugin_library/src/system_library_plugin.rs index b53db555452a..741bc62c52ab 100644 --- a/crates/rspack_plugin_library/src/system_library_plugin.rs +++ b/crates/rspack_plugin_library/src/system_library_plugin.rs @@ -151,7 +151,7 @@ async fn render( source.add(RawStringSource::from_static("return {\n")); if !is_has_external_modules { // setter : { [function(module){},...] }, - let setters = format!("setters: [{}],\n", setters); + let setters = format!("setters: [{setters}],\n"); source.add(RawStringSource::from(setters)) } source.add(RawStringSource::from_static("execute: function() {\n")); diff --git a/crates/rspack_plugin_library/src/umd_library_plugin.rs b/crates/rspack_plugin_library/src/umd_library_plugin.rs index 49de265cd8d6..9a0280436f3d 100644 --- a/crates/rspack_plugin_library/src/umd_library_plugin.rs +++ b/crates/rspack_plugin_library/src/umd_library_plugin.rs @@ -152,10 +152,9 @@ async fn render( ) }; format!( - r#"function webpackLoadOptionalExternalModuleAmd({}) {{ - return factory({}); - }}"#, - wrapper_arguments, factory_arguments + r#"function webpackLoadOptionalExternalModuleAmd({wrapper_arguments}) {{ + return factory({factory_arguments}); + }}"# ) }; @@ -179,7 +178,7 @@ async fn render( }; let name = if let Some(commonjs) = &names.commonjs { - library_name(&[commonjs.clone()], chunk, compilation).await? + library_name(std::slice::from_ref(commonjs), chunk, compilation).await? } else if let Some(root) = &names.root { library_name(root, chunk, compilation).await? } else { @@ -370,7 +369,7 @@ fn externals_require_array( let mut expr = if let Some(rest) = request.rest() { format!("require({}){}", primary, &accessor_to_object_access(rest)) } else { - format!("require({})", primary) + format!("require({primary})") }; if module_graph.is_optional(&m.id) { expr = format!("(function webpackLoadOptionalExternalModule() {{ try {{ return {expr}; }} catch(e) {{}} }}())"); diff --git a/crates/rspack_plugin_mf/src/container/container_entry_module.rs b/crates/rspack_plugin_mf/src/container/container_entry_module.rs index 445dd3a6e247..66df703d864b 100644 --- a/crates/rspack_plugin_mf/src/container/container_entry_module.rs +++ b/crates/rspack_plugin_mf/src/container/container_entry_module.rs @@ -346,7 +346,7 @@ impl ExposeModuleMap { ), "", ); - format!("return {}.then({});", block_promise, module_raw) + format!("return {block_promise}.then({module_raw});") }; module_map.push((name.to_string(), str)); } @@ -368,9 +368,8 @@ impl ExposeModuleMap { .join("\n"); format!( r#"{{ - {} -}}"#, - module_map + {module_map} +}}"# ) } } diff --git a/crates/rspack_plugin_mf/src/container/container_exposed_dependency.rs b/crates/rspack_plugin_mf/src/container/container_exposed_dependency.rs index 9401501b3c9d..4d6ac92870de 100644 --- a/crates/rspack_plugin_mf/src/container/container_exposed_dependency.rs +++ b/crates/rspack_plugin_mf/src/container/container_exposed_dependency.rs @@ -16,7 +16,7 @@ pub struct ContainerExposedDependency { impl ContainerExposedDependency { pub fn new(exposed_name: String, request: String) -> Self { - let resource_identifier = format!("exposed dependency {}={}", exposed_name, request); + let resource_identifier = format!("exposed dependency {exposed_name}={request}"); Self { id: DependencyId::new(), request, diff --git a/crates/rspack_plugin_mf/src/container/container_reference_plugin.rs b/crates/rspack_plugin_mf/src/container/container_reference_plugin.rs index 6a2704844e48..27975f65902c 100644 --- a/crates/rspack_plugin_mf/src/container/container_reference_plugin.rs +++ b/crates/rspack_plugin_mf/src/container/container_reference_plugin.rs @@ -89,14 +89,16 @@ async fn factorize(&self, data: &mut ModuleFactoryCreateData) -> Result 0) - .then(|| format!("/fallback-{}", itoa!(i))) - .unwrap_or_default() + if i > 0 { + format!("/fallback-{}", itoa!(i)) + } else { + Default::default() + } ) } }) .collect(), - format!(".{}", internal_request), + format!(".{internal_request}"), config.share_scope.clone(), key.to_string(), ) diff --git a/crates/rspack_plugin_mf/src/container/module_federation_runtime_plugin.rs b/crates/rspack_plugin_mf/src/container/module_federation_runtime_plugin.rs index 673f0e9ae539..2ddf08f1d77e 100644 --- a/crates/rspack_plugin_mf/src/container/module_federation_runtime_plugin.rs +++ b/crates/rspack_plugin_mf/src/container/module_federation_runtime_plugin.rs @@ -86,9 +86,8 @@ chunkMatcher: function(chunkId) {{ }; let root_output_dir_str = format!( - r#"rootOutputDir: "{}", -"#, - root_output_dir + r#"rootOutputDir: "{root_output_dir}", +"# ); format!( @@ -98,10 +97,7 @@ if(!{federation_global}){{ {chunk_matcher}{root_output_dir_str} }}; }} -"#, - federation_global = federation_global, - chunk_matcher = chunk_matcher, - root_output_dir_str = root_output_dir_str +"# ) } diff --git a/crates/rspack_plugin_mf/src/sharing/consume_shared_module.rs b/crates/rspack_plugin_mf/src/sharing/consume_shared_module.rs index 5d3a8f03230b..6f6a84a436ee 100644 --- a/crates/rspack_plugin_mf/src/sharing/consume_shared_module.rs +++ b/crates/rspack_plugin_mf/src/sharing/consume_shared_module.rs @@ -49,17 +49,26 @@ impl ConsumeSharedModule { .as_ref() .map(|v| v.to_string()) .unwrap_or_else(|| "*".to_string()), - options - .strict_version - .then_some(" (strict)") - .unwrap_or_default(), - options.singleton.then_some(" (strict)").unwrap_or_default(), + if options.strict_version { + " (strict)" + } else { + Default::default() + }, + if options.singleton { + " (strict)" + } else { + Default::default() + }, options .import_resolved .as_ref() .map(|f| format!(" (fallback: {f})")) .unwrap_or_default(), - options.eager.then_some(" (eager)").unwrap_or_default(), + if options.eager { + " (eager)" + } else { + Default::default() + }, ); Self { blocks: Vec::new(), @@ -72,7 +81,7 @@ impl ConsumeSharedModule { options .import .as_ref() - .map(|r| format!("/{}", r)) + .map(|r| format!("/{r}")) .unwrap_or_default() ), readable_identifier: identifier, @@ -195,7 +204,7 @@ impl Module for ConsumeSharedModule { function += "Singleton"; } let version = json_stringify(&version.to_string()); - args.push(format!("loaders.parseRange({})", version)); + args.push(format!("loaders.parseRange({version})")); function += "VersionCheck"; } else if self.options.singleton { function += "Singleton"; diff --git a/crates/rspack_plugin_mf/src/sharing/consume_shared_plugin.rs b/crates/rspack_plugin_mf/src/sharing/consume_shared_plugin.rs index 04b840975931..f979cb3dde2d 100644 --- a/crates/rspack_plugin_mf/src/sharing/consume_shared_plugin.rs +++ b/crates/rspack_plugin_mf/src/sharing/consume_shared_plugin.rs @@ -48,7 +48,7 @@ pub enum ConsumeVersion { impl fmt::Display for ConsumeVersion { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - ConsumeVersion::Version(v) => write!(f, "{}", v), + ConsumeVersion::Version(v) => write!(f, "{v}"), ConsumeVersion::False => write!(f, "*"), } } diff --git a/crates/rspack_plugin_mf/src/sharing/provide_shared_dependency.rs b/crates/rspack_plugin_mf/src/sharing/provide_shared_dependency.rs index db7d13d45bbb..4644027545f5 100644 --- a/crates/rspack_plugin_mf/src/sharing/provide_shared_dependency.rs +++ b/crates/rspack_plugin_mf/src/sharing/provide_shared_dependency.rs @@ -41,7 +41,7 @@ impl ProvideSharedDependency { &request, &name, &version, - eager.then_some("eager").unwrap_or_default(), + if eager { "eager" } else { Default::default() }, ); Self { id: DependencyId::new(), diff --git a/crates/rspack_plugin_mf/src/sharing/provide_shared_plugin.rs b/crates/rspack_plugin_mf/src/sharing/provide_shared_plugin.rs index 2f43a2e1fa03..621f1d7d9d22 100644 --- a/crates/rspack_plugin_mf/src/sharing/provide_shared_plugin.rs +++ b/crates/rspack_plugin_mf/src/sharing/provide_shared_plugin.rs @@ -74,7 +74,7 @@ pub enum ProvideVersion { impl fmt::Display for ProvideVersion { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - ProvideVersion::Version(v) => write!(f, "{}", v), + ProvideVersion::Version(v) => write!(f, "{v}"), ProvideVersion::False => write!(f, "0"), } } diff --git a/crates/rspack_plugin_module_info_header/src/lib.rs b/crates/rspack_plugin_module_info_header/src/lib.rs index b8afa1feefe0..c66751265b32 100644 --- a/crates/rspack_plugin_module_info_header/src/lib.rs +++ b/crates/rspack_plugin_module_info_header/src/lib.rs @@ -78,7 +78,7 @@ fn print_exports_info_to_source( Some(resolve_target) => { let target_module = request_shortener(&resolve_target.module); match resolve_target.export { - None => format!("-> {}", target_module), + None => format!("-> {target_module}"), Some(es) => { let exp = es.iter().map(|a| a.as_str()).collect::>().join("."); format!(" -> {target_module} {exp}") diff --git a/crates/rspack_plugin_rsdoctor/src/plugin.rs b/crates/rspack_plugin_rsdoctor/src/plugin.rs index ac64d4db96e1..193623fffdc8 100644 --- a/crates/rspack_plugin_rsdoctor/src/plugin.rs +++ b/crates/rspack_plugin_rsdoctor/src/plugin.rs @@ -61,7 +61,7 @@ impl From for RsdoctorPluginModuleGraphFeature { "graph" => RsdoctorPluginModuleGraphFeature::ModuleGraph, "ids" => RsdoctorPluginModuleGraphFeature::ModuleIds, "sources" => RsdoctorPluginModuleGraphFeature::ModuleSources, - _ => panic!("invalid module graph feature: {}", value), + _ => panic!("invalid module graph feature: {value}"), } } } @@ -87,7 +87,7 @@ impl From for RsdoctorPluginChunkGraphFeature { match value.as_str() { "graph" => RsdoctorPluginChunkGraphFeature::ChunkGraph, "assets" => RsdoctorPluginChunkGraphFeature::Assets, - _ => panic!("invalid chunk graph feature: {}", value), + _ => panic!("invalid chunk graph feature: {value}"), } } } @@ -129,10 +129,7 @@ impl RsdoctorPlugin { { return true; } - panic!( - "module graph feature \"{}\" need \"graph\" to be enabled", - feature - ); + panic!("module graph feature \"{feature}\" need \"graph\" to be enabled"); } pub fn has_chunk_graph_feature(&self, feature: RsdoctorPluginChunkGraphFeature) -> bool { @@ -146,10 +143,7 @@ impl RsdoctorPlugin { { return true; } - panic!( - "chunk graph feature \"{}\" need \"graph\" to be enabled", - feature - ); + panic!("chunk graph feature \"{feature}\" need \"graph\" to be enabled"); } pub fn get_compilation_hooks( @@ -230,7 +224,7 @@ async fn optimize_chunks(&self, compilation: &mut Compilation) -> Result {} - Err(e) => panic!("rsdoctor send chunk graph failed: {}", e), + Err(e) => panic!("rsdoctor send chunk graph failed: {e}"), }; }); @@ -342,7 +336,7 @@ async fn optimize_chunk_modules(&self, compilation: &mut Compilation) -> Result< .await { Ok(_) => {} - Err(e) => panic!("rsdoctor send module graph failed: {}", e), + Err(e) => panic!("rsdoctor send module graph failed: {e}"), }; }); @@ -370,7 +364,7 @@ async fn module_ids(&self, compilation: &mut Compilation) -> Result<()> { .await { Ok(_) => {} - Err(e) => panic!("rsdoctor send module ids failed: {}", e), + Err(e) => panic!("rsdoctor send module ids failed: {e}"), }; }); @@ -398,7 +392,7 @@ async fn after_code_generation(&self, compilation: &mut Compilation) -> Result<( .await { Ok(_) => {} - Err(e) => panic!("rsdoctor send module sources failed: {}", e), + Err(e) => panic!("rsdoctor send module sources failed: {e}"), }; }); Ok(()) @@ -435,7 +429,7 @@ async fn after_process_asssets(&self, compilation: &mut Compilation) -> Result<( .await { Ok(_) => {} - Err(e) => panic!("rsdoctor send assets failed: {}", e), + Err(e) => panic!("rsdoctor send assets failed: {e}"), }; }); diff --git a/crates/rspack_plugin_rstest/src/module_path_name_dependency.rs b/crates/rspack_plugin_rstest/src/module_path_name_dependency.rs index e966ad8b4b65..6fa625f905b5 100644 --- a/crates/rspack_plugin_rstest/src/module_path_name_dependency.rs +++ b/crates/rspack_plugin_rstest/src/module_path_name_dependency.rs @@ -70,7 +70,7 @@ impl DependencyTemplate for ModulePathNameDependencyTemplate { if dep.r#type == NameType::FileName { if let Some(resource_path) = resource_path { let init = NormalInitFragment::new( - format!("const __filename = '{}';\n", resource_path), + format!("const __filename = '{resource_path}';\n"), InitFragmentStage::StageConstants, 0, InitFragmentKey::Const(format!("retest __filename {}", m.id())), @@ -82,7 +82,7 @@ impl DependencyTemplate for ModulePathNameDependencyTemplate { } else if dep.r#type == NameType::DirName { if let Some(context) = context { let init = NormalInitFragment::new( - format!("const __dirname = '{}';\n", context), + format!("const __dirname = '{context}';\n"), InitFragmentStage::StageConstants, 0, InitFragmentKey::Const(format!("retest __dirname {}", m.id())), diff --git a/crates/rspack_plugin_rstest/src/parser_plugin.rs b/crates/rspack_plugin_rstest/src/parser_plugin.rs index e147a9772a12..15008e3902b3 100644 --- a/crates/rspack_plugin_rstest/src/parser_plugin.rs +++ b/crates/rspack_plugin_rstest/src/parser_plugin.rs @@ -36,7 +36,7 @@ impl RstestParserPlugin { .and_then(|p| p.parent()) .map(|p| p.to_string()) .unwrap_or_default(); - format!("'{}'", resource_path) + format!("'{resource_path}'") } } } diff --git a/crates/rspack_plugin_runtime/src/runtime_module/chunk_prefetch_preload_function.rs b/crates/rspack_plugin_runtime/src/runtime_module/chunk_prefetch_preload_function.rs index 355e98ccd9ff..4e81430e7991 100644 --- a/crates/rspack_plugin_runtime/src/runtime_module/chunk_prefetch_preload_function.rs +++ b/crates/rspack_plugin_runtime/src/runtime_module/chunk_prefetch_preload_function.rs @@ -17,8 +17,7 @@ impl ChunkPrefetchPreloadFunctionRuntimeModule { ) -> Self { Self::with_default( Identifier::from(format!( - "webpack/runtime/chunk_prefetch_function/{}", - child_type + "webpack/runtime/chunk_prefetch_function/{child_type}" )), runtime_function, runtime_handlers, diff --git a/crates/rspack_plugin_runtime/src/runtime_module/import_scripts_chunk_loading.rs b/crates/rspack_plugin_runtime/src/runtime_module/import_scripts_chunk_loading.rs index ae10d58389ef..a4045f9559c0 100644 --- a/crates/rspack_plugin_runtime/src/runtime_module/import_scripts_chunk_loading.rs +++ b/crates/rspack_plugin_runtime/src/runtime_module/import_scripts_chunk_loading.rs @@ -61,8 +61,8 @@ impl ImportScriptsChunkLoadingRuntimeModule { match id { TemplateId::Raw => base_id.to_string(), - TemplateId::WithHmr => format!("{}_with_hmr", base_id), - TemplateId::WithHmrManifest => format!("{}_with_hmr_manifest", base_id), + TemplateId::WithHmr => format!("{base_id}_with_hmr"), + TemplateId::WithHmrManifest => format!("{base_id}_with_hmr_manifest"), } } } diff --git a/crates/rspack_plugin_runtime/src/runtime_module/jsonp_chunk_loading.rs b/crates/rspack_plugin_runtime/src/runtime_module/jsonp_chunk_loading.rs index 9729d7814bb1..d9d7baa90084 100644 --- a/crates/rspack_plugin_runtime/src/runtime_module/jsonp_chunk_loading.rs +++ b/crates/rspack_plugin_runtime/src/runtime_module/jsonp_chunk_loading.rs @@ -45,12 +45,12 @@ impl JsonpChunkLoadingRuntimeModule { match id { TemplateId::Raw => base_id.to_string(), - TemplateId::WithPrefetch => format!("{}_with_prefetch", base_id), - TemplateId::WithPreload => format!("{}_with_preload", base_id), - TemplateId::WithHmr => format!("{}_with_hmr", base_id), - TemplateId::WithHmrManifest => format!("{}_with_hmr_manifest", base_id), - TemplateId::WithOnChunkLoad => format!("{}_with_on_chunk_load", base_id), - TemplateId::WithCallback => format!("{}_with_callback", base_id), + TemplateId::WithPrefetch => format!("{base_id}_with_prefetch"), + TemplateId::WithPreload => format!("{base_id}_with_preload"), + TemplateId::WithHmr => format!("{base_id}_with_hmr"), + TemplateId::WithHmrManifest => format!("{base_id}_with_hmr_manifest"), + TemplateId::WithOnChunkLoad => format!("{base_id}_with_on_chunk_load"), + TemplateId::WithCallback => format!("{base_id}_with_callback"), } } } @@ -165,7 +165,7 @@ impl RuntimeModule for JsonpChunkLoadingRuntimeModule { match with_hmr { true => { let state_expression = format!("{}_jsonp", RuntimeGlobals::HMR_RUNTIME_STATE_PREFIX); - format!("{} = {} || ", state_expression, state_expression) + format!("{state_expression} = {state_expression} || ") } false => "".to_string(), }, @@ -213,7 +213,7 @@ impl RuntimeModule for JsonpChunkLoadingRuntimeModule { let cross_origin = match cross_origin_loading { CrossOriginLoading::Disable => "".to_string(), CrossOriginLoading::Enable(v) => { - format!("link.crossOrigin = '{}';", v) + format!("link.crossOrigin = '{v}';") } }; let link_prefetch_code = r#" @@ -272,10 +272,9 @@ impl RuntimeModule for JsonpChunkLoadingRuntimeModule { format!( r#" if (link.href.indexOf(window.location.origin + '/') !== 0) {{ - link.crossOrigin = '{}'; + link.crossOrigin = '{v}'; }} - "#, - v + "# ) } } diff --git a/crates/rspack_plugin_runtime/src/runtime_module/module_chunk_loading.rs b/crates/rspack_plugin_runtime/src/runtime_module/module_chunk_loading.rs index 48ff572c1ad1..c90221180218 100644 --- a/crates/rspack_plugin_runtime/src/runtime_module/module_chunk_loading.rs +++ b/crates/rspack_plugin_runtime/src/runtime_module/module_chunk_loading.rs @@ -151,7 +151,7 @@ impl RuntimeModule for ModuleChunkLoadingRuntimeModule { match with_hmr { true => { let state_expression = format!("{}_module", RuntimeGlobals::HMR_RUNTIME_STATE_PREFIX); - format!("{} = {} || ", state_expression, state_expression) + format!("{state_expression} = {state_expression} || ") } false => "".to_string(), }, @@ -209,7 +209,7 @@ impl RuntimeModule for ModuleChunkLoadingRuntimeModule { let cross_origin = match cross_origin_loading { CrossOriginLoading::Disable => "".to_string(), CrossOriginLoading::Enable(v) => { - format!("link.crossOrigin = '{}'", v) + format!("link.crossOrigin = '{v}'") } }; let link_prefetch_code = r#" @@ -267,10 +267,9 @@ impl RuntimeModule for ModuleChunkLoadingRuntimeModule { format!( r#" if (link.href.indexOf(window.location.origin + '/') !== 0) {{ - link.crossOrigin = '{}'; + link.crossOrigin = '{v}'; }} - "#, - v + "# ) } } diff --git a/crates/rspack_plugin_runtime/src/runtime_module/readfile_chunk_loading.rs b/crates/rspack_plugin_runtime/src/runtime_module/readfile_chunk_loading.rs index 68e59d049a31..9336605ac171 100644 --- a/crates/rspack_plugin_runtime/src/runtime_module/readfile_chunk_loading.rs +++ b/crates/rspack_plugin_runtime/src/runtime_module/readfile_chunk_loading.rs @@ -62,11 +62,11 @@ impl ReadFileChunkLoadingRuntimeModule { match id { TemplateId::Raw => base_id, - TemplateId::WithOnChunkLoad => format!("{}_with_on_chunk_load", base_id), - TemplateId::WithLoading => format!("{}_with_loading", base_id), - TemplateId::WithExternalInstallChunk => format!("{}_with_external_install_chunk", base_id), - TemplateId::WithHmr => format!("{}_with_hmr", base_id), - TemplateId::WithHmrManifest => format!("{}_with_hmr_manifest", base_id), + TemplateId::WithOnChunkLoad => format!("{base_id}_with_on_chunk_load"), + TemplateId::WithLoading => format!("{base_id}_with_loading"), + TemplateId::WithExternalInstallChunk => format!("{base_id}_with_external_install_chunk"), + TemplateId::WithHmr => format!("{base_id}_with_hmr"), + TemplateId::WithHmrManifest => format!("{base_id}_with_hmr_manifest"), } } } diff --git a/crates/rspack_plugin_runtime/src/runtime_module/utils.rs b/crates/rspack_plugin_runtime/src/runtime_module/utils.rs index dec5e7716f7a..655980d988f1 100644 --- a/crates/rspack_plugin_runtime/src/runtime_module/utils.rs +++ b/crates/rspack_plugin_runtime/src/runtime_module/utils.rs @@ -218,9 +218,9 @@ pub fn stringify_static_chunk_map(filename: &String, chunk_ids: &[&str]) -> Stri ) }) .join(","); - format!("{{ {} }}[chunkId]", content) + format!("{{ {content} }}[chunkId]") }; - format!("if ({}) return {};", condition, filename) + format!("if ({condition}) return {filename};") } fn stringify_map(map: &HashMap<&str, T>) -> String { diff --git a/crates/rspack_plugin_schemes/src/http_uri/http_cache.rs b/crates/rspack_plugin_schemes/src/http_uri/http_cache.rs index 1c7365ede8e0..fa4dfe1f73e0 100644 --- a/crates/rspack_plugin_schemes/src/http_uri/http_cache.rs +++ b/crates/rspack_plugin_schemes/src/http_uri/http_cache.rs @@ -328,7 +328,7 @@ impl HttpCache { Err(_) => { let digest = Sha512::digest(url_str.as_bytes()); let hex_digest = self.to_hex_string(&digest)[..20].to_string(); - return format!("invalid-url_{}", hex_digest); + return format!("invalid-url_{hex_digest}"); } }; @@ -345,7 +345,7 @@ impl HttpCache { // Limit extension to 20 chars as webpack does let ext = if let Some(ext) = ext_opt { - let ext_str = format!(".{}", ext); + let ext_str = format!(".{ext}"); if ext_str.len() > 20 { String::new() } else { @@ -379,7 +379,7 @@ impl HttpCache { // Combine basename and query, limited to 150 chars let name_component = if !query.is_empty() { - format!("{}_{}", basename, query) + format!("{basename}_{query}") } else { basename }; @@ -389,10 +389,7 @@ impl HttpCache { name_component }; - format!( - "{}/{}_{}{}", - folder_component, name_component, hash_digest, ext - ) + format!("{folder_component}/{name_component}_{hash_digest}{ext}") } /// Convert a string to a safe path component (similar to webpack's toSafePath) @@ -410,7 +407,7 @@ impl HttpCache { let mut result = String::with_capacity(bytes.len() * 2); for b in bytes { use std::fmt::Write; - write!(result, "{:02x}", b).unwrap(); + write!(result, "{b:02x}").expect("write hex failed"); } result } diff --git a/crates/rspack_plugin_schemes/src/http_uri/lockfile.rs b/crates/rspack_plugin_schemes/src/http_uri/lockfile.rs index 255de2228ee0..2e14cbd55763 100644 --- a/crates/rspack_plugin_schemes/src/http_uri/lockfile.rs +++ b/crates/rspack_plugin_schemes/src/http_uri/lockfile.rs @@ -40,7 +40,7 @@ impl Lockfile { let version = data.get("version").and_then(|v| v.as_u64()).unwrap_or(1); if version != 1 { - return Err(format!("Unsupported lockfile version {}", version)); + return Err(format!("Unsupported lockfile version {version}")); } let mut lockfile = Lockfile::new(); @@ -133,7 +133,7 @@ impl LockfileAsync for Lockfile { let content = filesystem .read_file(utf8_path) .await - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{:?}", e)))?; + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{e:?}")))?; let content_str = String::from_utf8(content).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; Lockfile::parse(&content_str).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) diff --git a/crates/rspack_plugin_size_limits/src/lib.rs b/crates/rspack_plugin_size_limits/src/lib.rs index ba593a1f8f1d..db9ee25f325d 100644 --- a/crates/rspack_plugin_size_limits/src/lib.rs +++ b/crates/rspack_plugin_size_limits/src/lib.rs @@ -112,7 +112,7 @@ impl SizeLimitsPlugin { format_size(*size), files .iter() - .map(|file| format!(" {}", file)) + .map(|file| format!(" {file}")) .collect::>() .join("\n") ) diff --git a/crates/rspack_plugin_split_chunks/src/plugin/mod.rs b/crates/rspack_plugin_split_chunks/src/plugin/mod.rs index 6d29d9710ea3..d5a2d42394a4 100644 --- a/crates/rspack_plugin_split_chunks/src/plugin/mod.rs +++ b/crates/rspack_plugin_split_chunks/src/plugin/mod.rs @@ -81,7 +81,7 @@ impl SplitChunksPlugin { if let Some(chunk_reason) = new_chunk_mut.chunk_reason_mut() { chunk_reason.push_str(&format!(" (cache group: {})", cache_group.key.as_str())); if let Some(chunk_name) = &module_group.chunk_name { - chunk_reason.push_str(&format!(" (name: {})", chunk_name)); + chunk_reason.push_str(&format!(" (name: {chunk_name})")); } } diff --git a/crates/rspack_plugin_split_chunks/src/plugin/module_group.rs b/crates/rspack_plugin_split_chunks/src/plugin/module_group.rs index 39c2104d63f7..c4bb25cbb92d 100644 --- a/crates/rspack_plugin_split_chunks/src/plugin/module_group.rs +++ b/crates/rspack_plugin_split_chunks/src/plugin/module_group.rs @@ -643,7 +643,7 @@ async fn merge_matched_item_into_module_group_map( let selected_chunks_key = match chunk_key_to_string.entry(selected_chunks_key) { hash_map::Entry::Occupied(entry) => entry.get().to_string(), hash_map::Entry::Vacant(entry) => { - let key = format!("{:x}", selected_chunks_key); + let key = format!("{selected_chunks_key:x}"); entry.insert(key.clone()); key } diff --git a/crates/rspack_plugin_sri/src/asset.rs b/crates/rspack_plugin_sri/src/asset.rs index 712f0c616ab5..5a8f44df4f46 100644 --- a/crates/rspack_plugin_sri/src/asset.rs +++ b/crates/rspack_plugin_sri/src/asset.rs @@ -293,7 +293,7 @@ pub async fn detect_unresolved_integrity(&self, compilation: &mut Compilation) - for file in contain_unresolved_files { compilation.push_diagnostic(Diagnostic::error( "SubresourceIntegrity".to_string(), - format!("Asset {} contains unresolved integrity placeholders", file), + format!("Asset {file} contains unresolved integrity placeholders"), )); } Ok(()) diff --git a/crates/rspack_plugin_sri/src/config.rs b/crates/rspack_plugin_sri/src/config.rs index 3d6b02cca5bd..5586bb1b9fde 100644 --- a/crates/rspack_plugin_sri/src/config.rs +++ b/crates/rspack_plugin_sri/src/config.rs @@ -26,7 +26,7 @@ impl From for IntegrityHtmlPlugin { "JavaScript" => Self::JavaScriptPlugin, "Native" => Self::NativePlugin, "Disabled" => Self::Disabled, - _ => panic!("Invalid integrity html plugin: {}", value), + _ => panic!("Invalid integrity html plugin: {value}"), } } } diff --git a/crates/rspack_plugin_sri/src/runtime.rs b/crates/rspack_plugin_sri/src/runtime.rs index 2cce9ecaca2a..c7ec8c27e641 100644 --- a/crates/rspack_plugin_sri/src/runtime.rs +++ b/crates/rspack_plugin_sri/src/runtime.rs @@ -23,7 +23,7 @@ fn add_attribute(tag: &str, code: &str, cross_origin_loading: &CrossOriginLoadin SRI_HASH_VARIABLE_REFERENCE, match cross_origin_loading { CrossOriginLoading::Disable => "false".to_string(), - CrossOriginLoading::Enable(v) => format!("'{}'", v), + CrossOriginLoading::Enable(v) => format!("'{v}'"), } ) } @@ -107,7 +107,7 @@ fn generate_sri_hash_placeholders( .filter_map(|c| { let chunk_id = serde_json::to_string(c.as_str()).ok()?; let placeholder = serde_json::to_string(&make_placeholder(hash_funcs, c.as_str())).ok()?; - Some(format!("{}: {}", chunk_id, placeholder)) + Some(format!("{chunk_id}: {placeholder}")) }) .collect::>() .join(",") diff --git a/crates/rspack_plugin_sri/src/util.rs b/crates/rspack_plugin_sri/src/util.rs index 8800d9eda4a3..a8b23ac62d68 100644 --- a/crates/rspack_plugin_sri/src/util.rs +++ b/crates/rspack_plugin_sri/src/util.rs @@ -13,8 +13,7 @@ pub const PLACEHOLDER_PREFIX: &str = "*-*-*-CHUNK-SRI-HASH-"; pub static PLACEHOLDER_REGEX: LazyLock = LazyLock::new(|| { let escaped_prefix = regex::escape(PLACEHOLDER_PREFIX); regex::Regex::new(&format!( - r"{}[a-zA-Z0-9=/+]+(\s+sha\d{{3}}-[a-zA-Z0-9=/+]+)*", - escaped_prefix + r"{escaped_prefix}[a-zA-Z0-9=/+]+(\s+sha\d{{3}}-[a-zA-Z0-9=/+]+)*" )) .expect("should initialize `Regex`") }); @@ -66,7 +65,7 @@ fn recurse_chunk( } pub fn make_placeholder(hash_funcs: &Vec, id: &str) -> String { - let placeholder_source = format!("{}{}", PLACEHOLDER_PREFIX, id); + let placeholder_source = format!("{PLACEHOLDER_PREFIX}{id}"); let filler = compute_integrity(hash_funcs, &placeholder_source); format!( "{}{}", diff --git a/crates/rspack_plugin_swc_js_minimizer/src/lib.rs b/crates/rspack_plugin_swc_js_minimizer/src/lib.rs index 2a58238130f9..1a8fda5a14d9 100644 --- a/crates/rspack_plugin_swc_js_minimizer/src/lib.rs +++ b/crates/rspack_plugin_swc_js_minimizer/src/lib.rs @@ -219,7 +219,7 @@ async fn process_assets(&self, compilation: &mut Compilation) -> Result<()> { ..Default::default() }; let extract_comments_option = options.extract_comments.as_ref().map(|extract_comments| { - let comments_filename = format!("{}.LICENSE.txt", filename); + let comments_filename = format!("{filename}.LICENSE.txt"); let banner = match &extract_comments.banner { OptionWrapper::Default => { let dir = Path::new(filename).parent().expect("should has parent"); diff --git a/crates/rspack_plugin_wasm/src/runtime.rs b/crates/rspack_plugin_wasm/src/runtime.rs index bd7f8f6b7703..05bcee4754b3 100644 --- a/crates/rspack_plugin_wasm/src/runtime.rs +++ b/crates/rspack_plugin_wasm/src/runtime.rs @@ -62,7 +62,7 @@ impl RuntimeModule for AsyncWasmLoadingRuntimeModule { Ok(get_async_wasm_loading( &self .generate_load_binary_code - .cow_replace("$PATH", &format!("\"{}\"", path)) + .cow_replace("$PATH", &format!("\"{path}\"")) .cow_replace( "$IMPORT_META_NAME", compilation.options.output.import_meta_name.as_str(), diff --git a/crates/rspack_regex/src/napi.rs b/crates/rspack_regex/src/napi.rs index ef04f3fdc2e0..52e5a94d2910 100644 --- a/crates/rspack_regex/src/napi.rs +++ b/crates/rspack_regex/src/napi.rs @@ -50,10 +50,7 @@ impl FromNapiValue for RspackRegex { } else { Err(napi::Error::new( napi::Status::ObjectExpected, - format!( - "Expect value to be '[object RegExp]', but received {}", - object_type - ), + format!("Expect value to be '[object RegExp]', but received {object_type}"), )) } } diff --git a/crates/rspack_storage/src/error.rs b/crates/rspack_storage/src/error.rs index 871a137c029e..c441f118938a 100644 --- a/crates/rspack_storage/src/error.rs +++ b/crates/rspack_storage/src/error.rs @@ -46,7 +46,7 @@ impl std::fmt::Display for ErrorReason { ErrorReason::Detail(detail) => { write!(f, "{}", detail.reason)?; for line in detail.packs.iter().take(5) { - write!(f, "\n{}", line)?; + write!(f, "\n{line}")?; } if detail.packs.len() > 5 { write!(f, "\n...")?; @@ -56,11 +56,11 @@ impl std::fmt::Display for ErrorReason { if let Some(e) = e.downcast_ref::() { write!(f, "{}", e.inner)?; } else { - write!(f, "{}", e)?; + write!(f, "{e}")?; } } ErrorReason::Reason(e) => { - write!(f, "{}", e)?; + write!(f, "{e}")?; } }; Ok(()) @@ -150,9 +150,9 @@ impl Error { impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if let Some(t) = &self.r#type { - write!(f, "{} ", t)?; + write!(f, "{t} ")?; if let Some(scope) = self.scope { - write!(f, "scope `{}` ", scope)?; + write!(f, "scope `{scope}` ")?; } write!(f, "failed due to")?; write!(f, " {}", self.inner)?; diff --git a/crates/rspack_storage/src/fs/error.rs b/crates/rspack_storage/src/fs/error.rs index 58b32c17221e..e30fad5ae566 100644 --- a/crates/rspack_storage/src/fs/error.rs +++ b/crates/rspack_storage/src/fs/error.rs @@ -114,10 +114,10 @@ impl std::fmt::Display for BatchFSError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.message)?; if let Some(join_error) = &self.join_error { - write!(f, " due to `{}`", join_error)?; + write!(f, " due to `{join_error}`")?; } else { for error in self.errors.iter().take(5) { - write!(f, "\n{}", error)?; + write!(f, "\n{error}")?; } if self.errors.len() > 5 { write!(f, "\n...")?; diff --git a/crates/rspack_storage/src/pack/manager/mod.rs b/crates/rspack_storage/src/pack/manager/mod.rs index 4414211768d6..97838877e0dd 100644 --- a/crates/rspack_storage/src/pack/manager/mod.rs +++ b/crates/rspack_storage/src/pack/manager/mod.rs @@ -376,8 +376,7 @@ mod tests { assert!(!(fs.exists(root.join("scope2/scope_meta").as_path()).await?)); // wait for saving to files - rx.await - .unwrap_or_else(|e| panic!("save failed: {:?}", e))?; + rx.await.unwrap_or_else(|e| panic!("save failed: {e:?}"))?; assert_eq!(manager.load("scope1").await?.len(), 100); assert_eq!(manager.load("scope2").await?.len(), 100); @@ -437,8 +436,7 @@ mod tests { .mtime_ms; // wait for updating files - rx.await - .unwrap_or_else(|e| panic!("save failed: {:?}", e))?; + rx.await.unwrap_or_else(|e| panic!("save failed: {e:?}"))?; assert_eq!(manager.load("scope1").await?.len(), 100); assert_eq!(manager.load("scope2").await?.len(), 50); assert_ne!( @@ -498,8 +496,7 @@ mod tests { ); let rx = manager.save(scope_updates)?; // assert_eq!(manager.load("scope1").await?.len(), 100); - rx.await - .unwrap_or_else(|e| panic!("save failed: {:?}", e))?; + rx.await.unwrap_or_else(|e| panic!("save failed: {e:?}"))?; // assert_eq!(manager.load("scope1").await?.len(), 100); // // will override cache files to new one diff --git a/crates/rspack_storage/src/pack/strategy/split/handle_file.rs b/crates/rspack_storage/src/pack/strategy/split/handle_file.rs index 0f84475a9aa0..cda12e121b26 100644 --- a/crates/rspack_storage/src/pack/strategy/split/handle_file.rs +++ b/crates/rspack_storage/src/pack/strategy/split/handle_file.rs @@ -138,7 +138,7 @@ async fn recovery_lock( FSError::from_message( &lock_file, FSOperation::Read, - format!("parse utf8 failed: {}", e), + format!("parse utf8 failed: {e}"), ) })?; let files = lock_file_content @@ -355,7 +355,7 @@ async fn try_remove_version( FSError::from_message( &meta, FSOperation::Read, - format!("parse option meta failed: {}", e), + format!("parse option meta failed: {e}"), ) })?; let current = current_time(); diff --git a/crates/rspack_storage/src/pack/strategy/split/mod.rs b/crates/rspack_storage/src/pack/strategy/split/mod.rs index 759750b77703..94a53f66fee5 100644 --- a/crates/rspack_storage/src/pack/strategy/split/mod.rs +++ b/crates/rspack_storage/src/pack/strategy/split/mod.rs @@ -93,7 +93,7 @@ impl RootStrategy for SplitPackStrategy { FSError::from_message( &meta_path, FSOperation::Read, - format!("parse root meta failed: {}", e), + format!("parse root meta failed: {e}"), ) })?; let scopes = reader diff --git a/crates/rspack_storage/src/pack/strategy/split/read_pack.rs b/crates/rspack_storage/src/pack/strategy/split/read_pack.rs index 6a91b702cc00..e89988680ccb 100644 --- a/crates/rspack_storage/src/pack/strategy/split/read_pack.rs +++ b/crates/rspack_storage/src/pack/strategy/split/read_pack.rs @@ -31,7 +31,7 @@ impl PackReadStrategy for SplitPackStrategy { FSError::from_message( path, FSOperation::Read, - format!("parse pack key lengths failed: {}", e), + format!("parse pack key lengths failed: {e}"), ) }) }) @@ -65,7 +65,7 @@ impl PackReadStrategy for SplitPackStrategy { FSError::from_message( path, FSOperation::Read, - format!("parse pack key lengths failed: {}", e), + format!("parse pack key lengths failed: {e}"), ) }) }) @@ -82,7 +82,7 @@ impl PackReadStrategy for SplitPackStrategy { FSError::from_message( path, FSOperation::Read, - format!("parse pack content lengths failed: {}", e), + format!("parse pack content lengths failed: {e}"), ) }) }) @@ -97,7 +97,7 @@ impl PackReadStrategy for SplitPackStrategy { FSError::from_message( path, FSOperation::Read, - format!("parse pack generations failed: {}", e), + format!("parse pack generations failed: {e}"), ) }) }) diff --git a/crates/rspack_storage/src/pack/strategy/split/read_scope.rs b/crates/rspack_storage/src/pack/strategy/split/read_scope.rs index bb0cee9e83c8..c41cf953748b 100644 --- a/crates/rspack_storage/src/pack/strategy/split/read_scope.rs +++ b/crates/rspack_storage/src/pack/strategy/split/read_scope.rs @@ -110,7 +110,7 @@ async fn read_scope_meta( Error::from_reason( Some(ErrorType::Load), Some(scope), - format!("parse option meta failed: {}", e), + format!("parse option meta failed: {e}"), ) }) }) @@ -152,14 +152,14 @@ async fn read_scope_meta( Error::from_reason( Some(ErrorType::Load), Some(scope), - format!("parse file meta failed: {}", e), + format!("parse file meta failed: {e}"), ) })?, generation: i[3].parse::().map_err(|e| { Error::from_reason( Some(ErrorType::Load), Some(scope), - format!("parse file meta failed: {}", e), + format!("parse file meta failed: {e}"), ) })?, wrote: true, @@ -300,9 +300,9 @@ mod tests { mock_scope_meta_file(&ScopeMeta::get_path(path), fs, options, 3).await?; for bucket_id in 0..options.bucket_size { for pack_no in 0..3 { - let unique_id = format!("{}_{}", bucket_id, pack_no); - let pack_name = format!("pack_name_{}_{}", bucket_id, pack_no); - let pack_path = path.join(format!("./{}/{}", bucket_id, pack_name)); + let unique_id = format!("{bucket_id}_{pack_no}"); + let pack_name = format!("pack_name_{bucket_id}_{pack_no}"); + let pack_path = path.join(format!("./{bucket_id}/{pack_name}")); mock_pack_file(&pack_path, &unique_id, 10, fs).await?; } } diff --git a/crates/rspack_storage/src/pack/strategy/split/util.rs b/crates/rspack_storage/src/pack/strategy/split/util.rs index 40dce7f14648..768a6c865a17 100644 --- a/crates/rspack_storage/src/pack/strategy/split/util.rs +++ b/crates/rspack_storage/src/pack/strategy/split/util.rs @@ -124,13 +124,10 @@ pub mod test_pack_utils { for bucket_id in 0..options.bucket_size { let mut pack_meta_list = vec![]; for pack_no in 0..pack_count { - let pack_name = format!("pack_name_{}_{}", bucket_id, pack_no); - let pack_hash = format!("pack_hash_{}_{}", bucket_id, pack_no); + let pack_name = format!("pack_name_{bucket_id}_{pack_no}"); + let pack_hash = format!("pack_hash_{bucket_id}_{pack_no}"); let pack_size = 100; - pack_meta_list.push(format!( - "{},{},{},{}", - pack_name, pack_hash, pack_size, generation - )); + pack_meta_list.push(format!("{pack_name},{pack_hash},{pack_size},{generation}")); } writer.write_line(pack_meta_list.join(" ").as_str()).await?; } @@ -153,8 +150,8 @@ pub mod test_pack_utils { let mut contents = vec![]; let generations = vec![1_usize; item_count]; for i in 0..item_count { - keys.push(format!("key_{}_{}", unique_id, i).as_bytes().to_vec()); - contents.push(format!("val_{}_{}", unique_id, i).as_bytes().to_vec()); + keys.push(format!("key_{unique_id}_{i}").as_bytes().to_vec()); + contents.push(format!("val_{unique_id}_{i}").as_bytes().to_vec()); } writer .write_line(keys.iter().map(|k| k.len()).join(" ").as_str()) diff --git a/crates/rspack_storage/src/pack/strategy/split/write_scope.rs b/crates/rspack_storage/src/pack/strategy/split/write_scope.rs index 59c0c7587559..3bbff9c28236 100644 --- a/crates/rspack_storage/src/pack/strategy/split/write_scope.rs +++ b/crates/rspack_storage/src/pack/strategy/split/write_scope.rs @@ -407,9 +407,9 @@ mod tests { assert_eq!(contents.len(), end); assert_eq!( *contents - .get(format!("{:0>4}_key", start).as_bytes()) + .get(format!("{start:0>4}_key").as_bytes()) .expect("should have key"), - format!("{:0>4}_val", start).as_bytes() + format!("{start:0>4}_val").as_bytes() ); assert_eq!( *contents @@ -439,9 +439,9 @@ mod tests { assert_eq!(contents.len(), pre_item_count + end - start); assert_eq!( *contents - .get(format!("{:0>20}_key", start).as_bytes()) + .get(format!("{start:0>20}_key").as_bytes()) .expect("should have key"), - format!("{:0>20}_val", start).as_bytes() + format!("{start:0>20}_val").as_bytes() ); assert_eq!( *contents diff --git a/crates/rspack_storage/tests/build.rs b/crates/rspack_storage/tests/build.rs index 26a310d2bd16..c62993d82bc3 100644 --- a/crates/rspack_storage/tests/build.rs +++ b/crates/rspack_storage/tests/build.rs @@ -51,8 +51,8 @@ mod test_storage_build { for i in 0..1000 { storage.set( "test_scope", - format!("key_{:0>3}", i).as_bytes().to_vec(), - format!("val_{:0>3}", i).as_bytes().to_vec(), + format!("key_{i:0>3}").as_bytes().to_vec(), + format!("val_{i:0>3}").as_bytes().to_vec(), ); } let rx = storage.trigger_save()?; diff --git a/crates/rspack_storage/tests/dev.rs b/crates/rspack_storage/tests/dev.rs index 25954ed0de19..a001620020bf 100644 --- a/crates/rspack_storage/tests/dev.rs +++ b/crates/rspack_storage/tests/dev.rs @@ -51,8 +51,8 @@ mod test_storage_dev { for i in 0..300 { storage.set( "test_scope", - format!("key_{:0>3}", i).as_bytes().to_vec(), - format!("val_{:0>3}", i).as_bytes().to_vec(), + format!("key_{i:0>3}").as_bytes().to_vec(), + format!("val_{i:0>3}").as_bytes().to_vec(), ); } storage.trigger_save()?.await.expect("should save")?; @@ -61,8 +61,8 @@ mod test_storage_dev { for i in 300..700 { storage.set( "test_scope", - format!("key_{:0>3}", i).as_bytes().to_vec(), - format!("val_{:0>3}", i).as_bytes().to_vec(), + format!("key_{i:0>3}").as_bytes().to_vec(), + format!("val_{i:0>3}").as_bytes().to_vec(), ); } storage.trigger_save()?.await.expect("should save")?; @@ -70,8 +70,8 @@ mod test_storage_dev { for i in 700..1000 { storage.set( "test_scope", - format!("key_{:0>3}", i).as_bytes().to_vec(), - format!("val_{:0>3}", i).as_bytes().to_vec(), + format!("key_{i:0>3}").as_bytes().to_vec(), + format!("val_{i:0>3}").as_bytes().to_vec(), ); } let rx = storage.trigger_save()?; diff --git a/crates/rspack_storage/tests/error.rs b/crates/rspack_storage/tests/error.rs index e5b5f62e7f48..6d2fa2de70bc 100644 --- a/crates/rspack_storage/tests/error.rs +++ b/crates/rspack_storage/tests/error.rs @@ -51,8 +51,8 @@ mod test_storage_error { for i in 0..1000 { storage.set( "test_scope", - format!("key_{:0>3}", i).as_bytes().to_vec(), - format!("val_{:0>3}", i).as_bytes().to_vec(), + format!("key_{i:0>3}").as_bytes().to_vec(), + format!("val_{i:0>3}").as_bytes().to_vec(), ); } let rx = storage.trigger_save()?; @@ -106,10 +106,7 @@ mod test_storage_error { .split(",") .next() .expect("should have first pack"); - Ok(Utf8PathBuf::from(format!( - "{}/0/{}", - scope_name, first_pack - ))) + Ok(Utf8PathBuf::from(format!("{scope_name}/0/{first_pack}"))) } async fn test_recovery_remove_pack( diff --git a/crates/rspack_storage/tests/expire.rs b/crates/rspack_storage/tests/expire.rs index 893ef176d89d..fc65589bd199 100644 --- a/crates/rspack_storage/tests/expire.rs +++ b/crates/rspack_storage/tests/expire.rs @@ -43,8 +43,8 @@ mod test_storage_expire { for i in 0..100 { storage.set( "test_scope", - format!("key_{:0>3}", i).as_bytes().to_vec(), - format!("val_{:0>3}", i).as_bytes().to_vec(), + format!("key_{i:0>3}").as_bytes().to_vec(), + format!("val_{i:0>3}").as_bytes().to_vec(), ); } let rx = storage.trigger_save()?; diff --git a/crates/rspack_storage/tests/lock.rs b/crates/rspack_storage/tests/lock.rs index 637f1f5ec508..df8447ca3f28 100644 --- a/crates/rspack_storage/tests/lock.rs +++ b/crates/rspack_storage/tests/lock.rs @@ -106,8 +106,8 @@ mod test_storage_lock { for i in 0..100 { storage.set( "test_scope", - format!("key_{:0>3}", i).as_bytes().to_vec(), - format!("val_{:0>3}", i).as_bytes().to_vec(), + format!("key_{i:0>3}").as_bytes().to_vec(), + format!("val_{i:0>3}").as_bytes().to_vec(), ); } let rx = storage.trigger_save()?; diff --git a/crates/rspack_storage/tests/multi.rs b/crates/rspack_storage/tests/multi.rs index b1c08cf1e5dc..52b579618862 100644 --- a/crates/rspack_storage/tests/multi.rs +++ b/crates/rspack_storage/tests/multi.rs @@ -53,13 +53,13 @@ mod test_storage_multi { for i in 0..500 { storage.set( "scope_1", - format!("scope_1_key_{:0>3}", i).as_bytes().to_vec(), - format!("scope_1_val_{:0>3}", i).as_bytes().to_vec(), + format!("scope_1_key_{i:0>3}").as_bytes().to_vec(), + format!("scope_1_val_{i:0>3}").as_bytes().to_vec(), ); storage.set( "scope_2", - format!("scope_2_key_{:0>3}", i).as_bytes().to_vec(), - format!("scope_2_val_{:0>3}", i).as_bytes().to_vec(), + format!("scope_2_key_{i:0>3}").as_bytes().to_vec(), + format!("scope_2_val_{i:0>3}").as_bytes().to_vec(), ); } let rx = storage.trigger_save()?; diff --git a/crates/rspack_storage/tests/release.rs b/crates/rspack_storage/tests/release.rs index 7a23b8574791..386b9b2c19e8 100644 --- a/crates/rspack_storage/tests/release.rs +++ b/crates/rspack_storage/tests/release.rs @@ -80,8 +80,8 @@ mod test_storage_release { for i in 0..1000 { storage.set( scope_name, - format!("key_{:0>3}", i).as_bytes().to_vec(), - format!("val_{:0>3}", i).as_bytes().to_vec(), + format!("key_{i:0>3}").as_bytes().to_vec(), + format!("val_{i:0>3}").as_bytes().to_vec(), ); } storage.trigger_save()?.await.expect("should save")?; @@ -95,8 +95,8 @@ mod test_storage_release { for i in 0..100 { storage.set( scope_name, - format!("key_{:0>3}", i).as_bytes().to_vec(), - format!("new_{:0>3}", i).as_bytes().to_vec(), + format!("key_{i:0>3}").as_bytes().to_vec(), + format!("new_{i:0>3}").as_bytes().to_vec(), ); } storage.trigger_save()?.await.expect("should save")?; @@ -110,8 +110,8 @@ mod test_storage_release { for i in 100..200 { storage.set( scope_name, - format!("key_{:0>3}", i).as_bytes().to_vec(), - format!("new_{:0>3}", i).as_bytes().to_vec(), + format!("key_{i:0>3}").as_bytes().to_vec(), + format!("new_{i:0>3}").as_bytes().to_vec(), ); } storage.trigger_save()?.await.expect("should save")?; @@ -125,8 +125,8 @@ mod test_storage_release { for i in 200..300 { storage.set( scope_name, - format!("key_{:0>3}", i).as_bytes().to_vec(), - format!("new_{:0>3}", i).as_bytes().to_vec(), + format!("key_{i:0>3}").as_bytes().to_vec(), + format!("new_{i:0>3}").as_bytes().to_vec(), ); } storage.trigger_save()?.await.expect("should save")?; @@ -140,8 +140,8 @@ mod test_storage_release { for i in 300..400 { storage.set( scope_name, - format!("key_{:0>3}", i).as_bytes().to_vec(), - format!("new_{:0>3}", i).as_bytes().to_vec(), + format!("key_{i:0>3}").as_bytes().to_vec(), + format!("new_{i:0>3}").as_bytes().to_vec(), ); } storage.trigger_save()?.await.expect("should save")?; @@ -155,8 +155,8 @@ mod test_storage_release { for i in 400..500 { storage.set( scope_name, - format!("key_{:0>3}", i).as_bytes().to_vec(), - format!("new_{:0>3}", i).as_bytes().to_vec(), + format!("key_{i:0>3}").as_bytes().to_vec(), + format!("new_{i:0>3}").as_bytes().to_vec(), ); } storage.trigger_save()?.await.expect("should save")?; @@ -170,8 +170,8 @@ mod test_storage_release { for i in 500..600 { storage.set( scope_name, - format!("key_{:0>3}", i).as_bytes().to_vec(), - format!("new_{:0>3}", i).as_bytes().to_vec(), + format!("key_{i:0>3}").as_bytes().to_vec(), + format!("new_{i:0>3}").as_bytes().to_vec(), ); } storage.trigger_save()?.await.expect("should save")?; diff --git a/crates/rspack_util/src/node_path.rs b/crates/rspack_util/src/node_path.rs index b2ac712e6d76..17c97fc93177 100644 --- a/crates/rspack_util/src/node_path.rs +++ b/crates/rspack_util/src/node_path.rs @@ -341,7 +341,7 @@ impl NodePath for Utf8PathBuf { } if is_absolute { - Utf8PathBuf::from(format!("/{}", normalized_path)) + Utf8PathBuf::from(format!("/{normalized_path}")) } else { Utf8PathBuf::from(normalized_path) } @@ -401,7 +401,7 @@ impl NodePath for Utf8PathBuf { if j < len || j != last { if first_part == "." || first_part == "?" { // We matched a device root (e.g. \\\\.\\PHYSICALDRIVE0) - device = Some(Cow::from(format!("\\\\{}", first_part))); + device = Some(Cow::from(format!("\\\\{first_part}"))); root_end = 4; } else if j == len { // We matched a UNC root only @@ -453,21 +453,21 @@ impl NodePath for Utf8PathBuf { && is_windows_device_root(&tail.as_bytes()[0]) && tail.as_bytes().get(1) == Some(&b':') { - return Utf8PathBuf::from(format!(".\\{}", tail)); + return Utf8PathBuf::from(format!(".\\{tail}")); } let mut index = path.find(':'); while let Some(i) = index { if i == path.len() - 1 || path.as_bytes().get(i + 1).is_some_and(is_path_separator) { - return Utf8PathBuf::from(format!(".\\{}", tail)); + return Utf8PathBuf::from(format!(".\\{tail}")); } index = path[i + 1..].find(':').map(|next| next + i + 1); } } match device { - Some(device) if is_absolute => Utf8PathBuf::from(format!("{}\\{}", device, tail)), - Some(device) => Utf8PathBuf::from(format!("{}{}", device, tail)), - None if is_absolute => Utf8PathBuf::from(format!("\\{}", tail)), + Some(device) if is_absolute => Utf8PathBuf::from(format!("{device}\\{tail}")), + Some(device) => Utf8PathBuf::from(format!("{device}{tail}")), + None if is_absolute => Utf8PathBuf::from(format!("\\{tail}")), _ => Utf8PathBuf::from(tail), } } diff --git a/crates/rspack_util/src/test.rs b/crates/rspack_util/src/test.rs index b23d5df3625f..7088ee14f409 100644 --- a/crates/rspack_util/src/test.rs +++ b/crates/rspack_util/src/test.rs @@ -8,8 +8,8 @@ pub fn is_hot_test() -> bool { } pub static HOT_TEST_DEFINE_GLOBAL: LazyLock = LazyLock::new(|| { - is_hot_test() - .then(|| { + if is_hot_test() { + { r#" self.__HMR_UPDATED_RUNTIME__ = { javascript: { @@ -25,55 +25,65 @@ pub static HOT_TEST_DEFINE_GLOBAL: LazyLock = LazyLock::new(|| { }; "# .to_string() - }) - .unwrap_or_default() + } + } else { + Default::default() + } }); pub static HOT_TEST_STATUS_CHANGE: LazyLock = LazyLock::new(|| { - is_hot_test() - .then(|| { + if is_hot_test() { + { r#" self.__HMR_UPDATED_RUNTIME__.statusPath.push(newStatus); "# .to_string() - }) - .unwrap_or_default() + } + } else { + Default::default() + } }); pub static HOT_TEST_OUTDATED: LazyLock = LazyLock::new(|| { - is_hot_test() - .then(|| { + if is_hot_test() { + { r#" self.__HMR_UPDATED_RUNTIME__.javascript.outdatedModules = outdatedModules; self.__HMR_UPDATED_RUNTIME__.javascript.outdatedDependencies = outdatedDependencies; "# .to_string() - }) - .unwrap_or_default() + } + } else { + Default::default() + } }); pub static HOT_TEST_DISPOSE: LazyLock = LazyLock::new(|| { - is_hot_test() - .then(|| { + if is_hot_test() { + { r#" if (disposeHandlers.length > 0) { self.__HMR_UPDATED_RUNTIME__.javascript.disposedModules.push(moduleId); } "# .to_string() - }) - .unwrap_or_default() + } + } else { + Default::default() + } }); pub static HOT_TEST_UPDATED: LazyLock = LazyLock::new(|| { - is_hot_test() - .then(|| { + if is_hot_test() { + { r#" self.__HMR_UPDATED_RUNTIME__.javascript.updatedModules.push(updateModuleId); "# .to_string() - }) - .unwrap_or_default() + } + } else { + Default::default() + } }); pub static HOT_TEST_RUNTIME: LazyLock = LazyLock::new(|| { @@ -93,12 +103,14 @@ pub static HOT_TEST_RUNTIME: LazyLock = LazyLock::new(|| { }); pub static HOT_TEST_ACCEPT: LazyLock = LazyLock::new(|| { - is_hot_test() - .then(|| { + if is_hot_test() { + { r#" self.__HMR_UPDATED_RUNTIME__.javascript.acceptedModules.push(dependency); "# .to_string() - }) - .unwrap_or_default() + } + } else { + Default::default() + } }); diff --git a/crates/swc_plugin_import/src/legacy_case.rs b/crates/swc_plugin_import/src/legacy_case.rs index 1b5fda5e8a75..98e86f80d24c 100644 --- a/crates/swc_plugin_import/src/legacy_case.rs +++ b/crates/swc_plugin_import/src/legacy_case.rs @@ -16,7 +16,7 @@ fn transform_like_babel_plugin_import(s: &str, sym: &str, f: &mut fmt::Formatter write!(f, "{}{}", sym, c.to_lowercase())?; } } else { - write!(f, "{}", c)?; + write!(f, "{c}")?; } is_first = false } diff --git a/rust-toolchain.toml b/rust-toolchain.toml index fd521f747c69..22eee8f3cb0f 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,6 +1,4 @@ [toolchain] profile = "default" # Use nightly for better access to the latest Rust features. -# This date is aligned to stable release dates. -# stable-2025-04-03 -> v1.86.0 -channel = "nightly-2025-03-26" +channel = "nightly-2025-05-30" diff --git a/tasks/benchmark/benches/groups/build_chunk_graph.rs b/tasks/benchmark/benches/groups/build_chunk_graph.rs index bf63c3ed08a2..ccd28b5c30ca 100644 --- a/tasks/benchmark/benches/groups/build_chunk_graph.rs +++ b/tasks/benchmark/benches/groups/build_chunk_graph.rs @@ -42,9 +42,7 @@ function Navbar({ show }) { export default Navbar"; ctx.push(( - format!("/src/leaves/Component-{}.js", index) - .as_str() - .into(), + format!("/src/leaves/Component-{index}.js").as_str().into(), code.to_string(), )); } @@ -66,20 +64,18 @@ fn gen_dynamic_module( for i in index..index + 10 { static_imports.push(format!( - "import Comp{} from '/src/leaves/Component-{}.js'", - i, i, + "import Comp{i} from '/src/leaves/Component-{i}.js'" )); gen_static_leaf_module(i, ctx); - access.push(format!("Comp{}", i)); + access.push(format!("Comp{i}")); } let depth = index / 10; for random in random_table[depth].iter() { reuse.push(format!( - "import Comp{} from '/src/leaves/Component-{}.js'", - random, random, + "import Comp{random} from '/src/leaves/Component-{random}.js'" )); - access.push(format!("Comp{}", random)); + access.push(format!("Comp{random}")); } if gen_dynamic_module(num, index + 10, random_table, ctx) { @@ -95,7 +91,7 @@ fn gen_dynamic_module( depth ); - ctx.push((format!("/src/dynamic-{}.js", depth).as_str().into(), code)); + ctx.push((format!("/src/dynamic-{depth}.js").as_str().into(), code)); true }