From f5840bdcd360ec0bac2501f333e58e25742b1537 Mon Sep 17 00:00:00 2001 From: David Sherret Date: Fri, 27 Jan 2023 10:43:16 -0500 Subject: [PATCH] chore: upgrade to Rust 1.67 (#17548) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Bartek Iwańczuk --- .github/workflows/ci.generate.ts | 2 +- .github/workflows/ci.yml | 2 +- bench_util/js_runtime.rs | 2 +- cli/args/config_file.rs | 2 +- cli/args/flags.rs | 6 +- cli/args/flags_allow_net.rs | 8 +- cli/args/import_map.rs | 2 +- cli/args/mod.rs | 12 +-- cli/auth_tokens.rs | 4 +- cli/bench/http.rs | 8 +- cli/bench/lsp.rs | 6 +- cli/bench/lsp_bench_standalone.rs | 2 +- cli/bench/main.rs | 14 +-- cli/build.rs | 6 +- cli/cache/check.rs | 6 +- cli/cache/disk_cache.rs | 7 +- cli/cache/emit.rs | 2 +- cli/cache/http_cache.rs | 7 +- cli/cache/incremental.rs | 2 +- cli/cache/node.rs | 4 +- cli/errors.rs | 4 +- cli/file_fetcher.rs | 32 +++---- cli/graph_util.rs | 9 +- cli/http_util.rs | 5 +- cli/lsp/analysis.rs | 12 +-- cli/lsp/client.rs | 2 +- cli/lsp/completions.rs | 2 +- cli/lsp/diagnostics.rs | 17 ++-- cli/lsp/documents.rs | 6 +- cli/lsp/language_server.rs | 7 +- cli/lsp/path_to_regex.rs | 34 ++++--- cli/lsp/registries.rs | 14 +-- cli/lsp/repl.rs | 2 +- cli/lsp/tsc.rs | 23 +++-- cli/lsp/urls.rs | 6 +- cli/main.rs | 4 +- cli/module_loader.rs | 4 +- cli/napi/async.rs | 2 +- cli/napi/env.rs | 8 +- cli/node/analyze.rs | 4 +- cli/node/mod.rs | 29 +++--- cli/npm/cache.rs | 2 +- cli/npm/registry.rs | 16 +--- cli/npm/resolution/mod.rs | 4 +- cli/npm/resolution/snapshot.rs | 2 +- cli/npm/resolution/specifier.rs | 12 +-- cli/npm/resolvers/mod.rs | 5 +- cli/npm/semver/mod.rs | 18 ++-- cli/npm/semver/specifier.rs | 4 +- cli/npm/tarball.rs | 4 +- cli/proc_state.rs | 8 +- cli/standalone.rs | 4 +- cli/tests/integration/coverage_tests.rs | 37 ++++---- cli/tests/integration/fmt_tests.rs | 3 +- cli/tests/integration/inspector_tests.rs | 7 +- cli/tests/integration/lsp_tests.rs | 2 +- cli/tests/integration/repl_tests.rs | 2 +- cli/tests/integration/run_tests.rs | 21 ++--- cli/tests/integration/vendor_tests.rs | 4 +- cli/tests/integration/watcher_tests.rs | 4 +- cli/tools/coverage/mod.rs | 16 ++-- cli/tools/doc.rs | 2 +- cli/tools/fmt.rs | 13 ++- cli/tools/info.rs | 5 +- cli/tools/init/mod.rs | 2 +- cli/tools/installer.rs | 28 +++--- cli/tools/lint.rs | 12 +-- cli/tools/repl/editor.rs | 5 +- cli/tools/repl/mod.rs | 13 +-- cli/tools/repl/session.rs | 5 +- cli/tools/standalone.rs | 6 +- cli/tools/task.rs | 6 +- cli/tools/test.rs | 8 +- cli/tools/upgrade.rs | 4 +- cli/tools/vendor/build.rs | 10 +- cli/tools/vendor/import_map.rs | 2 +- cli/tools/vendor/mappings.rs | 6 +- cli/tools/vendor/specifiers.rs | 2 +- cli/tsc/diagnostics.rs | 8 +- cli/tsc/mod.rs | 6 +- cli/util/checksum.rs | 2 +- cli/util/display.rs | 8 +- cli/util/file_watcher.rs | 4 +- cli/util/fs.rs | 22 ++--- cli/util/path.rs | 15 ++- cli/util/progress_bar/renderer.rs | 2 +- cli/util/text_encoding.rs | 2 +- cli/util/v8.rs | 2 +- cli/worker.rs | 8 +- core/async_cell.rs | 4 +- core/bindings.rs | 3 +- core/error.rs | 24 ++--- core/examples/eval_js_value.rs | 6 +- core/examples/fs_module_loader.rs | 2 +- core/examples/schedule_task.rs | 2 +- core/examples/ts_module_loader.rs | 2 +- core/module_specifier.rs | 10 +- core/modules.rs | 14 ++- core/ops.rs | 2 +- core/ops_builtin_v8.rs | 6 +- core/runtime.rs | 20 ++-- ext/fetch/lib.rs | 9 +- ext/ffi/dlfcn.rs | 6 +- ext/ffi/lib.rs | 3 +- ext/flash/lib.rs | 7 +- ext/http/lib.rs | 4 +- ext/net/lib.rs | 3 +- ext/net/ops.rs | 2 +- ext/net/ops_unix.rs | 2 +- ext/node/errors.rs | 47 ++++------ ext/node/lib.rs | 6 +- ext/node/resolution.rs | 8 +- ext/web/blob.rs | 2 +- ext/web/lib.rs | 9 +- ext/webgpu/src/lib.rs | 3 +- ext/websocket/lib.rs | 5 +- lockfile/lib.rs | 2 +- ops/fast_call.rs | 4 +- ops/optimizer.rs | 6 +- runtime/build.rs | 5 +- runtime/fmt_errors.rs | 12 +-- runtime/inspector_server.rs | 6 +- runtime/ops/fs.rs | 6 +- runtime/ops/mod.rs | 3 +- runtime/ops/os/mod.rs | 16 +--- runtime/ops/permissions.rs | 8 +- runtime/ops/process.rs | 2 +- runtime/ops/signal.rs | 7 +- runtime/ops/utils.rs | 2 +- runtime/ops/web_worker/sync_fetch.rs | 6 +- runtime/ops/worker_host.rs | 3 +- runtime/permissions/mod.rs | 47 +++++----- runtime/permissions/prompter.rs | 18 ++-- runtime/worker_bootstrap.rs | 2 +- rust-toolchain.toml | 2 +- serde_v8/benches/de.rs | 2 +- serde_v8/error.rs | 2 +- serde_v8/examples/basic.rs | 8 +- serde_v8/tests/de.rs | 2 +- serde_v8/tests/ser.rs | 2 +- test_ffi/src/lib.rs | 10 +- test_ffi/tests/integration_tests.rs | 16 ++-- test_napi/src/properties.rs | 4 +- test_napi/tests/napi_tests.rs | 4 +- test_util/src/lib.rs | 113 +++++++++++------------ test_util/src/lsp.rs | 4 +- test_util/src/npm.rs | 5 +- test_util/src/pty.rs | 4 +- 148 files changed, 576 insertions(+), 681 deletions(-) diff --git a/.github/workflows/ci.generate.ts b/.github/workflows/ci.generate.ts index 8fddc3cc8e8d89..a3f915180de98b 100644 --- a/.github/workflows/ci.generate.ts +++ b/.github/workflows/ci.generate.ts @@ -438,7 +438,7 @@ const ci = { ].join("\n"), key: "never_saved", "restore-keys": - "18-cargo-target-${{ matrix.os }}-${{ matrix.profile }}-", + "19-cargo-target-${{ matrix.os }}-${{ matrix.profile }}-", }, }, { diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 12374bb6afc6d8..242e8d711de168 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -266,7 +266,7 @@ jobs: !./target/*/*.zip !./target/*/*.tar.gz key: never_saved - restore-keys: '18-cargo-target-${{ matrix.os }}-${{ matrix.profile }}-' + restore-keys: '19-cargo-target-${{ matrix.os }}-${{ matrix.profile }}-' - name: Apply and update mtime cache if: '!(github.event_name == ''pull_request'' && matrix.skip_pr) && (steps.exit_early.outputs.EXIT_EARLY != ''true'' && (!startsWith(github.ref, ''refs/tags/'')))' uses: ./.github/mtime_cache diff --git a/bench_util/js_runtime.rs b/bench_util/js_runtime.rs index 81cc84155ec187..7868c433ab4152 100644 --- a/bench_util/js_runtime.rs +++ b/bench_util/js_runtime.rs @@ -15,7 +15,7 @@ pub fn create_js_runtime(setup: impl FnOnce() -> Vec) -> JsRuntime { } fn loop_code(iters: u64, src: &str) -> String { - format!(r#"for(let i=0; i < {}; i++) {{ {} }}"#, iters, src,) + format!(r#"for(let i=0; i < {iters}; i++) {{ {src} }}"#,) } #[derive(Copy, Clone)] diff --git a/cli/args/config_file.rs b/cli/args/config_file.rs index 82ae7e5d758513..ad204f44953029 100644 --- a/cli/args/config_file.rs +++ b/cli/args/config_file.rs @@ -163,7 +163,7 @@ pub const IGNORED_COMPILER_OPTIONS: &[&str] = &[ /// A function that works like JavaScript's `Object.assign()`. pub fn json_merge(a: &mut Value, b: &Value) { match (a, b) { - (&mut Value::Object(ref mut a), &Value::Object(ref b)) => { + (&mut Value::Object(ref mut a), Value::Object(b)) => { for (k, v) in b { json_merge(a.entry(k.clone()).or_insert(Value::Null), v); } diff --git a/cli/args/flags.rs b/cli/args/flags.rs index 00df45274d5a95..257a99eb52e738 100644 --- a/cli/args/flags.rs +++ b/cli/args/flags.rs @@ -1904,7 +1904,7 @@ fn permission_args(app: Command) -> Command { .validator(|keys| { for key in keys.split(',') { if key.is_empty() || key.contains(&['=', '\0'] as &[char]) { - return Err(format!("invalid key \"{}\"", key)); + return Err(format!("invalid key \"{key}\"")); } } Ok(()) @@ -3164,7 +3164,7 @@ fn seed_arg_parse(flags: &mut Flags, matches: &ArgMatches) { let seed = seed_string.parse::().unwrap(); flags.seed = Some(seed); - flags.v8_flags.push(format!("--random-seed={}", seed)); + flags.v8_flags.push(format!("--random-seed={seed}")); } } @@ -3293,7 +3293,7 @@ pub fn resolve_urls(urls: Vec) -> Vec { } out.push(full_url); } else { - panic!("Bad Url: {}", urlstr); + panic!("Bad Url: {urlstr}"); } } out diff --git a/cli/args/flags_allow_net.rs b/cli/args/flags_allow_net.rs index bf189132a011e4..88d9d3c027b0a4 100644 --- a/cli/args/flags_allow_net.rs +++ b/cli/args/flags_allow_net.rs @@ -27,13 +27,13 @@ impl FromStr for BarePort { } pub fn validator(host_and_port: &str) -> Result<(), String> { - if Url::parse(&format!("deno://{}", host_and_port)).is_ok() + if Url::parse(&format!("deno://{host_and_port}")).is_ok() || host_and_port.parse::().is_ok() || host_and_port.parse::().is_ok() { Ok(()) } else { - Err(format!("Bad host:port pair: {}", host_and_port)) + Err(format!("Bad host:port pair: {host_and_port}")) } } @@ -43,7 +43,7 @@ pub fn validator(host_and_port: &str) -> Result<(), String> { pub fn parse(paths: Vec) -> clap::Result> { let mut out: Vec = vec![]; for host_and_port in paths.iter() { - if Url::parse(&format!("deno://{}", host_and_port)).is_ok() + if Url::parse(&format!("deno://{host_and_port}")).is_ok() || host_and_port.parse::().is_ok() { out.push(host_and_port.to_owned()) @@ -55,7 +55,7 @@ pub fn parse(paths: Vec) -> clap::Result> { } else { return Err(clap::Error::raw( clap::ErrorKind::InvalidValue, - format!("Bad host:port pair: {}", host_and_port), + format!("Bad host:port pair: {host_and_port}"), )); } } diff --git a/cli/args/import_map.rs b/cli/args/import_map.rs index bac31c080e418e..9d1b2bbda0943b 100644 --- a/cli/args/import_map.rs +++ b/cli/args/import_map.rs @@ -56,7 +56,7 @@ fn print_import_map_diagnostics(diagnostics: &[ImportMapDiagnostic]) { "Import map diagnostics:\n{}", diagnostics .iter() - .map(|d| format!(" - {}", d)) + .map(|d| format!(" - {d}")) .collect::>() .join("\n") ); diff --git a/cli/args/mod.rs b/cli/args/mod.rs index 5cb29cab215059..d75f25d525831a 100644 --- a/cli/args/mod.rs +++ b/cli/args/mod.rs @@ -90,7 +90,7 @@ impl CacheSetting { if list.iter().any(|i| i == "npm:") { return false; } - let specifier = format!("npm:{}", package_name); + let specifier = format!("npm:{package_name}"); if list.contains(&specifier) { return false; } @@ -491,7 +491,7 @@ impl CliOptions { format!("for: {}", insecure_allowlist.join(", ")) }; let msg = - format!("DANGER: TLS certificate validation is disabled {}", domains); + format!("DANGER: TLS certificate validation is disabled {domains}"); // use eprintln instead of log::warn so this always gets shown eprintln!("{}", colors::yellow(msg)); } @@ -579,8 +579,7 @@ impl CliOptions { ) .await .context(format!( - "Unable to load '{}' import map", - import_map_specifier + "Unable to load '{import_map_specifier}' import map" )) .map(Some) } @@ -929,7 +928,7 @@ fn resolve_import_map_specifier( } } let specifier = deno_core::resolve_url_or_path(import_map_path) - .context(format!("Bad URL (\"{}\") for import map.", import_map_path))?; + .context(format!("Bad URL (\"{import_map_path}\") for import map."))?; return Ok(Some(specifier)); } else if let Some(config_file) = &maybe_config_file { // if the config file is an import map we prefer to use it, over `importMap` @@ -970,8 +969,7 @@ fn resolve_import_map_specifier( } else { deno_core::resolve_import(&import_map_path, config_file.specifier.as_str()) .context(format!( - "Bad URL (\"{}\") for import map.", - import_map_path + "Bad URL (\"{import_map_path}\") for import map." ))? }; return Ok(Some(specifier)); diff --git a/cli/auth_tokens.rs b/cli/auth_tokens.rs index 360a7e6c7ff43b..6c3ed3846aab49 100644 --- a/cli/auth_tokens.rs +++ b/cli/auth_tokens.rs @@ -20,9 +20,9 @@ pub struct AuthToken { impl fmt::Display for AuthToken { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match &self.token { - AuthTokenData::Bearer(token) => write!(f, "Bearer {}", token), + AuthTokenData::Bearer(token) => write!(f, "Bearer {token}"), AuthTokenData::Basic { username, password } => { - let credentials = format!("{}:{}", username, password); + let credentials = format!("{username}:{password}"); write!(f, "Basic {}", base64::encode(credentials)) } } diff --git a/cli/bench/http.rs b/cli/bench/http.rs index 585574e2dcafa8..06a1773864966d 100644 --- a/cli/bench/http.rs +++ b/cli/bench/http.rs @@ -44,7 +44,7 @@ pub fn benchmark( let name = entry.file_name().into_string().unwrap(); let file_stem = pathbuf.file_stem().unwrap().to_str().unwrap(); - let lua_script = http_dir.join(format!("{}.lua", file_stem)); + let lua_script = http_dir.join(format!("{file_stem}.lua")); let mut maybe_lua = None; if lua_script.exists() { maybe_lua = Some(lua_script.to_str().unwrap()); @@ -158,7 +158,7 @@ fn run( let wrk = test_util::prebuilt_tool_path("wrk"); assert!(wrk.is_file()); - let addr = format!("http://127.0.0.1:{}/", port); + let addr = format!("http://127.0.0.1:{port}/"); let mut wrk_cmd = vec![wrk.to_str().unwrap(), "-d", DURATION, "--latency", &addr]; @@ -172,7 +172,7 @@ fn run( std::thread::sleep(Duration::from_secs(1)); // wait to capture failure. TODO racy. - println!("{}", output); + println!("{output}"); assert!( server.try_wait()?.map_or(true, |s| s.success()), "server ended with error" @@ -194,7 +194,7 @@ fn get_port() -> u16 { } fn server_addr(port: u16) -> String { - format!("0.0.0.0:{}", port) + format!("0.0.0.0:{port}") } fn core_http_json_ops(exe: &str) -> Result { diff --git a/cli/bench/lsp.rs b/cli/bench/lsp.rs index fe6fd2703d2d60..722a87b69bf9aa 100644 --- a/cli/bench/lsp.rs +++ b/cli/bench/lsp.rs @@ -202,7 +202,7 @@ fn bench_find_replace(deno_exe: &Path) -> Result { "textDocument/didOpen", json!({ "textDocument": { - "uri": format!("file:///a/file_{}.ts", i), + "uri": format!("file:///a/file_{i}.ts"), "languageId": "typescript", "version": 1, "text": "console.log(\"000\");\n" @@ -223,7 +223,7 @@ fn bench_find_replace(deno_exe: &Path) -> Result { } for i in 0..10 { - let file_name = format!("file:///a/file_{}.ts", i); + let file_name = format!("file:///a/file_{i}.ts"); client.write_notification( "textDocument/didChange", lsp::DidChangeTextDocumentParams { @@ -250,7 +250,7 @@ fn bench_find_replace(deno_exe: &Path) -> Result { } for i in 0..10 { - let file_name = format!("file:///a/file_{}.ts", i); + let file_name = format!("file:///a/file_{i}.ts"); let (maybe_res, maybe_err) = client.write_request::<_, _, Value>( "textDocument/formatting", lsp::DocumentFormattingParams { diff --git a/cli/bench/lsp_bench_standalone.rs b/cli/bench/lsp_bench_standalone.rs index 080f25e73499d4..e8dc2907309701 100644 --- a/cli/bench/lsp_bench_standalone.rs +++ b/cli/bench/lsp_bench_standalone.rs @@ -55,7 +55,7 @@ fn incremental_change_wait(bench: &mut Bencher) { let mut document_version: u64 = 0; bench.iter(|| { - let text = format!("m{:05}", document_version); + let text = format!("m{document_version:05}"); client .write_notification( "textDocument/didChange", diff --git a/cli/bench/main.rs b/cli/bench/main.rs index e6b9895f240b69..74740794511a39 100644 --- a/cli/bench/main.rs +++ b/cli/bench/main.rs @@ -189,7 +189,7 @@ fn run_exec_time( let ret_code_test = if let Some(code) = return_code { // Bash test which asserts the return code value of the previous command // $? contains the return code of the previous command - format!("; test $? -eq {}", code) + format!("; test $? -eq {code}") } else { "".to_string() }; @@ -244,11 +244,11 @@ fn rlib_size(target_dir: &std::path::Path, prefix: &str) -> i64 { if name.starts_with(prefix) && name.ends_with(".rlib") { let start = name.split('-').next().unwrap().to_string(); if seen.contains(&start) { - println!("skip {}", name); + println!("skip {name}"); } else { seen.insert(start); size += entry.metadata().unwrap().len(); - println!("check size {} {}", name, size); + println!("check size {name} {size}"); } } } @@ -269,11 +269,11 @@ fn get_binary_sizes(target_dir: &Path) -> Result> { // add up size for everything in target/release/deps/libswc* let swc_size = rlib_size(target_dir, "libswc"); - println!("swc {} bytes", swc_size); + println!("swc {swc_size} bytes"); sizes.insert("swc_rlib".to_string(), swc_size); let v8_size = rlib_size(target_dir, "libv8"); - println!("v8 {} bytes", v8_size); + println!("v8 {v8_size} bytes"); sizes.insert("rusty_v8_rlib".to_string(), v8_size); // Because cargo's OUT_DIR is not predictable, search the build tree for @@ -314,7 +314,7 @@ fn bundle_benchmark(deno_exe: &Path) -> Result> { let mut sizes = HashMap::::new(); for (name, url) in BUNDLES { - let path = format!("{}.bundle.js", name); + let path = format!("{name}.bundle.js"); test_util::run( &[ deno_exe.to_str().unwrap(), @@ -374,7 +374,7 @@ fn cargo_deps() -> usize { count += 1 } } - println!("cargo_deps {}", count); + println!("cargo_deps {count}"); assert!(count > 10); // Sanity check. count } diff --git a/cli/build.rs b/cli/build.rs index 131d404a7dc805..bb048d0d42bcbe 100644 --- a/cli/build.rs +++ b/cli/build.rs @@ -130,7 +130,7 @@ mod ts { for name in libs.iter() { println!( "cargo:rerun-if-changed={}", - path_dts.join(format!("lib.{}.d.ts", name)).display() + path_dts.join(format!("lib.{name}.d.ts")).display() ); } println!( @@ -229,7 +229,7 @@ mod ts { PathBuf::from(op_crate_lib).canonicalize()? // otherwise we are will generate the path ourself } else { - path_dts.join(format!("lib.{}.d.ts", lib)) + path_dts.join(format!("lib.{lib}.d.ts")) }; let data = std::fs::read_to_string(path)?; Ok(json!({ @@ -431,7 +431,7 @@ fn main() { // op_fetch_asset::trace_serializer(); if let Ok(c) = env::var("DENO_CANARY") { - println!("cargo:rustc-env=DENO_CANARY={}", c); + println!("cargo:rustc-env=DENO_CANARY={c}"); } println!("cargo:rerun-if-env-changed=DENO_CANARY"); diff --git a/cli/cache/check.rs b/cli/cache/check.rs index 86fb075776d76b..c991c14b190cdc 100644 --- a/cli/cache/check.rs +++ b/cli/cache/check.rs @@ -71,7 +71,7 @@ impl TypeCheckCache { Ok(val) => val, Err(err) => { if cfg!(debug_assertions) { - panic!("Error retrieving hash: {}", err); + panic!("Error retrieving hash: {err}"); } else { log::debug!("Error retrieving hash: {}", err); // fail silently when not debugging @@ -94,7 +94,7 @@ impl TypeCheckCache { pub fn add_check_hash(&self, check_hash: u64) { if let Err(err) = self.add_check_hash_result(check_hash) { if cfg!(debug_assertions) { - panic!("Error saving check hash: {}", err); + panic!("Error saving check hash: {err}"); } else { log::debug!("Error saving check hash: {}", err); } @@ -134,7 +134,7 @@ impl TypeCheckCache { if let Err(err) = self.set_tsbuildinfo_result(specifier, text) { // should never error here, but if it ever does don't fail if cfg!(debug_assertions) { - panic!("Error saving tsbuildinfo: {}", err); + panic!("Error saving tsbuildinfo: {err}"); } else { log::debug!("Error saving tsbuildinfo: {}", err); } diff --git a/cli/cache/disk_cache.rs b/cli/cache/disk_cache.rs index b97850204130f1..799610d5f4a7c9 100644 --- a/cli/cache/disk_cache.rs +++ b/cli/cache/disk_cache.rs @@ -43,8 +43,7 @@ impl DiskCache { } fs::create_dir_all(path).map_err(|e| { io::Error::new(e.kind(), format!( - "Could not create TypeScript compiler cache location: {:?}\nCheck the permission of the directory.", - path + "Could not create TypeScript compiler cache location: {path:?}\nCheck the permission of the directory." )) }) } @@ -61,7 +60,7 @@ impl DiskCache { let host_port = match url.port() { // Windows doesn't support ":" in filenames, so we represent port using a // special string. - Some(port) => format!("{}_PORT{}", host, port), + Some(port) => format!("{host}_PORT{port}"), None => host.to_string(), }; out.push(host_port); @@ -128,7 +127,7 @@ impl DiskCache { None => Some(base.with_extension(extension)), Some(ext) => { let original_extension = OsStr::to_str(ext).unwrap(); - let final_extension = format!("{}.{}", original_extension, extension); + let final_extension = format!("{original_extension}.{extension}"); Some(base.with_extension(final_extension)) } } diff --git a/cli/cache/emit.rs b/cli/cache/emit.rs index 21f382c55c4e65..89ff496fdd3101 100644 --- a/cli/cache/emit.rs +++ b/cli/cache/emit.rs @@ -90,7 +90,7 @@ impl EmitCache { if let Err(err) = self.set_emit_code_result(specifier, source_hash, code) { // should never error here, but if it ever does don't fail if cfg!(debug_assertions) { - panic!("Error saving emit data ({}): {}", specifier, err); + panic!("Error saving emit data ({specifier}): {err}"); } else { log::debug!("Error saving emit data({}): {}", specifier, err); } diff --git a/cli/cache/http_cache.rs b/cli/cache/http_cache.rs index 4be3166c900e5a..2e784765e2e570 100644 --- a/cli/cache/http_cache.rs +++ b/cli/cache/http_cache.rs @@ -35,7 +35,7 @@ fn base_url_to_filename(url: &Url) -> Option { "http" | "https" => { let host = url.host_str().unwrap(); let host_port = match url.port() { - Some(port) => format!("{}_PORT{}", host, port), + Some(port) => format!("{host}_PORT{port}"), None => host.to_string(), }; out.push(host_port); @@ -128,8 +128,7 @@ impl HttpCache { io::Error::new( e.kind(), format!( - "Could not create remote modules cache location: {:?}\nCheck the permission of the directory.", - path + "Could not create remote modules cache location: {path:?}\nCheck the permission of the directory." ), ) }) @@ -231,7 +230,7 @@ mod tests { headers.insert("etag".to_string(), "as5625rqdsfb".to_string()); let content = b"Hello world"; let r = cache.set(&url, headers, content); - eprintln!("result {:?}", r); + eprintln!("result {r:?}"); assert!(r.is_ok()); let r = cache.get(&url); assert!(r.is_ok()); diff --git a/cli/cache/incremental.rs b/cli/cache/incremental.rs index 652965ad77a0f2..985181c5938baa 100644 --- a/cli/cache/incremental.rs +++ b/cli/cache/incremental.rs @@ -185,7 +185,7 @@ impl SqlIncrementalCache { Ok(option) => option, Err(err) => { if cfg!(debug_assertions) { - panic!("Error retrieving hash: {}", err); + panic!("Error retrieving hash: {err}"); } else { // fail silently when not debugging None diff --git a/cli/cache/node.rs b/cli/cache/node.rs index ec0121c6163283..b1977222911a72 100644 --- a/cli/cache/node.rs +++ b/cli/cache/node.rs @@ -108,7 +108,7 @@ impl NodeAnalysisCache { Err(err) => { // should never error here, but if it ever does don't fail if cfg!(debug_assertions) { - panic!("Error creating node analysis cache: {:#}", err); + panic!("Error creating node analysis cache: {err:#}"); } else { log::debug!("Error creating node analysis cache: {:#}", err); None @@ -124,7 +124,7 @@ impl NodeAnalysisCache { Err(err) => { // should never error here, but if it ever does don't fail if cfg!(debug_assertions) { - panic!("Error using esm analysis: {:#}", err); + panic!("Error using esm analysis: {err:#}"); } else { log::debug!("Error using esm analysis: {:#}", err); } diff --git a/cli/errors.rs b/cli/errors.rs index 5259b90fba895e..823d32da5833af 100644 --- a/cli/errors.rs +++ b/cli/errors.rs @@ -65,9 +65,7 @@ pub fn get_error_class_name(e: &AnyError) -> &'static str { eprintln!( "Error '{}' contains boxed error of unknown type:{}", e, - e.chain() - .map(|e| format!("\n {:?}", e)) - .collect::() + e.chain().map(|e| format!("\n {e:?}")).collect::() ); "Error" }) diff --git a/cli/file_fetcher.rs b/cli/file_fetcher.rs index 4e417778e539f5..f287209640a211 100644 --- a/cli/file_fetcher.rs +++ b/cli/file_fetcher.rs @@ -88,7 +88,7 @@ impl FileCache { /// Fetch a source file from the local file system. fn fetch_local(specifier: &ModuleSpecifier) -> Result { let local = specifier.to_file_path().map_err(|_| { - uri_error(format!("Invalid file path.\n Specifier: {}", specifier)) + uri_error(format!("Invalid file path.\n Specifier: {specifier}")) })?; let bytes = fs::read(&local)?; let charset = text_encoding::detect_charset(&bytes).to_string(); @@ -111,13 +111,13 @@ pub fn get_source_from_data_url( specifier: &ModuleSpecifier, ) -> Result<(String, String), AnyError> { let data_url = DataUrl::process(specifier.as_str()) - .map_err(|e| uri_error(format!("{:?}", e)))?; + .map_err(|e| uri_error(format!("{e:?}")))?; let mime = data_url.mime_type(); let charset = mime.get_parameter("charset").map(|v| v.to_string()); let (bytes, _) = data_url .decode_to_vec() - .map_err(|e| uri_error(format!("{:?}", e)))?; - Ok((get_source_from_bytes(bytes, charset)?, format!("{}", mime))) + .map_err(|e| uri_error(format!("{e:?}")))?; + Ok((get_source_from_bytes(bytes, charset)?, format!("{mime}"))) } /// Given a vector of bytes and optionally a charset, decode the bytes to a @@ -142,8 +142,7 @@ fn get_validated_scheme( let scheme = specifier.scheme(); if !SUPPORTED_SCHEMES.contains(&scheme) { Err(generic_error(format!( - "Unsupported scheme \"{}\" for module \"{}\". Supported schemes: {:#?}", - scheme, specifier, SUPPORTED_SCHEMES + "Unsupported scheme \"{scheme}\" for module \"{specifier}\". Supported schemes: {SUPPORTED_SCHEMES:#?}" ))) } else { Ok(scheme.to_string()) @@ -301,8 +300,7 @@ impl FileFetcher { return Err(custom_error( "NotCached", format!( - "Specifier not found in cache: \"{}\", --cached-only is specified.", - specifier + "Specifier not found in cache: \"{specifier}\", --cached-only is specified." ), )); } @@ -349,8 +347,7 @@ impl FileFetcher { return Err(custom_error( "NotCached", format!( - "Specifier not found in cache: \"{}\", --cached-only is specified.", - specifier + "Specifier not found in cache: \"{specifier}\", --cached-only is specified." ), )); } @@ -362,7 +359,7 @@ impl FileFetcher { .ok_or_else(|| { custom_error( "NotFound", - format!("Blob URL not found: \"{}\".", specifier), + format!("Blob URL not found: \"{specifier}\"."), ) })? }; @@ -435,8 +432,7 @@ impl FileFetcher { return futures::future::err(custom_error( "NotCached", format!( - "Specifier not found in cache: \"{}\", --cached-only is specified.", - specifier + "Specifier not found in cache: \"{specifier}\", --cached-only is specified." ), )) .boxed(); @@ -580,7 +576,7 @@ impl FileFetcher { } else if !self.allow_remote { Err(custom_error( "NoRemote", - format!("A remote specifier was requested: \"{}\", but --no-remote is specified.", specifier), + format!("A remote specifier was requested: \"{specifier}\", but --no-remote is specified."), )) } else { let result = self @@ -818,19 +814,19 @@ mod tests { charset: &str, expected: &str, ) { - let url_str = format!("http://127.0.0.1:4545/encoding/{}", fixture); + let url_str = format!("http://127.0.0.1:4545/encoding/{fixture}"); let specifier = resolve_url(&url_str).unwrap(); let (file, headers) = test_fetch_remote(&specifier).await; assert_eq!(&*file.source, expected); assert_eq!(file.media_type, MediaType::TypeScript); assert_eq!( headers.get("content-type").unwrap(), - &format!("application/typescript;charset={}", charset) + &format!("application/typescript;charset={charset}") ); } async fn test_fetch_local_encoded(charset: &str, expected: String) { - let p = test_util::testdata_path().join(format!("encoding/{}.ts", charset)); + let p = test_util::testdata_path().join(format!("encoding/{charset}.ts")); let specifier = resolve_url_or_path(p.to_str().unwrap()).unwrap(); let (file, _) = test_fetch(&specifier).await; assert_eq!(&*file.source, expected); @@ -2016,7 +2012,7 @@ mod tests { ) .await; - println!("{:?}", result); + println!("{result:?}"); if let Ok(FetchOnceResult::Code(body, _headers)) = result { assert!(!body.is_empty()); } else { diff --git a/cli/graph_util.rs b/cli/graph_util.rs index 3cf3b0d0b0851b..c216ba50332b5c 100644 --- a/cli/graph_util.rs +++ b/cli/graph_util.rs @@ -630,12 +630,12 @@ fn handle_check_error( let mut message = if let Some(err) = error.downcast_ref::() { enhanced_resolution_error_message(err) } else { - format!("{}", error) + format!("{error}") }; if let Some(range) = maybe_range { if !range.specifier.as_str().contains("$deno") { - message.push_str(&format!("\n at {}", range)); + message.push_str(&format!("\n at {range}")); } } @@ -644,7 +644,7 @@ fn handle_check_error( /// Adds more explanatory information to a resolution error. pub fn enhanced_resolution_error_message(error: &ResolutionError) -> String { - let mut message = format!("{}", error); + let mut message = format!("{error}"); if let ResolutionError::InvalidSpecifier { error: SpecifierError::ImportPrefixMissing(specifier, _), @@ -653,8 +653,7 @@ pub fn enhanced_resolution_error_message(error: &ResolutionError) -> String { { if crate::node::resolve_builtin_node_module(specifier).is_ok() { message.push_str(&format!( - "\nIf you want to use a built-in Node module, add a \"node:\" prefix (ex. \"node:{}\").", - specifier + "\nIf you want to use a built-in Node module, add a \"node:\" prefix (ex. \"node:{specifier}\")." )); } } diff --git a/cli/http_util.rs b/cli/http_util.rs index 52d0cb66400570..225c49996b9321 100644 --- a/cli/http_util.rs +++ b/cli/http_util.rs @@ -59,8 +59,7 @@ pub fn resolve_redirect_from_response( Ok(new_url) } else { Err(generic_error(format!( - "Redirection from '{}' did not provide location header", - request_url + "Redirection from '{request_url}' did not provide location header" ))) } } @@ -290,7 +289,7 @@ impl HttpClient { "Bad response: {:?}{}", status, match maybe_response_text { - Some(text) => format!("\n\n{}", text), + Some(text) => format!("\n\n{text}"), None => String::new(), } ); diff --git a/cli/lsp/analysis.rs b/cli/lsp/analysis.rs index c7f5ba8aae6d8e..182ad940e63b7d 100644 --- a/cli/lsp/analysis.rs +++ b/cli/lsp/analysis.rs @@ -158,7 +158,7 @@ fn check_specifier( documents: &Documents, ) -> Option { for ext in SUPPORTED_EXTENSIONS { - let specifier_with_ext = format!("{}{}", specifier, ext); + let specifier_with_ext = format!("{specifier}{ext}"); if documents.contains_import(&specifier_with_ext, referrer) { return Some(specifier_with_ext); } @@ -398,7 +398,7 @@ impl CodeActionCollection { specifier.clone(), vec![lsp::TextEdit { new_text: prepend_whitespace( - format!("// deno-lint-ignore {}\n", code), + format!("// deno-lint-ignore {code}\n"), line_content, ), range: lsp::Range { @@ -414,7 +414,7 @@ impl CodeActionCollection { }], ); let ignore_error_action = lsp::CodeAction { - title: format!("Disable {} for this line", code), + title: format!("Disable {code} for this line"), kind: Some(lsp::CodeActionKind::QUICKFIX), diagnostics: Some(vec![diagnostic.clone()]), command: None, @@ -447,7 +447,7 @@ impl CodeActionCollection { }) }); - let mut new_text = format!("// deno-lint-ignore-file {}\n", code); + let mut new_text = format!("// deno-lint-ignore-file {code}\n"); let mut range = lsp::Range { start: lsp::Position { line: 0, @@ -461,7 +461,7 @@ impl CodeActionCollection { // If ignore file comment already exists, append the lint code // to the existing comment. if let Some(ignore_comment) = maybe_ignore_comment { - new_text = format!(" {}", code); + new_text = format!(" {code}"); // Get the end position of the comment. let line = maybe_parsed_source .unwrap() @@ -479,7 +479,7 @@ impl CodeActionCollection { let mut changes = HashMap::new(); changes.insert(specifier.clone(), vec![lsp::TextEdit { new_text, range }]); let ignore_file_action = lsp::CodeAction { - title: format!("Disable {} for the entire file", code), + title: format!("Disable {code} for the entire file"), kind: Some(lsp::CodeActionKind::QUICKFIX), diagnostics: Some(vec![diagnostic.clone()]), command: None, diff --git a/cli/lsp/client.rs b/cli/lsp/client.rs index b39678667f8ad1..cdef1cfbf5662d 100644 --- a/cli/lsp/client.rs +++ b/cli/lsp/client.rs @@ -107,7 +107,7 @@ impl Client { ) { self .0 - .show_message(message_type, format!("{}", message)) + .show_message(message_type, format!("{message}")) .await } diff --git a/cli/lsp/completions.rs b/cli/lsp/completions.rs index a8e7896c544c7c..b89aec6c982396 100644 --- a/cli/lsp/completions.rs +++ b/cli/lsp/completions.rs @@ -394,7 +394,7 @@ fn get_local_completions( let filter_text = if full_text.starts_with(current) { Some(full_text) } else { - Some(format!("{}{}", current, label)) + Some(format!("{current}{label}")) }; match de.file_type() { Ok(file_type) if file_type.is_dir() => Some(lsp::CompletionItem { diff --git a/cli/lsp/diagnostics.rs b/cli/lsp/diagnostics.rs index 9f3c409ccb9012..b6dff86827c94b 100644 --- a/cli/lsp/diagnostics.rs +++ b/cli/lsp/diagnostics.rs @@ -670,17 +670,14 @@ impl DenoDiagnostic { let DiagnosticDataImportMapRemap { from, to } = serde_json::from_value(data)?; lsp::CodeAction { - title: format!( - "Update \"{}\" to \"{}\" to use import map.", - from, to - ), + title: format!("Update \"{from}\" to \"{to}\" to use import map."), kind: Some(lsp::CodeActionKind::QUICKFIX), diagnostics: Some(vec![diagnostic.clone()]), edit: Some(lsp::WorkspaceEdit { changes: Some(HashMap::from([( specifier.clone(), vec![lsp::TextEdit { - new_text: format!("\"{}\"", to), + new_text: format!("\"{to}\""), range: diagnostic.range, }], )])), @@ -821,15 +818,15 @@ impl DenoDiagnostic { pub fn to_lsp_diagnostic(&self, range: &lsp::Range) -> lsp::Diagnostic { let (severity, message, data) = match self { Self::DenoWarn(message) => (lsp::DiagnosticSeverity::WARNING, message.to_string(), None), - Self::ImportMapRemap { from, to } => (lsp::DiagnosticSeverity::HINT, format!("The import specifier can be remapped to \"{}\" which will resolve it via the active import map.", to), Some(json!({ "from": from, "to": to }))), - Self::InvalidAssertType(assert_type) => (lsp::DiagnosticSeverity::ERROR, format!("The module is a JSON module and expected an assertion type of \"json\". Instead got \"{}\".", assert_type), None), + Self::ImportMapRemap { from, to } => (lsp::DiagnosticSeverity::HINT, format!("The import specifier can be remapped to \"{to}\" which will resolve it via the active import map."), Some(json!({ "from": from, "to": to }))), + Self::InvalidAssertType(assert_type) => (lsp::DiagnosticSeverity::ERROR, format!("The module is a JSON module and expected an assertion type of \"json\". Instead got \"{assert_type}\"."), None), Self::NoAssertType => (lsp::DiagnosticSeverity::ERROR, "The module is a JSON module and not being imported with an import assertion. Consider adding `assert { type: \"json\" }` to the import statement.".to_string(), None), - Self::NoCache(specifier) => (lsp::DiagnosticSeverity::ERROR, format!("Uncached or missing remote URL: \"{}\".", specifier), Some(json!({ "specifier": specifier }))), + Self::NoCache(specifier) => (lsp::DiagnosticSeverity::ERROR, format!("Uncached or missing remote URL: \"{specifier}\"."), Some(json!({ "specifier": specifier }))), Self::NoCacheBlob => (lsp::DiagnosticSeverity::ERROR, "Uncached blob URL.".to_string(), None), Self::NoCacheData(specifier) => (lsp::DiagnosticSeverity::ERROR, "Uncached data URL.".to_string(), Some(json!({ "specifier": specifier }))), Self::NoCacheNpm(pkg_ref, specifier) => (lsp::DiagnosticSeverity::ERROR, format!("Uncached or missing npm package: \"{}\".", pkg_ref.req), Some(json!({ "specifier": specifier }))), - Self::NoLocal(specifier) => (lsp::DiagnosticSeverity::ERROR, format!("Unable to load a local module: \"{}\".\n Please check the file path.", specifier), None), - Self::Redirect { from, to} => (lsp::DiagnosticSeverity::INFORMATION, format!("The import of \"{}\" was redirected to \"{}\".", from, to), Some(json!({ "specifier": from, "redirect": to }))), + Self::NoLocal(specifier) => (lsp::DiagnosticSeverity::ERROR, format!("Unable to load a local module: \"{specifier}\".\n Please check the file path."), None), + Self::Redirect { from, to} => (lsp::DiagnosticSeverity::INFORMATION, format!("The import of \"{from}\" was redirected to \"{to}\"."), Some(json!({ "specifier": from, "redirect": to }))), Self::ResolutionError(err) => ( lsp::DiagnosticSeverity::ERROR, enhanced_resolution_error_message(err), diff --git a/cli/lsp/documents.rs b/cli/lsp/documents.rs index 03210ebaab9052..07003a1687b1fe 100644 --- a/cli/lsp/documents.rs +++ b/cli/lsp/documents.rs @@ -838,7 +838,7 @@ impl Documents { || { Err(custom_error( "NotFound", - format!("The specifier \"{}\" was not found.", specifier), + format!("The specifier \"{specifier}\" was not found."), )) }, Ok, @@ -862,7 +862,7 @@ impl Documents { } else { return Err(custom_error( "NotFound", - format!("The specifier \"{}\" was not found.", specifier), + format!("The specifier \"{specifier}\" was not found."), )); } } @@ -1100,7 +1100,7 @@ impl Documents { } else { return Err(custom_error( "NotFound", - format!("Specifier not found {}", specifier), + format!("Specifier not found {specifier}"), )); } } diff --git a/cli/lsp/language_server.rs b/cli/lsp/language_server.rs index 0b02115afb9064..58116d49e21c4b 100644 --- a/cli/lsp/language_server.rs +++ b/cli/lsp/language_server.rs @@ -375,8 +375,7 @@ impl Inner { self.get_maybe_asset_or_document(specifier).map_or_else( || { Err(LspError::invalid_params(format!( - "Unable to find asset or document for: {}", - specifier + "Unable to find asset or document for: {specifier}" ))) }, Ok, @@ -1296,7 +1295,7 @@ impl Inner { Ok(Some(text_edits)) } } else { - self.client.show_message(MessageType::WARNING, format!("Unable to format \"{}\". Likely due to unrecoverable syntax errors in the file.", specifier)).await; + self.client.show_message(MessageType::WARNING, format!("Unable to format \"{specifier}\". Likely due to unrecoverable syntax errors in the file.")).await; Ok(None) } } @@ -1354,7 +1353,7 @@ impl Inner { }; let value = if let Some(docs) = self.module_registries.get_hover(&dep).await { - format!("{}\n\n---\n\n{}", value, docs) + format!("{value}\n\n---\n\n{docs}") } else { value }; diff --git a/cli/lsp/path_to_regex.rs b/cli/lsp/path_to_regex.rs index a9b4bcdf37b335..1d766e02486fbf 100644 --- a/cli/lsp/path_to_regex.rs +++ b/cli/lsp/path_to_regex.rs @@ -220,8 +220,8 @@ pub enum StringOrNumber { impl fmt::Display for StringOrNumber { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match &self { - Self::Number(n) => write!(f, "{}", n), - Self::String(s) => write!(f, "{}", s), + Self::Number(n) => write!(f, "{n}"), + Self::String(s) => write!(f, "{s}"), } } } @@ -269,9 +269,9 @@ impl StringOrVec { let mut s = String::new(); for (i, segment) in v.iter().enumerate() { if omit_initial_prefix && i == 0 { - write!(s, "{}{}", segment, suffix).unwrap(); + write!(s, "{segment}{suffix}").unwrap(); } else { - write!(s, "{}{}{}", prefix, segment, suffix).unwrap(); + write!(s, "{prefix}{segment}{suffix}").unwrap(); } } s @@ -610,7 +610,7 @@ pub fn tokens_to_regex( } } else { let modifier = key.modifier.clone().unwrap_or_default(); - format!(r"(?:{}{}){}", prefix, suffix, modifier) + format!(r"(?:{prefix}{suffix}){modifier}") } } }; @@ -619,10 +619,10 @@ pub fn tokens_to_regex( if end { if !strict { - write!(route, r"{}?", delimiter).unwrap(); + write!(route, r"{delimiter}?").unwrap(); } if has_ends_with { - write!(route, r"(?={})", ends_with).unwrap(); + write!(route, r"(?={ends_with})").unwrap(); } else { route.push('$'); } @@ -640,16 +640,16 @@ pub fn tokens_to_regex( }; if !strict { - write!(route, r"(?:{}(?={}))?", delimiter, ends_with).unwrap(); + write!(route, r"(?:{delimiter}(?={ends_with}))?").unwrap(); } if !is_end_deliminated { - write!(route, r"(?={}|{})", delimiter, ends_with).unwrap(); + write!(route, r"(?={delimiter}|{ends_with})").unwrap(); } } let flags = if sensitive { "" } else { "(?i)" }; - let re = FancyRegex::new(&format!("{}{}", flags, route))?; + let re = FancyRegex::new(&format!("{flags}{route}"))?; let maybe_keys = if keys.is_empty() { None } else { Some(keys) }; Ok((re, maybe_keys)) @@ -754,7 +754,7 @@ impl Compiler { } } } - write!(path, "{}{}{}", prefix, segment, suffix).unwrap(); + write!(path, "{prefix}{segment}{suffix}").unwrap(); } } } @@ -773,7 +773,7 @@ impl Compiler { } let prefix = k.prefix.clone().unwrap_or_default(); let suffix = k.suffix.clone().unwrap_or_default(); - write!(path, "{}{}{}", prefix, s, suffix).unwrap(); + write!(path, "{prefix}{s}{suffix}").unwrap(); } None => { if !optional { @@ -874,25 +874,23 @@ mod tests { fixtures: &[Fixture], ) { let result = string_to_regex(path, maybe_options); - assert!(result.is_ok(), "Could not parse path: \"{}\"", path); + assert!(result.is_ok(), "Could not parse path: \"{path}\""); let (re, _) = result.unwrap(); for (fixture, expected) in fixtures { let result = re.find(fixture); assert!( result.is_ok(), - "Find failure for path \"{}\" and fixture \"{}\"", - path, - fixture + "Find failure for path \"{path}\" and fixture \"{fixture}\"" ); let actual = result.unwrap(); if let Some((text, start, end)) = *expected { - assert!(actual.is_some(), "Match failure for path \"{}\" and fixture \"{}\". Expected Some got None", path, fixture); + assert!(actual.is_some(), "Match failure for path \"{path}\" and fixture \"{fixture}\". Expected Some got None"); let actual = actual.unwrap(); assert_eq!(actual.as_str(), text, "Match failure for path \"{}\" and fixture \"{}\". Expected \"{}\" got \"{}\".", path, fixture, text, actual.as_str()); assert_eq!(actual.start(), start); assert_eq!(actual.end(), end); } else { - assert!(actual.is_none(), "Match failure for path \"{}\" and fixture \"{}\". Expected None got {:?}", path, fixture, actual); + assert!(actual.is_none(), "Match failure for path \"{path}\" and fixture \"{fixture}\". Expected None got {actual:?}"); } } } diff --git a/cli/lsp/registries.rs b/cli/lsp/registries.rs index ca7b6368e95583..d67068ec728a7a 100644 --- a/cli/lsp/registries.rs +++ b/cli/lsp/registries.rs @@ -217,10 +217,10 @@ fn get_endpoint_with_match( Token::Key(k) if k.name == *key => Some(k), _ => None, }); - url = url - .replace(&format!("${{{}}}", name), &value.to_string(maybe_key, true)); + url = + url.replace(&format!("${{{name}}}"), &value.to_string(maybe_key, true)); url = url.replace( - &format!("${{{{{}}}}}", name), + &format!("${{{{{name}}}}}"), &percent_encoding::percent_encode( value.to_string(maybe_key, true).as_bytes(), COMPONENT, @@ -278,8 +278,8 @@ fn replace_variable( let value = maybe_value.unwrap_or(""); if let StringOrNumber::String(name) = &variable.name { url_str - .replace(&format!("${{{}}}", name), value) - .replace(&format! {"${{{{{}}}}}", name}, value) + .replace(&format!("${{{name}}}"), value) + .replace(&format! {"${{{{{name}}}}}"}, value) } else { url_str } @@ -723,7 +723,7 @@ impl ModuleRegistry { } for (idx, item) in items.into_iter().enumerate() { let mut label = if let Some(p) = &prefix { - format!("{}{}", p, item) + format!("{p}{item}") } else { item.clone() }; @@ -880,7 +880,7 @@ impl ModuleRegistry { is_incomplete = true; } for (idx, item) in items.into_iter().enumerate() { - let path = format!("{}{}", prefix, item); + let path = format!("{prefix}{item}"); let kind = Some(lsp::CompletionItemKind::FOLDER); let item_specifier = base.join(&path).ok()?; let full_text = item_specifier.as_str(); diff --git a/cli/lsp/repl.rs b/cli/lsp/repl.rs index 81e621c13c3d3a..41a3f993ac8cec 100644 --- a/cli/lsp/repl.rs +++ b/cli/lsp/repl.rs @@ -188,7 +188,7 @@ impl ReplLanguageServer { let new_text = if new_text.ends_with('\n') { new_text.to_string() } else { - format!("{}\n", new_text) + format!("{new_text}\n") }; self.document_version += 1; let current_line_count = diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs index 3619f529c1f255..2f66e2d2db6db0 100644 --- a/cli/lsp/tsc.rs +++ b/cli/lsp/tsc.rs @@ -211,7 +211,7 @@ fn new_assets_map() -> Arc> { let assets = tsc::LAZILY_LOADED_STATIC_ASSETS .iter() .map(|(k, v)| { - let url_str = format!("asset:///{}", k); + let url_str = format!("asset:///{k}"); let specifier = resolve_url(&url_str).unwrap(); let asset = AssetDocument::new(specifier.clone(), v); (specifier, asset) @@ -384,9 +384,9 @@ fn get_tag_documentation( let maybe_text = get_tag_body_text(tag, language_server); if let Some(text) = maybe_text { if text.contains('\n') { - format!("{} \n{}", label, text) + format!("{label} \n{text}") } else { - format!("{} - {}", label, text) + format!("{label} - {text}") } } else { label @@ -397,7 +397,7 @@ fn make_codeblock(text: &str) -> String { if CODEBLOCK_RE.is_match(text) { text.to_string() } else { - format!("```\n{}\n```", text) + format!("```\n{text}\n```") } } @@ -700,9 +700,9 @@ fn display_parts_to_string( .unwrap_or_else(|| "".to_string()) }); let link_str = if link.linkcode { - format!("[`{}`]({})", link_text, specifier) + format!("[`{link_text}`]({specifier})") } else { - format!("[{}]({})", link_text, specifier) + format!("[{link_text}]({specifier})") }; out.push(link_str); } @@ -785,8 +785,7 @@ impl QuickInfo { .join(" \n\n"); if !tags_preview.is_empty() { parts.push(lsp::MarkedString::from_markdown(format!( - "\n\n{}", - tags_preview + "\n\n{tags_preview}" ))); } } @@ -1984,7 +1983,7 @@ impl CompletionEntryDetails { .map(|tag_info| get_tag_documentation(tag_info, language_server)) .collect::>() .join(""); - value = format!("{}\n\n{}", value, tag_documentation); + value = format!("{value}\n\n{tag_documentation}"); } Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind: lsp::MarkupKind::Markdown, @@ -2486,7 +2485,7 @@ impl SignatureHelpItem { let documentation = display_parts_to_string(&self.documentation, language_server); lsp::SignatureInformation { - label: format!("{}{}{}", prefix_text, params_text, suffix_text), + label: format!("{prefix_text}{params_text}{suffix_text}"), documentation: Some(lsp::Documentation::MarkupContent( lsp::MarkupContent { kind: lsp::MarkupKind::Markdown, @@ -2844,7 +2843,7 @@ fn start( .clone() .unwrap_or_else(|| Url::parse("cache:///").unwrap()); let init_config = json!({ "debug": debug, "rootUri": root_uri }); - let init_src = format!("globalThis.serverInit({});", init_config); + let init_src = format!("globalThis.serverInit({init_config});"); runtime.execute_script(&located_script_name!(), &init_src)?; Ok(()) @@ -3433,7 +3432,7 @@ pub fn request( (state.performance.clone(), method.to_value(state, id)) }; let mark = performance.mark("request", Some(request_params.clone())); - let request_src = format!("globalThis.serverRequest({});", request_params); + let request_src = format!("globalThis.serverRequest({request_params});"); runtime.execute_script(&located_script_name!(), &request_src)?; let op_state = runtime.op_state(); diff --git a/cli/lsp/urls.rs b/cli/lsp/urls.rs index abe83d3cb5e40c..4fba0c9ff3a373 100644 --- a/cli/lsp/urls.rs +++ b/cli/lsp/urls.rs @@ -104,10 +104,10 @@ impl LspUrlMap { format!("deno:/asset{}", specifier.path()) } else if specifier.scheme() == "data" { let data_url = DataUrl::process(specifier.as_str()) - .map_err(|e| uri_error(format!("{:?}", e)))?; + .map_err(|e| uri_error(format!("{e:?}")))?; let mime = data_url.mime_type(); let (media_type, _) = - map_content_type(specifier, Some(&format!("{}", mime))); + map_content_type(specifier, Some(&format!("{mime}"))); let extension = if media_type == MediaType::Unknown { "" } else { @@ -128,7 +128,7 @@ impl LspUrlMap { }) .collect(); path.push_str(&parts.join("/")); - format!("deno:/{}", path) + format!("deno:/{path}") }; let url = Url::parse(&specifier_str)?; inner.put(specifier.clone(), url.clone()); diff --git a/cli/main.rs b/cli/main.rs index 8c0dd0354157f1..7504bf9417175f 100644 --- a/cli/main.rs +++ b/cli/main.rs @@ -139,7 +139,7 @@ async fn run_subcommand(flags: Flags) -> Result { DenoSubcommand::Test(test_flags) => { if let Some(ref coverage_dir) = flags.coverage_dir { std::fs::create_dir_all(coverage_dir) - .with_context(|| format!("Failed creating: {}", coverage_dir))?; + .with_context(|| format!("Failed creating: {coverage_dir}"))?; // this is set in order to ensure spawned processes use the same // coverage directory env::set_var( @@ -206,7 +206,7 @@ fn unwrap_or_exit(result: Result) -> T { match result { Ok(value) => value, Err(error) => { - let mut error_string = format!("{:?}", error); + let mut error_string = format!("{error:?}"); let mut error_code = 1; if let Some(e) = error.downcast_ref::() { diff --git a/cli/module_loader.rs b/cli/module_loader.rs index c0f9e43d010268..c7872988b1b018 100644 --- a/cli/module_loader.rs +++ b/cli/module_loader.rs @@ -122,7 +122,7 @@ impl CliModuleLoader { )? } MediaType::TsBuildInfo | MediaType::Wasm | MediaType::SourceMap => { - panic!("Unexpected media type {} for {}", media_type, found_url) + panic!("Unexpected media type {media_type} for {found_url}") } }; @@ -136,7 +136,7 @@ impl CliModuleLoader { }) } _ => { - let mut msg = format!("Loading unprepared module: {}", specifier); + let mut msg = format!("Loading unprepared module: {specifier}"); if let Some(referrer) = maybe_referrer { msg = format!("{}, imported from: {}", msg, referrer.as_str()); } diff --git a/cli/napi/async.rs b/cli/napi/async.rs index 8fdb4f9d241c8d..8cbdb22204c866 100644 --- a/cli/napi/async.rs +++ b/cli/napi/async.rs @@ -39,7 +39,7 @@ fn napi_cancel_async_work( /// Frees a previously allocated work object. #[napi_sym::napi_sym] fn napi_delete_async_work(_env: &mut Env, work: napi_async_work) -> Result { - let work = Box::from_raw(work); + let work = Box::from_raw(work as *mut AsyncWork); drop(work); Ok(()) diff --git a/cli/napi/env.rs b/cli/napi/env.rs index 922c6414023555..bdd5221e874b5b 100644 --- a/cli/napi/env.rs +++ b/cli/napi/env.rs @@ -34,8 +34,7 @@ pub unsafe extern "C" fn napi_fatal_error( std::str::from_utf8(slice).unwrap() }; panic!( - "Fatal exception triggered by napi_fatal_error!\nLocation: {:?}\n{}", - location, message + "Fatal exception triggered by napi_fatal_error!\nLocation: {location:?}\n{message}" ); } @@ -46,10 +45,7 @@ fn napi_fatal_exception(env: *mut Env, value: napi_value) -> Result { let env: &mut Env = env.as_mut().ok_or(Error::InvalidArg)?; let value = transmute::>(value); let error = value.to_rust_string_lossy(&mut env.scope()); - panic!( - "Fatal exception triggered by napi_fatal_exception!\n{}", - error - ); + panic!("Fatal exception triggered by napi_fatal_exception!\n{error}"); } #[napi_sym::napi_sym] diff --git a/cli/node/analyze.rs b/cli/node/analyze.rs index fd131c551b2520..d1046e275a7aa5 100644 --- a/cli/node/analyze.rs +++ b/cli/node/analyze.rs @@ -76,11 +76,11 @@ pub fn esm_code_with_node_globals( let global_this_expr = if has_global_this { global_this_expr } else { - write!(result, "var globalThis = {};", global_this_expr).unwrap(); + write!(result, "var globalThis = {global_this_expr};").unwrap(); "globalThis" }; for global in globals { - write!(result, "var {0} = {1}.{0};", global, global_this_expr).unwrap(); + write!(result, "var {global} = {global_this_expr}.{global};").unwrap(); } let file_text = text_info.text_str(); diff --git a/cli/node/mod.rs b/cli/node/mod.rs index 2125f670e188db..8d599923b3d27f 100644 --- a/cli/node/mod.rs +++ b/cli/node/mod.rs @@ -65,7 +65,7 @@ impl NodeResolution { if specifier.starts_with("node:") { ModuleSpecifier::parse(&specifier).unwrap() } else { - ModuleSpecifier::parse(&format!("node:{}", specifier)).unwrap() + ModuleSpecifier::parse(&format!("node:{specifier}")).unwrap() } } } @@ -146,8 +146,7 @@ pub fn resolve_builtin_node_module(specifier: &str) -> Result { } Err(generic_error(format!( - "Unknown built-in \"node:\" module: {}", - specifier + "Unknown built-in \"node:\" module: {specifier}" ))) } @@ -235,8 +234,7 @@ pub async fn initialize_binary_command( Object.defineProperty(process.argv, "0", {{ get: () => binaryName, }}); - }})('{}');"#, - binary_name, + }})('{binary_name}');"#, ); let value = @@ -333,7 +331,7 @@ pub fn node_resolve_npm_reference( &reference .sub_path .as_ref() - .map(|s| format!("./{}", s)) + .map(|s| format!("./{s}")) .unwrap_or_else(|| ".".to_string()), &package_folder, node_module_kind, @@ -343,7 +341,7 @@ pub fn node_resolve_npm_reference( permissions, ) .with_context(|| { - format!("Error resolving package config for '{}'", reference) + format!("Error resolving package config for '{reference}'") })?; let resolved_path = match maybe_resolved_path { Some(resolved_path) => resolved_path, @@ -425,7 +423,7 @@ fn resolve_bin_entry_value<'a>( .map(|o| { o.keys() .into_iter() - .map(|k| format!(" * npm:{}/{}", pkg_req, k)) + .map(|k| format!(" * npm:{pkg_req}/{k}")) .collect::>() }) .unwrap_or_default(); @@ -546,8 +544,7 @@ pub fn url_to_node_resolution( Ok(NodeResolution::Esm(url)) } else if url_str.ends_with(".ts") { Err(generic_error(format!( - "TypeScript files are not supported in npm packages: {}", - url + "TypeScript files are not supported in npm packages: {url}" ))) } else { Ok(NodeResolution::CommonJs(url)) @@ -681,15 +678,13 @@ fn add_export( // so assign it to a temporary variable that won't have a conflict, then re-export // it as a string source.push(format!( - "const __deno_export_{}__ = {};", - temp_var_count, initializer + "const __deno_export_{temp_var_count}__ = {initializer};" )); source.push(format!( - "export {{ __deno_export_{}__ as \"{}\" }};", - temp_var_count, name + "export {{ __deno_export_{temp_var_count}__ as \"{name}\" }};" )); } else { - source.push(format!("export const {} = {};", name, initializer)); + source.push(format!("export const {name} = {initializer};")); } } @@ -838,7 +833,7 @@ pub fn translate_cjs_to_esm( add_export( &mut source, export, - &format!("mod[\"{}\"]", export), + &format!("mod[\"{export}\"]"), &mut temp_var_count, ); } @@ -975,7 +970,7 @@ fn parse_specifier(specifier: &str) -> Option<(String, String)> { fn to_file_path(url: &ModuleSpecifier) -> PathBuf { url .to_file_path() - .unwrap_or_else(|_| panic!("Provided URL was not file:// URL: {}", url)) + .unwrap_or_else(|_| panic!("Provided URL was not file:// URL: {url}")) } fn to_file_path_string(url: &ModuleSpecifier) -> String { diff --git a/cli/npm/cache.rs b/cli/npm/cache.rs index 6a6c6156ca5d0e..0d07d27b260048 100644 --- a/cli/npm/cache.rs +++ b/cli/npm/cache.rs @@ -216,7 +216,7 @@ impl ReadonlyNpmCache { let encoded_name = mixed_case_package_name_encode(name); // Using the encoded directory may have a collision with an actual package name // so prefix it with an underscore since npm packages can't start with that - dir.join(format!("_{}", encoded_name)) + dir.join(format!("_{encoded_name}")) } else { // ensure backslashes are used on windows for part in name.split('/') { diff --git a/cli/npm/registry.rs b/cli/npm/registry.rs index 97397350dee5b5..9598feba1f00cf 100644 --- a/cli/npm/registry.rs +++ b/cli/npm/registry.rs @@ -131,8 +131,7 @@ impl NpmPackageVersionInfo { let version_req = NpmVersionReq::parse(&version_req).with_context(|| { format!( - "error parsing version requirement for dependency: {}@{}", - bare_specifier, version_req + "error parsing version requirement for dependency: {bare_specifier}@{version_req}" ) })?; Ok(NpmDependencyEntry { @@ -369,10 +368,7 @@ impl RealNpmRegistryApiInner { Ok(value) => value, Err(err) => { if cfg!(debug_assertions) { - panic!( - "error loading cached npm package info for {}: {:#}", - name, err - ); + panic!("error loading cached npm package info for {name}: {err:#}"); } else { None } @@ -415,10 +411,7 @@ impl RealNpmRegistryApiInner { self.save_package_info_to_file_cache_result(name, package_info) { if cfg!(debug_assertions) { - panic!( - "error saving cached npm package info for {}: {:#}", - name, err - ); + panic!("error saving cached npm package info for {name}: {err:#}"); } } } @@ -443,8 +436,7 @@ impl RealNpmRegistryApiInner { return Err(custom_error( "NotCached", format!( - "An npm specifier not found in cache: \"{}\", --cached-only is specified.", - name + "An npm specifier not found in cache: \"{name}\", --cached-only is specified." ) )); } diff --git a/cli/npm/resolution/mod.rs b/cli/npm/resolution/mod.rs index ed194bbac8910a..407651ccb996b2 100644 --- a/cli/npm/resolution/mod.rs +++ b/cli/npm/resolution/mod.rs @@ -112,7 +112,7 @@ impl NpmPackageId { let (input, version) = parse_version(input)?; match NpmVersion::parse(version) { Ok(version) => Ok((input, (name.to_string(), version))), - Err(err) => ParseError::fail(at_version_input, format!("{:#}", err)), + Err(err) => ParseError::fail(at_version_input, format!("{err:#}")), } } @@ -173,7 +173,7 @@ impl NpmPackageId { } with_failure_handling(parse_id_at_level(0))(id) - .with_context(|| format!("Invalid npm package id '{}'.", id)) + .with_context(|| format!("Invalid npm package id '{id}'.")) } pub fn display(&self) -> String { diff --git a/cli/npm/resolution/snapshot.rs b/cli/npm/resolution/snapshot.rs index ad6aee6d955b3c..be64ea611e6b16 100644 --- a/cli/npm/resolution/snapshot.rs +++ b/cli/npm/resolution/snapshot.rs @@ -247,7 +247,7 @@ impl NpmResolutionSnapshot { // collect the specifiers to version mappings for (key, value) in &lockfile.content.npm.specifiers { let package_req = NpmPackageReq::from_str(key) - .with_context(|| format!("Unable to parse npm specifier: {}", key))?; + .with_context(|| format!("Unable to parse npm specifier: {key}"))?; let package_id = NpmPackageId::from_serialized(value)?; package_reqs.insert(package_req, package_id.clone()); verify_ids.insert(package_id.clone()); diff --git a/cli/npm/resolution/specifier.rs b/cli/npm/resolution/specifier.rs index 6667c60dd11426..0aa6934727b011 100644 --- a/cli/npm/resolution/specifier.rs +++ b/cli/npm/resolution/specifier.rs @@ -47,7 +47,7 @@ impl NpmPackageReference { let parts = specifier.split('/').collect::>(); let name_part_len = if specifier.starts_with('@') { 2 } else { 1 }; if parts.len() < name_part_len { - return Err(generic_error(format!("Not a valid package: {}", specifier))); + return Err(generic_error(format!("Not a valid package: {specifier}"))); } let name_parts = &parts[0..name_part_len]; let last_name_part = &name_parts[name_part_len - 1]; @@ -81,8 +81,7 @@ impl NpmPackageReference { if let Some(at_index) = sub_path.rfind('@') { let (new_sub_path, version) = sub_path.split_at(at_index); let msg = format!( - "Invalid package specifier 'npm:{}/{}'. Did you mean to write 'npm:{}{}/{}'?", - name, sub_path, name, version, new_sub_path + "Invalid package specifier 'npm:{name}/{sub_path}'. Did you mean to write 'npm:{name}{version}/{new_sub_path}'?" ); return Err(generic_error(msg)); } @@ -90,8 +89,7 @@ impl NpmPackageReference { if name.is_empty() { let msg = format!( - "Invalid npm specifier '{}'. Did not contain a package name.", - original_text + "Invalid npm specifier '{original_text}'. Did not contain a package name." ); return Err(generic_error(msg)); } @@ -133,7 +131,7 @@ impl std::fmt::Display for NpmPackageReq { impl NpmPackageReq { pub fn from_str(text: &str) -> Result { // probably should do something more targeted in the future - let reference = NpmPackageReference::from_str(&format!("npm:{}", text))?; + let reference = NpmPackageReference::from_str(&format!("npm:{text}"))?; Ok(reference.req) } } @@ -163,7 +161,7 @@ impl NpmVersionMatcher for NpmPackageReq { self .version_req .as_ref() - .map(|v| format!("{}", v)) + .map(|v| format!("{v}")) .unwrap_or_else(|| "non-prerelease".to_string()) } } diff --git a/cli/npm/resolvers/mod.rs b/cli/npm/resolvers/mod.rs index 4307f2b2eca96c..9ea14061ecbc3e 100644 --- a/cli/npm/resolvers/mod.rs +++ b/cli/npm/resolvers/mod.rs @@ -256,14 +256,13 @@ impl NpmPackageResolver { .iter() .collect::>() // prevent duplicates .iter() - .map(|p| format!("\"{}\"", p)) + .map(|p| format!("\"{p}\"")) .collect::>() .join(", "); return Err(custom_error( "NoNpm", format!( - "Following npm specifiers were requested: {}; but --no-npm is specified.", - fmt_reqs + "Following npm specifiers were requested: {fmt_reqs}; but --no-npm is specified." ), )); } diff --git a/cli/npm/semver/mod.rs b/cli/npm/semver/mod.rs index a8758580983645..b532835e6a9949 100644 --- a/cli/npm/semver/mod.rs +++ b/cli/npm/semver/mod.rs @@ -53,7 +53,7 @@ impl fmt::Display for NpmVersion { if i > 0 { write!(f, ".")?; } - write!(f, "{}", part)?; + write!(f, "{part}")?; } } if !self.build.is_empty() { @@ -62,7 +62,7 @@ impl fmt::Display for NpmVersion { if i > 0 { write!(f, ".")?; } - write!(f, "{}", part)?; + write!(f, "{part}")?; } } Ok(()) @@ -143,7 +143,7 @@ impl NpmVersion { pub fn parse(text: &str) -> Result { let text = text.trim(); with_failure_handling(parse_npm_version)(text) - .with_context(|| format!("Invalid npm version '{}'.", text)) + .with_context(|| format!("Invalid npm version '{text}'.")) } } @@ -218,7 +218,7 @@ impl NpmVersionReq { pub fn parse(text: &str) -> Result { let text = text.trim(); with_failure_handling(parse_npm_version_req)(text) - .with_context(|| format!("Invalid npm version requirement '{}'.", text)) + .with_context(|| format!("Invalid npm version requirement '{text}'.")) } } @@ -523,7 +523,7 @@ fn nr(input: &str) -> ParseResult { Err(err) => { return ParseError::fail( input, - format!("Error parsing '{}' to u64.\n\n{:#}", result, err), + format!("Error parsing '{result}' to u64.\n\n{err:#}"), ) } }; @@ -984,9 +984,7 @@ mod tests { let version = NpmVersion::parse(version_text).unwrap(); assert!( req.matches(&version), - "Checking {} satisfies {}", - req_text, - version_text + "Checking {req_text} satisfies {version_text}" ); } } @@ -1083,9 +1081,7 @@ mod tests { let version = NpmVersion::parse(version_text).unwrap(); assert!( !req.matches(&version), - "Checking {} not satisfies {}", - req_text, - version_text + "Checking {req_text} not satisfies {version_text}" ); } } diff --git a/cli/npm/semver/specifier.rs b/cli/npm/semver/specifier.rs index 3fdeab16d5d21d..b12a5c3088dcbb 100644 --- a/cli/npm/semver/specifier.rs +++ b/cli/npm/semver/specifier.rs @@ -33,7 +33,7 @@ impl std::fmt::Display for SpecifierVersionReq { impl SpecifierVersionReq { pub fn parse(text: &str) -> Result { with_failure_handling(parse_npm_specifier)(text).with_context(|| { - format!("Invalid npm specifier version requirement '{}'.", text) + format!("Invalid npm specifier version requirement '{text}'.") }) } @@ -143,7 +143,7 @@ fn nr(input: &str) -> ParseResult { Err(err) => { return ParseError::fail( input, - format!("Error parsing '{}' to u64.\n\n{:#}", result, err), + format!("Error parsing '{result}' to u64.\n\n{err:#}"), ) } }; diff --git a/cli/npm/tarball.rs b/cli/npm/tarball.rs index 7fce69cdaa4722..758ac3ded6258f 100644 --- a/cli/npm/tarball.rs +++ b/cli/npm/tarball.rs @@ -154,12 +154,12 @@ mod test { verify_tarball_integrity(package, &Vec::new(), "sha512-test") .unwrap_err() .to_string(), - format!("Tarball checksum did not match what was provided by npm registry for package@1.0.0.\n\nExpected: test\nActual: {}", actual_checksum), + format!("Tarball checksum did not match what was provided by npm registry for package@1.0.0.\n\nExpected: test\nActual: {actual_checksum}"), ); assert!(verify_tarball_integrity( package, &Vec::new(), - &format!("sha512-{}", actual_checksum) + &format!("sha512-{actual_checksum}") ) .is_ok()); } diff --git a/cli/proc_state.rs b/cli/proc_state.rs index eca4579c83e6fd..2612af75b4bc90 100644 --- a/cli/proc_state.rs +++ b/cli/proc_state.rs @@ -559,7 +559,7 @@ impl ProcState { permissions, )) .with_context(|| { - format!("Could not resolve '{}' from '{}'.", specifier, referrer) + format!("Could not resolve '{specifier}' from '{referrer}'.") }); } @@ -581,7 +581,7 @@ impl ProcState { { return Err(custom_error( "NotSupported", - format!("importing npm specifiers in remote modules requires the --unstable flag (referrer: {})", found_referrer), + format!("importing npm specifiers in remote modules requires the --unstable flag (referrer: {found_referrer})"), )); } @@ -592,7 +592,7 @@ impl ProcState { &self.npm_resolver, permissions, )) - .with_context(|| format!("Could not resolve '{}'.", reference)); + .with_context(|| format!("Could not resolve '{reference}'.")); } else { return Ok(specifier.clone()); } @@ -639,7 +639,7 @@ impl ProcState { &self.npm_resolver, permissions, )) - .with_context(|| format!("Could not resolve '{}'.", reference)); + .with_context(|| format!("Could not resolve '{reference}'.")); } } } diff --git a/cli/standalone.rs b/cli/standalone.rs index 063ad7d3374fc8..e36584d7200608 100644 --- a/cli/standalone.rs +++ b/cli/standalone.rs @@ -320,9 +320,7 @@ fn get_error_class_name(e: &AnyError) -> &'static str { panic!( "Error '{}' contains boxed error of unsupported type:{}", e, - e.chain() - .map(|e| format!("\n {:?}", e)) - .collect::() + e.chain().map(|e| format!("\n {e:?}")).collect::() ); }) } diff --git a/cli/tests/integration/coverage_tests.rs b/cli/tests/integration/coverage_tests.rs index 5f82971c60c6db..87ed655b8b88c3 100644 --- a/cli/tests/integration/coverage_tests.rs +++ b/cli/tests/integration/coverage_tests.rs @@ -97,7 +97,7 @@ fn run_coverage_text(test_name: &str, extension: &str) { .arg("--quiet") .arg("--unstable") .arg(format!("--coverage={}", tempdir.to_str().unwrap())) - .arg(format!("coverage/{}_test.{}", test_name, extension)) + .arg(format!("coverage/{test_name}_test.{extension}")) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::inherit()) .status() @@ -123,13 +123,13 @@ fn run_coverage_text(test_name: &str, extension: &str) { .to_string(); let expected = fs::read_to_string( - util::testdata_path().join(format!("coverage/{}_expected.out", test_name)), + util::testdata_path().join(format!("coverage/{test_name}_expected.out")), ) .unwrap(); if !util::wildcard_match(&expected, &actual) { - println!("OUTPUT\n{}\nOUTPUT", actual); - println!("EXPECTED\n{}\nEXPECTED", expected); + println!("OUTPUT\n{actual}\nOUTPUT"); + println!("EXPECTED\n{expected}\nEXPECTED"); panic!("pattern match failed"); } @@ -152,13 +152,13 @@ fn run_coverage_text(test_name: &str, extension: &str) { .to_string(); let expected = fs::read_to_string( - util::testdata_path().join(format!("coverage/{}_expected.lcov", test_name)), + util::testdata_path().join(format!("coverage/{test_name}_expected.lcov")), ) .unwrap(); if !util::wildcard_match(&expected, &actual) { - println!("OUTPUT\n{}\nOUTPUT", actual); - println!("EXPECTED\n{}\nEXPECTED", expected); + println!("OUTPUT\n{actual}\nOUTPUT"); + println!("EXPECTED\n{expected}\nEXPECTED"); panic!("pattern match failed"); } @@ -208,8 +208,8 @@ fn multifile_coverage() { .unwrap(); if !util::wildcard_match(&expected, &actual) { - println!("OUTPUT\n{}\nOUTPUT", actual); - println!("EXPECTED\n{}\nEXPECTED", expected); + println!("OUTPUT\n{actual}\nOUTPUT"); + println!("EXPECTED\n{expected}\nEXPECTED"); panic!("pattern match failed"); } @@ -237,8 +237,8 @@ fn multifile_coverage() { .unwrap(); if !util::wildcard_match(&expected, &actual) { - println!("OUTPUT\n{}\nOUTPUT", actual); - println!("EXPECTED\n{}\nEXPECTED", expected); + println!("OUTPUT\n{actual}\nOUTPUT"); + println!("EXPECTED\n{expected}\nEXPECTED"); panic!("pattern match failed"); } @@ -258,8 +258,7 @@ fn no_snaps_included(test_name: &str, extension: &str) { .arg("--allow-read") .arg(format!("--coverage={}", tempdir.to_str().unwrap())) .arg(format!( - "coverage/no_snaps_included/{}_test.{}", - test_name, extension + "coverage/no_snaps_included/{test_name}_test.{extension}" )) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()) @@ -292,8 +291,8 @@ fn no_snaps_included(test_name: &str, extension: &str) { .unwrap(); if !util::wildcard_match(&expected, &actual) { - println!("OUTPUT\n{}\nOUTPUT", actual); - println!("EXPECTED\n{}\nEXPECTED", expected); + println!("OUTPUT\n{actual}\nOUTPUT"); + println!("EXPECTED\n{expected}\nEXPECTED"); panic!("pattern match failed"); } @@ -339,8 +338,8 @@ fn no_transpiled_lines() { .unwrap(); if !util::wildcard_match(&expected, &actual) { - println!("OUTPUT\n{}\nOUTPUT", actual); - println!("EXPECTED\n{}\nEXPECTED", expected); + println!("OUTPUT\n{actual}\nOUTPUT"); + println!("EXPECTED\n{expected}\nEXPECTED"); panic!("pattern match failed"); } @@ -367,8 +366,8 @@ fn no_transpiled_lines() { .unwrap(); if !util::wildcard_match(&expected, &actual) { - println!("OUTPUT\n{}\nOUTPUT", actual); - println!("EXPECTED\n{}\nEXPECTED", expected); + println!("OUTPUT\n{actual}\nOUTPUT"); + println!("EXPECTED\n{expected}\nEXPECTED"); panic!("pattern match failed"); } diff --git a/cli/tests/integration/fmt_tests.rs b/cli/tests/integration/fmt_tests.rs index d230f96c076d00..52aae2bd315878 100644 --- a/cli/tests/integration/fmt_tests.rs +++ b/cli/tests/integration/fmt_tests.rs @@ -31,8 +31,7 @@ fn fmt_test() { .current_dir(&testdata_fmt_dir) .arg("fmt") .arg(format!( - "--ignore={},{},{}", - badly_formatted_js_str, badly_formatted_md_str, badly_formatted_json_str + "--ignore={badly_formatted_js_str},{badly_formatted_md_str},{badly_formatted_json_str}" )) .arg("--check") .arg(badly_formatted_js_str) diff --git a/cli/tests/integration/inspector_tests.rs b/cli/tests/integration/inspector_tests.rs index 5b01522d5dbc7c..bfc3a63e0922be 100644 --- a/cli/tests/integration/inspector_tests.rs +++ b/cli/tests/integration/inspector_tests.rs @@ -103,8 +103,7 @@ impl InspectorTester { self.child.kill().unwrap(); panic!( - "Inspector test failed with error: {:?}.\nstdout:\n{}\nstderr:\n{}", - err, stdout, stderr + "Inspector test failed with error: {err:?}.\nstdout:\n{stdout}\nstderr:\n{stderr}" ); } } @@ -215,7 +214,7 @@ fn inspect_flag_with_unique_port(flag_prefix: &str) -> String { use std::sync::atomic::Ordering; static PORT: AtomicU16 = AtomicU16::new(9229); let port = PORT.fetch_add(1, Ordering::Relaxed); - format!("{}=127.0.0.1:{}", flag_prefix, port) + format!("{flag_prefix}=127.0.0.1:{port}") } fn extract_ws_url_from_stderr( @@ -508,7 +507,7 @@ async fn inspector_does_not_hang() { .await; tester .assert_received_messages( - &[&format!(r#"{{"id":{},"result":{{}}}}"#, request_id)], + &[&format!(r#"{{"id":{request_id},"result":{{}}}}"#)], &[r#"{"method":"Debugger.resumed","params":{}}"#], ) .await; diff --git a/cli/tests/integration/lsp_tests.rs b/cli/tests/integration/lsp_tests.rs index be280bfa736833..1fd619a40af1b5 100644 --- a/cli/tests/integration/lsp_tests.rs +++ b/cli/tests/integration/lsp_tests.rs @@ -103,7 +103,7 @@ pub fn ensure_directory_specifier( ) -> ModuleSpecifier { let path = specifier.path(); if !path.ends_with('/') { - let new_path = format!("{}/", path); + let new_path = format!("{path}/"); specifier.set_path(&new_path); } specifier diff --git a/cli/tests/integration/repl_tests.rs b/cli/tests/integration/repl_tests.rs index af9fce18750df0..30d91bc1ca2349 100644 --- a/cli/tests/integration/repl_tests.rs +++ b/cli/tests/integration/repl_tests.rs @@ -673,7 +673,7 @@ fn assign_underscore_error() { Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), false, ); - println!("{}", out); + println!("{out}"); assert_ends_with!( out, "Last thrown error is no longer saved to _error.\n1\nUncaught 2\n1\n" diff --git a/cli/tests/integration/run_tests.rs b/cli/tests/integration/run_tests.rs index fd6644326afb2d..923232f9d441e4 100644 --- a/cli/tests/integration/run_tests.rs +++ b/cli/tests/integration/run_tests.rs @@ -1942,9 +1942,9 @@ mod permissions { .current_dir(&util::testdata_path()) .arg("run") .arg("--unstable") - .arg(format!("--allow-{0}", permission)) + .arg(format!("--allow-{permission}")) .arg("run/permission_test.ts") - .arg(format!("{0}Required", permission)) + .arg(format!("{permission}Required")) .spawn() .unwrap() .wait() @@ -1959,10 +1959,7 @@ mod permissions { for permission in &util::PERMISSION_VARIANTS { let (_, err) = util::run_and_collect_output( false, - &format!( - "run --unstable run/permission_test.ts {0}Required", - permission - ), + &format!("run --unstable run/permission_test.ts {permission}Required"), None, None, false, @@ -2100,7 +2097,7 @@ mod permissions { let status = util::deno_cmd() .current_dir(&util::testdata_path()) .arg("run") - .arg(format!("--allow-{0}={1},{2}", permission, test_dir, js_dir)) + .arg(format!("--allow-{permission}={test_dir},{js_dir}")) .arg("run/complex_permissions_test.ts") .arg(permission) .arg("run/complex_permissions_test.ts") @@ -2119,7 +2116,7 @@ mod permissions { let status = util::deno_cmd() .current_dir(&util::testdata_path()) .arg("run") - .arg(format!("--allow-{0}=.", permission)) + .arg(format!("--allow-{permission}=.")) .arg("run/complex_permissions_test.ts") .arg(permission) .arg("run/complex_permissions_test.ts") @@ -2138,7 +2135,7 @@ mod permissions { let status = util::deno_cmd() .current_dir(&util::testdata_path()) .arg("run") - .arg(format!("--allow-{0}=tls/../", permission)) + .arg(format!("--allow-{permission}=tls/../")) .arg("run/complex_permissions_test.ts") .arg(permission) .arg("run/complex_permissions_test.ts") @@ -3251,7 +3248,7 @@ fn basic_auth_tokens() { assert!(stdout_str.is_empty()); let stderr_str = std::str::from_utf8(&output.stderr).unwrap().trim(); - eprintln!("{}", stderr_str); + eprintln!("{stderr_str}"); assert!(stderr_str .contains("Module not found \"http://127.0.0.1:4554/run/001_hello.js\".")); @@ -3269,7 +3266,7 @@ fn basic_auth_tokens() { .unwrap(); let stderr_str = std::str::from_utf8(&output.stderr).unwrap().trim(); - eprintln!("{}", stderr_str); + eprintln!("{stderr_str}"); assert!(output.status.success()); @@ -3354,7 +3351,7 @@ async fn test_resolve_dns() { .unwrap(); let err = String::from_utf8_lossy(&output.stderr); let out = String::from_utf8_lossy(&output.stdout); - println!("{}", err); + println!("{err}"); assert!(output.status.success()); assert!(err.starts_with("Check file")); diff --git a/cli/tests/integration/vendor_tests.rs b/cli/tests/integration/vendor_tests.rs index 11fee568682baf..cd2f7f12e23b97 100644 --- a/cli/tests/integration/vendor_tests.rs +++ b/cli/tests/integration/vendor_tests.rs @@ -530,7 +530,7 @@ fn update_existing_config_test() { } fn success_text(module_count: &str, dir: &str, has_import_map: bool) -> String { - let mut text = format!("Vendored {} into {} directory.", module_count, dir); + let mut text = format!("Vendored {module_count} into {dir} directory."); if has_import_map { let f = format!( concat!( @@ -544,7 +544,7 @@ fn success_text(module_count: &str, dir: &str, has_import_map: bool) -> String { dir.to_string() } ); - write!(text, "{}", f).unwrap(); + write!(text, "{f}").unwrap(); } text } diff --git a/cli/tests/integration/watcher_tests.rs b/cli/tests/integration/watcher_tests.rs index 375bf680453172..3f586d812299b4 100644 --- a/cli/tests/integration/watcher_tests.rs +++ b/cli/tests/integration/watcher_tests.rs @@ -74,14 +74,14 @@ fn child_lines( .lines() .map(|r| { let line = r.unwrap(); - eprintln!("STDOUT: {}", line); + eprintln!("STDOUT: {line}"); line }); let stderr_lines = std::io::BufReader::new(child.stderr.take().unwrap()) .lines() .map(|r| { let line = r.unwrap(); - eprintln!("STDERR: {}", line); + eprintln!("STDERR: {line}"); line }); (stdout_lines, stderr_lines) diff --git a/cli/tools/coverage/mod.rs b/cli/tools/coverage/mod.rs index 056ed4ab4c1ff2..4b2bcd49d0a3fe 100644 --- a/cli/tools/coverage/mod.rs +++ b/cli/tools/coverage/mod.rs @@ -413,7 +413,7 @@ impl CoverageReporter for LcovCoverageReporter { .ok() .and_then(|p| p.to_str().map(|p| p.to_string())) .unwrap_or_else(|| coverage_report.url.to_string()); - writeln!(out_writer, "SF:{}", file_path)?; + writeln!(out_writer, "SF:{file_path}")?; for function in &coverage_report.named_functions { writeln!( @@ -433,13 +433,13 @@ impl CoverageReporter for LcovCoverageReporter { } let functions_found = coverage_report.named_functions.len(); - writeln!(out_writer, "FNF:{}", functions_found)?; + writeln!(out_writer, "FNF:{functions_found}")?; let functions_hit = coverage_report .named_functions .iter() .filter(|f| f.execution_count > 0) .count(); - writeln!(out_writer, "FNH:{}", functions_hit)?; + writeln!(out_writer, "FNH:{functions_hit}")?; for branch in &coverage_report.branches { let taken = if let Some(taken) = &branch.taken { @@ -459,10 +459,10 @@ impl CoverageReporter for LcovCoverageReporter { } let branches_found = coverage_report.branches.len(); - writeln!(out_writer, "BRF:{}", branches_found)?; + writeln!(out_writer, "BRF:{branches_found}")?; let branches_hit = coverage_report.branches.iter().filter(|b| b.is_hit).count(); - writeln!(out_writer, "BRH:{}", branches_hit)?; + writeln!(out_writer, "BRH:{branches_hit}")?; for (index, count) in &coverage_report.found_lines { writeln!(out_writer, "DA:{},{}", index + 1, count)?; } @@ -472,10 +472,10 @@ impl CoverageReporter for LcovCoverageReporter { .iter() .filter(|(_, count)| *count != 0) .count(); - writeln!(out_writer, "LH:{}", lines_hit)?; + writeln!(out_writer, "LH:{lines_hit}")?; let lines_found = coverage_report.found_lines.len(); - writeln!(out_writer, "LF:{}", lines_found)?; + writeln!(out_writer, "LF:{lines_found}")?; writeln!(out_writer, "end_of_record")?; Ok(()) @@ -664,7 +664,7 @@ pub async fn cover_files( ps.file_fetcher .fetch_cached(&module_specifier, 10) .with_context(|| { - format!("Failed to fetch \"{}\" from cache.", module_specifier) + format!("Failed to fetch \"{module_specifier}\" from cache.") })? }; let file = maybe_file.ok_or_else(|| { diff --git a/cli/tools/doc.rs b/cli/tools/doc.rs index 163d3ffcd9dce8..e27e495704c383 100644 --- a/cli/tools/doc.rs +++ b/cli/tools/doc.rs @@ -69,7 +69,7 @@ pub async fn print_docs( local: PathBuf::from("./$deno$doc.ts"), maybe_types: None, media_type: MediaType::TypeScript, - source: format!("export * from \"{}\";", module_specifier).into(), + source: format!("export * from \"{module_specifier}\";").into(), specifier: root_specifier.clone(), maybe_headers: None, }; diff --git a/cli/tools/fmt.rs b/cli/tools/fmt.rs index 441d4fe0807a2a..a2d9a3027b1a0b 100644 --- a/cli/tools/fmt.rs +++ b/cli/tools/fmt.rs @@ -183,7 +183,7 @@ fn format_markdown( dprint_plugin_json::format_text(text, &json_config) } else { let fake_filename = - PathBuf::from(format!("deno_fmt_stdin.{}", extension)); + PathBuf::from(format!("deno_fmt_stdin.{extension}")); let mut codeblock_config = get_resolved_typescript_config(fmt_options); codeblock_config.line_width = line_width; @@ -287,13 +287,13 @@ async fn check_source_files( warn!("Error checking: {}", file_path.to_string_lossy()); warn!( "{}", - format!("{}", e) + format!("{e}") .split('\n') .map(|l| { if l.trim().is_empty() { String::new() } else { - format!(" {}", l) + format!(" {l}") } }) .collect::>() @@ -317,8 +317,7 @@ async fn check_source_files( } else { let not_formatted_files_str = files_str(not_formatted_files_count); Err(generic_error(format!( - "Found {} not formatted {} in {}", - not_formatted_files_count, not_formatted_files_str, checked_files_str, + "Found {not_formatted_files_count} not formatted {not_formatted_files_str} in {checked_files_str}", ))) } } @@ -369,7 +368,7 @@ async fn format_source_files( Err(e) => { let _g = output_lock.lock(); eprintln!("Error formatting: {}", file_path.to_string_lossy()); - eprintln!(" {}", e); + eprintln!(" {e}"); } } Ok(()) @@ -719,7 +718,7 @@ mod test { &PathBuf::from("mod.ts"), "1", &Default::default(), - |_, file_text, _| Ok(Some(format!("1{}", file_text))), + |_, file_text, _| Ok(Some(format!("1{file_text}"))), ) .unwrap(); } diff --git a/cli/tools/info.rs b/cli/tools/info.rs index 21b3d03f7fd93f..f3de922c6b89c5 100644 --- a/cli/tools/info.rs +++ b/cli/tools/info.rs @@ -266,10 +266,7 @@ fn print_tree_node( writeln!( writer, "{} {}", - colors::gray(format!( - "{}{}─{}", - prefix, sibling_connector, child_connector - )), + colors::gray(format!("{prefix}{sibling_connector}─{child_connector}")), child.text )?; let child_prefix = format!( diff --git a/cli/tools/init/mod.rs b/cli/tools/init/mod.rs index 12d5872f1abd8a..c12b7a286b41bd 100644 --- a/cli/tools/init/mod.rs +++ b/cli/tools/init/mod.rs @@ -18,7 +18,7 @@ fn create_file( .write(true) .create_new(true) .open(dir.join(filename)) - .with_context(|| format!("Failed to create {} file", filename))?; + .with_context(|| format!("Failed to create {filename} file"))?; file.write_all(content.as_bytes())?; Ok(()) } diff --git a/cli/tools/installer.rs b/cli/tools/installer.rs index 2d2584f5480830..cc9b5c696a7824 100644 --- a/cli/tools/installer.rs +++ b/cli/tools/installer.rs @@ -41,8 +41,7 @@ fn validate_name(exec_name: &str) -> Result<(), AnyError> { Ok(()) } else { Err(generic_error(format!( - "Invalid executable name: {}", - exec_name + "Invalid executable name: {exec_name}" ))) } } @@ -53,11 +52,8 @@ fn validate_name(exec_name: &str) -> Result<(), AnyError> { /// A second compatible with git bash / MINGW64 /// Generate batch script to satisfy that. fn generate_executable_file(shim_data: &ShimData) -> Result<(), AnyError> { - let args: Vec = shim_data - .args - .iter() - .map(|c| format!("\"{}\"", c)) - .collect(); + let args: Vec = + shim_data.args.iter().map(|c| format!("\"{c}\"")).collect(); let template = format!( "% generated by deno install %\n@deno {} %*\n", args @@ -122,7 +118,7 @@ fn get_installer_root() -> Result { .ok_or_else(|| { io::Error::new( io::ErrorKind::NotFound, - format!("${} is not defined", home_env_var), + format!("${home_env_var} is not defined"), ) })?; home_path.push(".deno"); @@ -201,7 +197,7 @@ pub fn uninstall(name: String, root: Option) -> Result<(), AnyError> { } if !removed { - return Err(generic_error(format!("No installation found for {}", name))); + return Err(generic_error(format!("No installation found for {name}"))); } // There might be some extra files to delete @@ -339,7 +335,7 @@ fn resolve_shim_data( Level::Debug => "debug", Level::Info => "info", _ => { - return Err(generic_error(format!("invalid log level {}", log_level))) + return Err(generic_error(format!("invalid log level {log_level}"))) } }; executable_args.push(log_level.to_string()); @@ -388,11 +384,11 @@ fn resolve_shim_data( } if let Some(inspect) = flags.inspect { - executable_args.push(format!("--inspect={}", inspect)); + executable_args.push(format!("--inspect={inspect}")); } if let Some(inspect_brk) = flags.inspect_brk { - executable_args.push(format!("--inspect-brk={}", inspect_brk)); + executable_args.push(format!("--inspect-brk={inspect_brk}")); } if let Some(import_map_path) = &flags.import_map_path { @@ -408,7 +404,7 @@ fn resolve_shim_data( extra_files.push(( copy_path, fs::read_to_string(config_path) - .with_context(|| format!("error reading {}", config_path))?, + .with_context(|| format!("error reading {config_path}"))?, )); } else { executable_args.push("--no-config".to_string()); @@ -1082,13 +1078,11 @@ mod tests { assert!(file_path.exists()); let mut expected_string = format!( - "--import-map '{}' --no-config 'http://localhost:4545/cat.ts'", - import_map_url + "--import-map '{import_map_url}' --no-config 'http://localhost:4545/cat.ts'" ); if cfg!(windows) { expected_string = format!( - "\"--import-map\" \"{}\" \"--no-config\" \"http://localhost:4545/cat.ts\"", - import_map_url + "\"--import-map\" \"{import_map_url}\" \"--no-config\" \"http://localhost:4545/cat.ts\"" ); } diff --git a/cli/tools/lint.rs b/cli/tools/lint.rs index ba30c546a17df4..0f81ec89dfaf7b 100644 --- a/cli/tools/lint.rs +++ b/cli/tools/lint.rs @@ -219,7 +219,7 @@ pub fn print_rules_list(json: bool) { }) .collect(); let json_str = serde_json::to_string_pretty(&json_rules).unwrap(); - println!("{}", json_str); + println!("{json_str}"); } else { // The rules should still be printed even if `--quiet` option is enabled, // so use `println!` here instead of `info!`. @@ -345,12 +345,12 @@ impl LintReporter for PrettyLintReporter { )), ); - eprintln!("{}\n", message); + eprintln!("{message}\n"); } fn visit_error(&mut self, file_path: &str, err: &AnyError) { - eprintln!("Error linting: {}", file_path); - eprintln!(" {}", err); + eprintln!("Error linting: {file_path}"); + eprintln!(" {err}"); } fn close(&mut self, check_count: usize) { @@ -393,8 +393,8 @@ impl LintReporter for CompactLintReporter { } fn visit_error(&mut self, file_path: &str, err: &AnyError) { - eprintln!("Error linting: {}", file_path); - eprintln!(" {}", err); + eprintln!("Error linting: {file_path}"); + eprintln!(" {err}"); } fn close(&mut self, check_count: usize) { diff --git a/cli/tools/repl/editor.rs b/cli/tools/repl/editor.rs index f8302367ab0bc0..c9f019305c991d 100644 --- a/cli/tools/repl/editor.rs +++ b/cli/tools/repl/editor.rs @@ -277,8 +277,7 @@ fn validate(input: &str) -> ValidationResult { | (Some(Token::DollarLBrace), Token::RBrace) => {} (Some(left), _) => { return ValidationResult::Invalid(Some(format!( - "Mismatched pairs: {:?} is not properly closed", - left + "Mismatched pairs: {left:?} is not properly closed" ))) } (None, _) => { @@ -460,7 +459,7 @@ impl ReplEditor { } self.errored_on_history_save.store(true, Relaxed); - eprintln!("Unable to save history file: {}", e); + eprintln!("Unable to save history file: {e}"); } } diff --git a/cli/tools/repl/mod.rs b/cli/tools/repl/mod.rs index 780f16a6af393d..a9cb0132baf7c0 100644 --- a/cli/tools/repl/mod.rs +++ b/cli/tools/repl/mod.rs @@ -112,14 +112,11 @@ pub async fn run(flags: Flags, repl_flags: ReplFlags) -> Result { .await; // only output errors if let EvaluationOutput::Error(error_text) = output { - println!( - "Error in --eval-file file \"{}\": {}", - eval_file, error_text - ); + println!("Error in --eval-file file \"{eval_file}\": {error_text}"); } } Err(e) => { - println!("Error in --eval-file file \"{}\": {}", eval_file, e); + println!("Error in --eval-file file \"{eval_file}\": {e}"); } } } @@ -129,7 +126,7 @@ pub async fn run(flags: Flags, repl_flags: ReplFlags) -> Result { let output = repl_session.evaluate_line_and_get_output(&eval).await; // only output errors if let EvaluationOutput::Error(error_text) = output { - println!("Error in --eval flag: {}", error_text); + println!("Error in --eval flag: {error_text}"); } } @@ -166,7 +163,7 @@ pub async fn run(flags: Flags, repl_flags: ReplFlags) -> Result { break; } - println!("{}", output); + println!("{output}"); } Err(ReadlineError::Interrupted) => { if editor.should_exit_on_interrupt() { @@ -180,7 +177,7 @@ pub async fn run(flags: Flags, repl_flags: ReplFlags) -> Result { break; } Err(err) => { - println!("Error: {:?}", err); + println!("Error: {err:?}"); break; } } diff --git a/cli/tools/repl/session.rs b/cli/tools/repl/session.rs index cb7d18c46abeee..e288ab0e6503e6 100644 --- a/cli/tools/repl/session.rs +++ b/cli/tools/repl/session.rs @@ -419,10 +419,7 @@ impl ReplSession { .text; let value = self - .evaluate_expression(&format!( - "'use strict'; void 0;\n{}", - transpiled_src - )) + .evaluate_expression(&format!("'use strict'; void 0;\n{transpiled_src}")) .await?; Ok(TsEvaluateResponse { diff --git a/cli/tools/standalone.rs b/cli/tools/standalone.rs index a0fa29e81e4d3a..72f30aae975e81 100644 --- a/cli/tools/standalone.rs +++ b/cli/tools/standalone.rs @@ -94,7 +94,7 @@ async fn get_base_binary( } let target = target.unwrap_or_else(|| env!("TARGET").to_string()); - let binary_name = format!("deno-{}.zip", target); + let binary_name = format!("deno-{target}.zip"); let binary_path_suffix = if crate::version::is_canary() { format!("canary/{}/{}", crate::version::GIT_COMMIT_HASH, binary_name) @@ -127,7 +127,7 @@ async fn download_base_binary( output_directory: &Path, binary_path_suffix: &str, ) -> Result<(), AnyError> { - let download_url = format!("https://dl.deno.land/{}", binary_path_suffix); + let download_url = format!("https://dl.deno.land/{binary_path_suffix}"); let maybe_bytes = { let progress_bars = ProgressBar::new(ProgressBarStyle::DownloadBars); let progress = progress_bars.update(&download_url); @@ -164,7 +164,7 @@ async fn create_standalone_binary( let ca_data = match ps.options.ca_data() { Some(CaData::File(ca_file)) => { - Some(fs::read(ca_file).with_context(|| format!("Reading: {}", ca_file))?) + Some(fs::read(ca_file).with_context(|| format!("Reading: {ca_file}"))?) } Some(CaData::Bytes(bytes)) => Some(bytes.clone()), None => None, diff --git a/cli/tools/task.rs b/cli/tools/task.rs index 51fd377e4a7d0f..0b611b9d32ee19 100644 --- a/cli/tools/task.rs +++ b/cli/tools/task.rs @@ -56,7 +56,7 @@ pub async fn execute_script( .map(|a| format!("\"{}\"", a.replace('"', "\\\"").replace('$', "\\$"))) .collect::>() .join(" "); - let script = format!("{} {}", script, additional_args); + let script = format!("{script} {additional_args}"); let script = script.trim(); log::info!( "{} {} {}", @@ -65,7 +65,7 @@ pub async fn execute_script( script, ); let seq_list = deno_task_shell::parser::parse(script) - .with_context(|| format!("Error parsing script '{}'.", task_name))?; + .with_context(|| format!("Error parsing script '{task_name}'."))?; // get the starting env vars (the PWD env var will be set by deno_task_shell) let mut env_vars = std::env::vars().collect::>(); @@ -81,7 +81,7 @@ pub async fn execute_script( let exit_code = deno_task_shell::execute(seq_list, env_vars, &cwd).await; Ok(exit_code) } else { - eprintln!("Task not found: {}", task_name); + eprintln!("Task not found: {task_name}"); print_available_tasks(tasks_config); Ok(1) } diff --git a/cli/tools/test.rs b/cli/tools/test.rs index c4c39ede32dbf3..e680d571873c98 100644 --- a/cli/tools/test.rs +++ b/cli/tools/test.rs @@ -323,7 +323,7 @@ impl PrettyTestReporter { if url.scheme() == "file" { if let Some(mut r) = self.cwd.make_relative(&url) { if !r.starts_with("../") { - r = format!("./{}", r); + r = format!("./{r}"); } return r; } @@ -513,7 +513,7 @@ impl PrettyTestReporter { ); print!(" {} ...", root.name); for name in ancestor_names { - print!(" {} ...", name); + print!(" {name} ..."); } print!(" {} ...", description.name); self.in_new_line = false; @@ -584,7 +584,7 @@ impl PrettyTestReporter { } println!("{}\n", colors::white_bold_on_red(" FAILURES ")); for failure_title in failure_titles { - println!("{}", failure_title); + println!("{failure_title}"); } } @@ -600,7 +600,7 @@ impl PrettyTestReporter { } else if count == 1 { " (1 step)".to_string() } else { - format!(" ({} steps)", count) + format!(" ({count} steps)") } }; diff --git a/cli/tools/upgrade.rs b/cli/tools/upgrade.rs index f34a307444e0ee..2caaa0e02956c5 100644 --- a/cli/tools/upgrade.rs +++ b/cli/tools/upgrade.rs @@ -373,7 +373,7 @@ pub async fn upgrade( let archive_data = download_package(client, &download_url) .await - .with_context(|| format!("Failed downloading {}", download_url))?; + .with_context(|| format!("Failed downloading {download_url}"))?; log::info!("Deno is upgrading to version {}", &install_version); @@ -531,7 +531,7 @@ pub fn unpack_into_dir( })? .wait()? } - ext => panic!("Unsupported archive type: '{}'", ext), + ext => panic!("Unsupported archive type: '{ext}'"), }; assert!(unpack_status.success()); assert!(exe_path.exists()); diff --git a/cli/tools/vendor/build.rs b/cli/tools/vendor/build.rs index 830cb39f7f8505..f418670b3a77c6 100644 --- a/cli/tools/vendor/build.rs +++ b/cli/tools/vendor/build.rs @@ -204,19 +204,15 @@ fn build_proxy_module_source( // for simplicity, always include the `export *` statement as it won't error // even when the module does not contain a named export - writeln!(text, "export * from \"{}\";", relative_specifier).unwrap(); + writeln!(text, "export * from \"{relative_specifier}\";").unwrap(); // add a default export if one exists in the module if let Some(parsed_source) = parsed_source_cache.get_parsed_source_from_module(module)? { if has_default_export(&parsed_source) { - writeln!( - text, - "export {{ default }} from \"{}\";", - relative_specifier - ) - .unwrap(); + writeln!(text, "export {{ default }} from \"{relative_specifier}\";") + .unwrap(); } } diff --git a/cli/tools/vendor/import_map.rs b/cli/tools/vendor/import_map.rs index 411a2e059b9ff0..0897cbcf68975c 100644 --- a/cli/tools/vendor/import_map.rs +++ b/cli/tools/vendor/import_map.rs @@ -322,7 +322,7 @@ fn handle_remote_dep_specifier( if is_remote_specifier_text(text) { let base_specifier = mappings.base_specifier(specifier); if !text.starts_with(base_specifier.as_str()) { - panic!("Expected {} to start with {}", text, base_specifier); + panic!("Expected {text} to start with {base_specifier}"); } let sub_path = &text[base_specifier.as_str().len()..]; diff --git a/cli/tools/vendor/mappings.rs b/cli/tools/vendor/mappings.rs index 14705e51ea1b2d..8cf6388d2dd95f 100644 --- a/cli/tools/vendor/mappings.rs +++ b/cli/tools/vendor/mappings.rs @@ -133,9 +133,7 @@ impl Mappings { self .mappings .get(specifier) - .unwrap_or_else(|| { - panic!("Could not find local path for {}", specifier) - }) + .unwrap_or_else(|| panic!("Could not find local path for {specifier}")) .to_path_buf() } } @@ -163,7 +161,7 @@ impl Mappings { .iter() .find(|s| child_specifier.as_str().starts_with(s.as_str())) .unwrap_or_else(|| { - panic!("Could not find base specifier for {}", child_specifier) + panic!("Could not find base specifier for {child_specifier}") }) } diff --git a/cli/tools/vendor/specifiers.rs b/cli/tools/vendor/specifiers.rs index d4f413c31ca0d9..7418bcb8b5c91a 100644 --- a/cli/tools/vendor/specifiers.rs +++ b/cli/tools/vendor/specifiers.rs @@ -45,7 +45,7 @@ pub fn get_unique_path( let mut count = 2; // case insensitive comparison so the output works on case insensitive file systems while !unique_set.insert(path.to_string_lossy().to_lowercase()) { - path = path_with_stem_suffix(&original_path, &format!("_{}", count)); + path = path_with_stem_suffix(&original_path, &format!("_{count}")); count += 1; } path diff --git a/cli/tsc/diagnostics.rs b/cli/tsc/diagnostics.rs index ffb4a946dcd675..461cda77511d6e 100644 --- a/cli/tsc/diagnostics.rs +++ b/cli/tsc/diagnostics.rs @@ -143,7 +143,7 @@ impl From for DiagnosticCategory { 1 => DiagnosticCategory::Error, 2 => DiagnosticCategory::Suggestion, 3 => DiagnosticCategory::Message, - _ => panic!("Unknown value: {}", value), + _ => panic!("Unknown value: {value}"), } } } @@ -212,7 +212,7 @@ impl Diagnostic { }; if !category.is_empty() { - write!(f, "{}[{}]: ", code, category) + write!(f, "{code}[{category}]: ") } else { Ok(()) } @@ -375,12 +375,12 @@ impl fmt::Display for Diagnostics { if i > 0 { write!(f, "\n\n")?; } - write!(f, "{}", item)?; + write!(f, "{item}")?; i += 1; } if i > 1 { - write!(f, "\n\nFound {} errors.", i)?; + write!(f, "\n\nFound {i} errors.")?; } Ok(()) diff --git a/cli/tsc/mod.rs b/cli/tsc/mod.rs index 439a0de20d4ce0..3e7fbfb1528814 100644 --- a/cli/tsc/mod.rs +++ b/cli/tsc/mod.rs @@ -98,7 +98,7 @@ pub fn get_types_declaration_file_text(unstable: bool) -> String { lib_names .into_iter() .map(|name| { - let asset_url = format!("asset:///lib.{}.d.ts", name); + let asset_url = format!("asset:///lib.{name}.d.ts"); assets.remove(&asset_url).unwrap() }) .collect::>() @@ -204,7 +204,7 @@ impl fmt::Display for Stats { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "Compilation statistics:")?; for (key, value) in self.0.clone() { - writeln!(f, " {}: {}", key, value)?; + writeln!(f, " {key}: {value}")?; } Ok(()) @@ -838,7 +838,7 @@ pub fn exec(request: Request) -> Result { "rootNames": root_names, }); let request_str = request_value.to_string(); - let exec_source = format!("globalThis.exec({})", request_str); + let exec_source = format!("globalThis.exec({request_str})"); runtime .execute_script(&located_script_name!(), startup_source) diff --git a/cli/util/checksum.rs b/cli/util/checksum.rs index 73eec19d271e32..38a37259046a6d 100644 --- a/cli/util/checksum.rs +++ b/cli/util/checksum.rs @@ -12,7 +12,7 @@ pub fn gen(v: &[impl AsRef<[u8]>]) -> String { let out: Vec = digest .as_ref() .iter() - .map(|byte| format!("{:02x}", byte)) + .map(|byte| format!("{byte:02x}")) .collect(); out.join("") } diff --git a/cli/util/display.rs b/cli/util/display.rs index ee3d2f2d6af8af..96b6cf84e57ba6 100644 --- a/cli/util/display.rs +++ b/cli/util/display.rs @@ -23,7 +23,7 @@ pub fn human_size(size: f64) -> String { .unwrap() * 1_f64; let unit = units[exponent as usize]; - format!("{}{}{}", negative, pretty_bytes, unit) + format!("{negative}{pretty_bytes}{unit}") } const BYTES_TO_KIB: u64 = 2u64.pow(10); @@ -41,7 +41,7 @@ pub fn human_download_size(byte_count: u64, total_bytes: u64) -> String { fn get_in_format(byte_count: u64, conversion: u64, suffix: &str) -> String { let converted_value = byte_count / conversion; let decimal = (byte_count % conversion) * 100 / conversion; - format!("{}.{:0>2}{}", converted_value, decimal, suffix) + format!("{converted_value}.{decimal:0>2}{suffix}") } } @@ -49,7 +49,7 @@ pub fn human_download_size(byte_count: u64, total_bytes: u64) -> String { /// represents a human readable version of that time. pub fn human_elapsed(elapsed: u128) -> String { if elapsed < 1_000 { - return format!("{}ms", elapsed); + return format!("{elapsed}ms"); } if elapsed < 1_000 * 60 { return format!("{}s", elapsed / 1000); @@ -58,7 +58,7 @@ pub fn human_elapsed(elapsed: u128) -> String { let seconds = elapsed / 1_000; let minutes = seconds / 60; let seconds_remainder = seconds % 60; - format!("{}m{}s", minutes, seconds_remainder) + format!("{minutes}m{seconds_remainder}s") } pub fn write_to_stdout_ignore_sigpipe( diff --git a/cli/util/file_watcher.rs b/cli/util/file_watcher.rs index 29213f0c96b157..05415f2a63edf2 100644 --- a/cli/util/file_watcher.rs +++ b/cli/util/file_watcher.rs @@ -74,7 +74,7 @@ where if let Err(err) = result { let error_string = match err.downcast_ref::() { Some(e) => format_js_error(e), - None => format!("{:?}", err), + None => format!("{err:?}"), }; eprintln!( "{}: {}", @@ -130,7 +130,7 @@ pub struct PrintConfig { fn create_print_after_restart_fn(clear_screen: bool) -> impl Fn() { move || { if clear_screen && atty::is(atty::Stream::Stderr) { - eprint!("{}", CLEAR_SCREEN); + eprint!("{CLEAR_SCREEN}"); } info!( "{} File change detected! Restarting!", diff --git a/cli/util/fs.rs b/cli/util/fs.rs index cb9232f392ba20..777b22c5fe2e4f 100644 --- a/cli/util/fs.rs +++ b/cli/util/fs.rs @@ -29,7 +29,7 @@ pub fn atomic_write_file>( let rand: String = (0..4) .map(|_| format!("{:02x}", rand::random::())) .collect(); - let extension = format!("{}.tmp", rand); + let extension = format!("{rand}.tmp"); let tmp_file = filename.with_extension(extension); write_file(&tmp_file, data, mode)?; std::fs::rename(tmp_file, filename)?; @@ -710,13 +710,13 @@ mod tests { .to_string(); let expected: Vec = [ "http://localhost:8080", - &format!("{}/a.ts", root_dir_url), - &format!("{}/b.js", root_dir_url), - &format!("{}/c.tsx", root_dir_url), - &format!("{}/child/README.md", root_dir_url), - &format!("{}/child/e.mjs", root_dir_url), - &format!("{}/child/f.mjsx", root_dir_url), - &format!("{}/d.jsx", root_dir_url), + &format!("{root_dir_url}/a.ts"), + &format!("{root_dir_url}/b.js"), + &format!("{root_dir_url}/c.tsx"), + &format!("{root_dir_url}/child/README.md"), + &format!("{root_dir_url}/child/e.mjs"), + &format!("{root_dir_url}/child/f.mjsx"), + &format!("{root_dir_url}/d.jsx"), "https://localhost:8080", ] .iter() @@ -748,9 +748,9 @@ mod tests { .unwrap(); let expected: Vec = [ - &format!("{}/child/README.md", root_dir_url), - &format!("{}/child/e.mjs", root_dir_url), - &format!("{}/child/f.mjsx", root_dir_url), + &format!("{root_dir_url}/child/README.md"), + &format!("{root_dir_url}/child/e.mjs"), + &format!("{root_dir_url}/child/f.mjsx"), ] .iter() .map(|f| ModuleSpecifier::parse(f).unwrap()) diff --git a/cli/util/path.rs b/cli/util/path.rs index 76e2a1b6fa9448..d073d80bd5b44b 100644 --- a/cli/util/path.rs +++ b/cli/util/path.rs @@ -64,8 +64,7 @@ pub fn specifier_to_file_path( match result { Ok(path) => Ok(path), Err(()) => Err(uri_error(format!( - "Invalid file path.\n Specifier: {}", - specifier + "Invalid file path.\n Specifier: {specifier}" ))), } } @@ -76,7 +75,7 @@ pub fn ensure_directory_specifier( ) -> ModuleSpecifier { let path = specifier.path(); if !path.ends_with('/') { - let new_path = format!("{}/", path); + let new_path = format!("{path}/"); specifier.set_path(&new_path); } specifier @@ -135,7 +134,7 @@ pub fn relative_specifier( Some(if text.starts_with("../") || text.starts_with("./") { text } else { - format!("./{}", text) + format!("./{text}") }) } @@ -170,12 +169,12 @@ pub fn path_with_stem_suffix(path: &Path, suffix: &str) -> PathBuf { ext )) } else { - path.with_file_name(format!("{}{}.{}", file_stem, suffix, ext)) + path.with_file_name(format!("{file_stem}{suffix}.{ext}")) }; } } - path.with_file_name(format!("{}{}", file_name, suffix)) + path.with_file_name(format!("{file_name}{suffix}")) } else { path.with_file_name(suffix) } @@ -380,9 +379,7 @@ mod test { assert_eq!( actual.as_deref(), expected, - "from: \"{}\" to: \"{}\"", - from_str, - to_str + "from: \"{from_str}\" to: \"{to_str}\"" ); } } diff --git a/cli/util/progress_bar/renderer.rs b/cli/util/progress_bar/renderer.rs index 41a27f3aac4456..0ea275e7731535 100644 --- a/cli/util/progress_bar/renderer.rs +++ b/cli/util/progress_bar/renderer.rs @@ -154,7 +154,7 @@ fn get_elapsed_text(elapsed: Duration) -> String { let elapsed_secs = elapsed.as_secs(); let seconds = elapsed_secs % 60; let minutes = elapsed_secs / 60; - format!("[{:0>2}:{:0>2}]", minutes, seconds) + format!("[{minutes:0>2}:{seconds:0>2}]") } #[cfg(test)] diff --git a/cli/util/text_encoding.rs b/cli/util/text_encoding.rs index bb7d442e927d69..87067e90947c1d 100644 --- a/cli/util/text_encoding.rs +++ b/cli/util/text_encoding.rs @@ -39,7 +39,7 @@ pub fn convert_to_utf8<'a>( .ok_or_else(|| ErrorKind::InvalidData.into()), None => Err(Error::new( ErrorKind::InvalidInput, - format!("Unsupported charset: {}", charset), + format!("Unsupported charset: {charset}"), )), } } diff --git a/cli/util/v8.rs b/cli/util/v8.rs index b6d6aa44ed89ce..6afaf285e3de52 100644 --- a/cli/util/v8.rs +++ b/cli/util/v8.rs @@ -36,7 +36,7 @@ pub fn init_v8_flags(v8_flags: &[String], env_v8_flags: Vec) { .collect::>(); if !unrecognized_v8_flags.is_empty() { for f in unrecognized_v8_flags { - eprintln!("error: V8 did not recognize flag '{}'", f); + eprintln!("error: V8 did not recognize flag '{f}'"); } eprintln!("\nFor a list of V8 flags, use '--v8-flags=--help'"); std::process::exit(1); diff --git a/cli/worker.rs b/cli/worker.rs index 591889ccd9c281..60663ebc034e6f 100644 --- a/cli/worker.rs +++ b/cli/worker.rs @@ -791,10 +791,10 @@ mod tests { let mut worker = create_test_worker(); let result = worker.execute_main_module(&module_specifier).await; if let Err(err) = result { - eprintln!("execute_mod err {:?}", err); + eprintln!("execute_mod err {err:?}"); } if let Err(e) = worker.run_event_loop(false).await { - panic!("Future got unexpected error: {:?}", e); + panic!("Future got unexpected error: {e:?}"); } } @@ -808,10 +808,10 @@ mod tests { let mut worker = create_test_worker(); let result = worker.execute_main_module(&module_specifier).await; if let Err(err) = result { - eprintln!("execute_mod err {:?}", err); + eprintln!("execute_mod err {err:?}"); } if let Err(e) = worker.run_event_loop(false).await { - panic!("Future got unexpected error: {:?}", e); + panic!("Future got unexpected error: {e:?}"); } } diff --git a/core/async_cell.rs b/core/async_cell.rs index f95dc3a84a7a64..a5b8d5467d63e7 100644 --- a/core/async_cell.rs +++ b/core/async_cell.rs @@ -577,7 +577,7 @@ mod internal { pub fn add(self, mode: BorrowMode) -> BorrowCount { match self.try_add(mode) { Some(value) => value, - None => panic!("Can't add {:?} to {:?}", mode, self), + None => panic!("Can't add {mode:?} to {self:?}"), } } @@ -596,7 +596,7 @@ mod internal { pub fn remove(self, mode: BorrowMode) -> BorrowCount { match self.try_remove(mode) { Some(value) => value, - None => panic!("Can't remove {:?} from {:?}", mode, self), + None => panic!("Can't remove {mode:?} from {self:?}"), } } } diff --git a/core/bindings.rs b/core/bindings.rs index bf0da18e4e1cef..d5f38d3c2fb0ac 100644 --- a/core/bindings.rs +++ b/core/bindings.rs @@ -613,8 +613,7 @@ pub fn module_resolve_callback<'s>( } let msg = format!( - r#"Cannot resolve module "{}" from "{}""#, - specifier_str, referrer_name + r#"Cannot resolve module "{specifier_str}" from "{referrer_name}""# ); throw_type_error(scope, msg); None diff --git a/core/error.rs b/core/error.rs index a682c69aac6ebd..79b37d529029ee 100644 --- a/core/error.rs +++ b/core/error.rs @@ -45,7 +45,7 @@ pub fn range_error(message: impl Into>) -> Error { } pub fn invalid_hostname(hostname: &str) -> Error { - type_error(format!("Invalid hostname: '{}'", hostname)) + type_error(format!("Invalid hostname: '{hostname}'")) } pub fn uri_error(message: impl Into>) -> Error { @@ -109,7 +109,7 @@ pub fn to_v8_error<'a>( let cb = cb.open(tc_scope); let this = v8::undefined(tc_scope).into(); let class = v8::String::new(tc_scope, get_class(error)).unwrap(); - let message = v8::String::new(tc_scope, &format!("{:#}", error)).unwrap(); + let message = v8::String::new(tc_scope, &format!("{error:#}")).unwrap(); let mut args = vec![class.into(), message.into()]; if let Some(code) = crate::error_codes::get_error_code(error) { args.push(v8::String::new(tc_scope, code).unwrap().into()); @@ -339,11 +339,11 @@ impl JsError { let message_prop = e.message.clone().unwrap_or_default(); let exception_message = exception_message.unwrap_or_else(|| { if !name.is_empty() && !message_prop.is_empty() { - format!("Uncaught {}: {}", name, message_prop) + format!("Uncaught {name}: {message_prop}") } else if !name.is_empty() { - format!("Uncaught {}", name) + format!("Uncaught {name}") } else if !message_prop.is_empty() { - format!("Uncaught {}", message_prop) + format!("Uncaught {message_prop}") } else { "Uncaught".to_string() } @@ -509,7 +509,7 @@ fn format_source_loc( ) -> String { let line_number = line_number; let column_number = column_number; - format!("{}:{}:{}", file_name, line_number, column_number) + format!("{file_name}:{line_number}:{column_number}") } impl Display for JsError { @@ -517,7 +517,7 @@ impl Display for JsError { if let Some(stack) = &self.stack { let stack_lines = stack.lines(); if stack_lines.count() > 1 { - return write!(f, "{}", stack); + return write!(f, "{stack}"); } } write!(f, "{}", self.exception_message)?; @@ -527,7 +527,7 @@ impl Display for JsError { (&frame.file_name, frame.line_number, frame.column_number) { let source_loc = format_source_loc(f_, l, c); - write!(f, "\n at {}", source_loc)?; + write!(f, "\n at {source_loc}")?; } } Ok(()) @@ -568,8 +568,8 @@ pub(crate) fn to_v8_type_error( /// of `instanceof`. `Value::is_native_error()` also checks for static class /// inheritance rather than just scanning the prototype chain, which doesn't /// work with our WebIDL implementation of `DOMException`. -pub(crate) fn is_instance_of_error<'s>( - scope: &mut v8::HandleScope<'s>, +pub(crate) fn is_instance_of_error( + scope: &mut v8::HandleScope, value: v8::Local, ) -> bool { if !value.is_object() { @@ -603,8 +603,8 @@ pub(crate) fn is_instance_of_error<'s>( /// NOTE: There is currently no way to detect `AggregateError` via `rusty_v8`, /// as v8 itself doesn't expose `v8__Exception__AggregateError`, /// and we cannot create bindings for it. This forces us to rely on `name` inference. -pub(crate) fn is_aggregate_error<'s>( - scope: &mut v8::HandleScope<'s>, +pub(crate) fn is_aggregate_error( + scope: &mut v8::HandleScope, value: v8::Local, ) -> bool { let mut maybe_prototype = Some(value); diff --git a/core/examples/eval_js_value.rs b/core/examples/eval_js_value.rs index 7bb954371a32b4..6990abb85667c9 100644 --- a/core/examples/eval_js_value.rs +++ b/core/examples/eval_js_value.rs @@ -18,7 +18,7 @@ fn main() { let output: serde_json::Value = eval(&mut runtime, code).expect("Eval failed"); - println!("Output: {:?}", output); + println!("Output: {output:?}"); let expected_output = serde_json::json!(10); assert_eq!(expected_output, output); @@ -40,9 +40,9 @@ fn eval( match deserialized_value { Ok(value) => Ok(value), - Err(err) => Err(format!("Cannot deserialize value: {:?}", err)), + Err(err) => Err(format!("Cannot deserialize value: {err:?}")), } } - Err(err) => Err(format!("Evaling error: {:?}", err)), + Err(err) => Err(format!("Evaling error: {err:?}")), } } diff --git a/core/examples/fs_module_loader.rs b/core/examples/fs_module_loader.rs index 620204c601321e..a8d33e104d3941 100644 --- a/core/examples/fs_module_loader.rs +++ b/core/examples/fs_module_loader.rs @@ -13,7 +13,7 @@ fn main() -> Result<(), Error> { std::process::exit(1); } let main_url = &args[1]; - println!("Run {}", main_url); + println!("Run {main_url}"); let mut js_runtime = JsRuntime::new(RuntimeOptions { module_loader: Some(Rc::new(FsModuleLoader)), diff --git a/core/examples/schedule_task.rs b/core/examples/schedule_task.rs index 6a61619d874258..56c8f6dd66688b 100644 --- a/core/examples/schedule_task.rs +++ b/core/examples/schedule_task.rs @@ -65,7 +65,7 @@ fn main() { #[op] fn op_schedule_task(state: &mut OpState, i: u8) -> Result<(), Error> { let tx = state.borrow_mut::>(); - tx.unbounded_send(Box::new(move || println!("Hello, world! x{}", i))) + tx.unbounded_send(Box::new(move || println!("Hello, world! x{i}"))) .expect("unbounded_send failed"); Ok(()) } diff --git a/core/examples/ts_module_loader.rs b/core/examples/ts_module_loader.rs index c78c1f868757d2..82a3c1079d5352 100644 --- a/core/examples/ts_module_loader.rs +++ b/core/examples/ts_module_loader.rs @@ -99,7 +99,7 @@ fn main() -> Result<(), Error> { std::process::exit(1); } let main_url = &args[1]; - println!("Run {}", main_url); + println!("Run {main_url}"); let mut js_runtime = JsRuntime::new(RuntimeOptions { module_loader: Some(Rc::new(TypescriptModuleLoader)), diff --git a/core/module_specifier.rs b/core/module_specifier.rs index 832208758d2fd6..c65f34110521f0 100644 --- a/core/module_specifier.rs +++ b/core/module_specifier.rs @@ -32,17 +32,17 @@ impl Error for ModuleResolutionError { impl fmt::Display for ModuleResolutionError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - InvalidUrl(ref err) => write!(f, "invalid URL: {}", err), + InvalidUrl(ref err) => write!(f, "invalid URL: {err}"), InvalidBaseUrl(ref err) => { - write!(f, "invalid base URL for relative import: {}", err) + write!(f, "invalid base URL for relative import: {err}") } - InvalidPath(ref path) => write!(f, "invalid module path: {:?}", path), + InvalidPath(ref path) => write!(f, "invalid module path: {path:?}"), ImportPrefixMissing(ref specifier, ref maybe_referrer) => write!( f, "Relative import path \"{}\" not prefixed with / or ./ or ../{}", specifier, match maybe_referrer { - Some(referrer) => format!(" from \"{}\"", referrer), + Some(referrer) => format!(" from \"{referrer}\""), None => String::new(), } ), @@ -425,7 +425,7 @@ mod tests { ]); // Relative local path. - let expected_url = format!("file://{}/tests/006_url_imports.ts", cwd_str); + let expected_url = format!("file://{cwd_str}/tests/006_url_imports.ts"); tests.extend(vec![ ("tests/006_url_imports.ts", expected_url.to_string()), ("./tests/006_url_imports.ts", expected_url.to_string()), diff --git a/core/modules.rs b/core/modules.rs index 6ce9f4614fd175..9a7445959531dc 100644 --- a/core/modules.rs +++ b/core/modules.rs @@ -51,7 +51,7 @@ pub(crate) fn validate_import_assertions( if key == "type" && !SUPPORTED_TYPE_ASSERTIONS.contains(&value.as_str()) { let message = v8::String::new( scope, - &format!("\"{}\" is not a valid module type.", value), + &format!("\"{value}\" is not a valid module type."), ) .unwrap(); let exception = v8::Exception::type_error(scope, message); @@ -318,8 +318,7 @@ impl ModuleLoader for FsModuleLoader { async move { let path = module_specifier.to_file_path().map_err(|_| { generic_error(format!( - "Provided module specifier \"{}\" is not a file URL.", - module_specifier + "Provided module specifier \"{module_specifier}\" is not a file URL." )) })?; let module_type = if let Some(extension) = path.extension() { @@ -1483,6 +1482,7 @@ import "/a.js"; let a_id_fut = runtime.load_main_module(&spec, None); let a_id = futures::executor::block_on(a_id_fut).unwrap(); + #[allow(clippy::let_underscore_future)] let _ = runtime.mod_evaluate(a_id); futures::executor::block_on(runtime.run_event_loop(false)).unwrap(); let l = loads.lock(); @@ -1662,6 +1662,7 @@ import "/a.js"; runtime.instantiate_module(mod_a).unwrap(); assert_eq!(DISPATCH_COUNT.load(Ordering::Relaxed), 0); + #[allow(clippy::let_underscore_future)] let _ = runtime.mod_evaluate(mod_a); assert_eq!(DISPATCH_COUNT.load(Ordering::Relaxed), 1); } @@ -2042,6 +2043,7 @@ import "/a.js"; let result = runtime.load_main_module(&spec, None).await; assert!(result.is_ok()); let circular1_id = result.unwrap(); + #[allow(clippy::let_underscore_future)] let _ = runtime.mod_evaluate(circular1_id); runtime.run_event_loop(false).await.unwrap(); @@ -2122,6 +2124,7 @@ import "/a.js"; let result = runtime.load_main_module(&spec, None).await; assert!(result.is_ok()); let redirect1_id = result.unwrap(); + #[allow(clippy::let_underscore_future)] let _ = runtime.mod_evaluate(redirect1_id); runtime.run_event_loop(false).await.unwrap(); let l = loads.lock(); @@ -2280,6 +2283,7 @@ if (import.meta.url != 'file:///main_with_code.js') throw Error(); .boxed_local(); let main_id = futures::executor::block_on(main_id_fut).unwrap(); + #[allow(clippy::let_underscore_future)] let _ = runtime.mod_evaluate(main_id); futures::executor::block_on(runtime.run_event_loop(false)).unwrap(); @@ -2397,6 +2401,7 @@ if (import.meta.url != 'file:///main_with_code.js') throw Error(); .boxed_local(); let main_id = futures::executor::block_on(main_id_fut).unwrap(); + #[allow(clippy::let_underscore_future)] let _ = runtime.mod_evaluate(main_id); futures::executor::block_on(runtime.run_event_loop(false)).unwrap(); @@ -2412,6 +2417,7 @@ if (import.meta.url != 'file:///main_with_code.js') throw Error(); .boxed_local(); let side_id = futures::executor::block_on(side_id_fut).unwrap(); + #[allow(clippy::let_underscore_future)] let _ = runtime.mod_evaluate(side_id); futures::executor::block_on(runtime.run_event_loop(false)).unwrap(); } @@ -2440,6 +2446,7 @@ if (import.meta.url != 'file:///main_with_code.js') throw Error(); .boxed_local(); let main_id = futures::executor::block_on(main_id_fut).unwrap(); + #[allow(clippy::let_underscore_future)] let _ = runtime.mod_evaluate(main_id); futures::executor::block_on(runtime.run_event_loop(false)).unwrap(); runtime.snapshot() @@ -2479,6 +2486,7 @@ if (import.meta.url != 'file:///main_with_code.js') throw Error(); .boxed_local(); let main_id = futures::executor::block_on(main_id_fut).unwrap(); + #[allow(clippy::let_underscore_future)] let _ = runtime.mod_evaluate(main_id); futures::executor::block_on(runtime.run_event_loop(false)).unwrap(); runtime.snapshot() diff --git a/core/ops.rs b/core/ops.rs index 098de8c9353f4e..ca465c821e28e9 100644 --- a/core/ops.rs +++ b/core/ops.rs @@ -134,7 +134,7 @@ impl OpError { pub fn new(get_class: GetErrorClassFn, err: Error) -> Self { Self { class_name: (get_class)(&err), - message: format!("{:#}", err), + message: format!("{err:#}"), code: crate::error_codes::get_error_code(&err), } } diff --git a/core/ops_builtin_v8.rs b/core/ops_builtin_v8.rs index 225a81901fed90..a94f8a50b7321a 100644 --- a/core/ops_builtin_v8.rs +++ b/core/ops_builtin_v8.rs @@ -471,7 +471,7 @@ fn op_serialize( if buf.was_detached() { return Err(custom_error( "DOMExceptionOperationError", - format!("ArrayBuffer at index {} is already detached", index), + format!("ArrayBuffer at index {index} is already detached"), )); } @@ -593,8 +593,8 @@ fn op_get_promise_details<'a>( } #[op(v8)] -fn op_set_promise_hooks<'a>( - scope: &mut v8::HandleScope<'a>, +fn op_set_promise_hooks( + scope: &mut v8::HandleScope, init_cb: serde_v8::Value, before_cb: serde_v8::Value, after_cb: serde_v8::Value, diff --git a/core/runtime.rs b/core/runtime.rs index 0788cc08c925d2..29a6ca450b7aeb 100644 --- a/core/runtime.rs +++ b/core/runtime.rs @@ -435,12 +435,11 @@ impl JsRuntime { match err { v8::DataError::BadType { actual, expected } => { panic!( - "Invalid type for snapshot data: expected {}, got {}", - expected, actual + "Invalid type for snapshot data: expected {expected}, got {actual}" ); } v8::DataError::NoData { expected } => { - panic!("No data for snapshot data: expected {}", expected); + panic!("No data for snapshot data: expected {expected}"); } } } @@ -1528,8 +1527,8 @@ impl JsRuntimeState { } } -pub(crate) fn exception_to_err_result<'s, T>( - scope: &mut v8::HandleScope<'s>, +pub(crate) fn exception_to_err_result( + scope: &mut v8::HandleScope, exception: v8::Local, in_promise: bool, ) -> Result { @@ -3393,6 +3392,7 @@ pub mod tests { ) .unwrap(); + #[allow(clippy::let_underscore_future)] let _ = runtime.mod_evaluate(module_id); let module_namespace = runtime.get_module_namespace(module_id).unwrap(); @@ -3570,6 +3570,7 @@ pub mod tests { }; assert_eq!(i, id); + #[allow(clippy::let_underscore_future)] let _ = runtime.mod_evaluate(id); futures::executor::block_on(runtime.run_event_loop(false)).unwrap(); @@ -3622,6 +3623,7 @@ pub mod tests { ) .unwrap(); + #[allow(clippy::let_underscore_future)] let _ = runtime.mod_evaluate(id); futures::executor::block_on(runtime.run_event_loop(false)).unwrap(); @@ -3820,7 +3822,7 @@ Deno.core.initializeAsyncOps(); match runtime.poll_value(&promise, cx) { Poll::Ready(Ok(_)) => {} - Poll::Ready(Err(err)) => panic!("{:?}", err), + Poll::Ready(Err(err)) => panic!("{err:?}"), _ => panic!(), } }) @@ -4344,9 +4346,7 @@ Deno.core.ops.op_async_serialize_object_with_numbers_as_keys({ globalThis.rejectValue = `{realm_name}/${{reason}}`; }}); Deno.core.ops.op_void_async().then(() => Promise.reject({number})); - "#, - realm_name=realm_name, - number=number + "# ), ) .unwrap(); @@ -4362,7 +4362,7 @@ Deno.core.ops.op_async_serialize_object_with_numbers_as_keys({ let reject_value = v8::Local::new(scope, reject_value); assert!(reject_value.is_string()); let reject_value_string = reject_value.to_rust_string_lossy(scope); - assert_eq!(reject_value_string, format!("{}/{}", realm_name, number)); + assert_eq!(reject_value_string, format!("{realm_name}/{number}")); } } diff --git a/ext/fetch/lib.rs b/ext/fetch/lib.rs index 4a19650cbf65d2..7f0a5e37e8bbb5 100644 --- a/ext/fetch/lib.rs +++ b/ext/fetch/lib.rs @@ -231,8 +231,7 @@ where if method != Method::GET { return Err(type_error(format!( - "Fetching files only supports the GET method. Received {}.", - method + "Fetching files only supports the GET method. Received {method}." ))); } @@ -347,11 +346,11 @@ where } "data" => { let data_url = DataUrl::process(url.as_str()) - .map_err(|e| type_error(format!("{:?}", e)))?; + .map_err(|e| type_error(format!("{e:?}")))?; let (body, _) = data_url .decode_to_vec() - .map_err(|e| type_error(format!("{:?}", e)))?; + .map_err(|e| type_error(format!("{e:?}")))?; let response = http::Response::builder() .status(http::StatusCode::OK) @@ -371,7 +370,7 @@ where // because the URL isn't an object URL. return Err(type_error("Blob for the given URL not found.")); } - _ => return Err(type_error(format!("scheme '{}' not supported", scheme))), + _ => return Err(type_error(format!("scheme '{scheme}' not supported"))), }; Ok(FetchReturn { diff --git a/ext/ffi/dlfcn.rs b/ext/ffi/dlfcn.rs index a6b870c3016f55..570af09fce215d 100644 --- a/ext/ffi/dlfcn.rs +++ b/ext/ffi/dlfcn.rs @@ -46,8 +46,7 @@ impl DynamicLibraryResource { match unsafe { self.lib.symbol::<*const c_void>(&symbol) } { Ok(value) => Ok(Ok(value)), Err(err) => Err(generic_error(format!( - "Failed to register symbol {}: {}", - symbol, err + "Failed to register symbol {symbol}: {err}" ))), }? } @@ -156,8 +155,7 @@ where match unsafe { resource.lib.symbol::<*const c_void>(symbol) } { Ok(value) => Ok(value), Err(err) => Err(generic_error(format!( - "Failed to register symbol {}: {}", - symbol, err + "Failed to register symbol {symbol}: {err}" ))), }?; let ptr = libffi::middle::CodePtr::from_ptr(fn_ptr as _); diff --git a/ext/ffi/lib.rs b/ext/ffi/lib.rs index 64d7314914f9dd..d97bb16b4f3e88 100644 --- a/ext/ffi/lib.rs +++ b/ext/ffi/lib.rs @@ -60,8 +60,7 @@ fn check_unstable(state: &OpState, api_name: &str) { if !unstable.0 { eprintln!( - "Unstable API '{}'. The --unstable flag must be provided.", - api_name + "Unstable API '{api_name}'. The --unstable flag must be provided." ); std::process::exit(70); } diff --git a/ext/flash/lib.rs b/ext/flash/lib.rs index 7a7849be1d274a..92490e0b8f34af 100644 --- a/ext/flash/lib.rs +++ b/ext/flash/lib.rs @@ -723,7 +723,7 @@ fn op_flash_first_packet( return Ok(Some(buf.into())); } Err(e) => { - return Err(type_error(format!("{}", e))); + return Err(type_error(format!("{e}"))); } } } @@ -773,7 +773,7 @@ async fn op_flash_read_body( return n; } Err(e) if e.kind() == std::io::ErrorKind::InvalidInput => { - panic!("chunked read error: {}", e); + panic!("chunked read error: {e}"); } Err(_) => { drop(_lock); @@ -1493,8 +1493,7 @@ fn check_unstable(state: &OpState, api_name: &str) { if !unstable.0 { eprintln!( - "Unstable API '{}'. The --unstable flag must be provided.", - api_name + "Unstable API '{api_name}'. The --unstable flag must be provided." ); std::process::exit(70); } diff --git a/ext/http/lib.rs b/ext/http/lib.rs index f1371ffece2bf3..d6450bb69a8fef 100644 --- a/ext/http/lib.rs +++ b/ext/http/lib.rs @@ -746,7 +746,7 @@ fn ensure_vary_accept_encoding(hmap: &mut hyper::HeaderMap) { if let Some(v) = hmap.get_mut(hyper::header::VARY) { if let Ok(s) = v.to_str() { if !s.to_lowercase().contains("accept-encoding") { - *v = format!("Accept-Encoding, {}", s).try_into().unwrap() + *v = format!("Accept-Encoding, {s}").try_into().unwrap() } return; } @@ -935,7 +935,7 @@ async fn op_http_shutdown( fn op_http_websocket_accept_header(key: String) -> Result { let digest = ring::digest::digest( &ring::digest::SHA1_FOR_LEGACY_USE_ONLY, - format!("{}258EAFA5-E914-47DA-95CA-C5AB0DC85B11", key).as_bytes(), + format!("{key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11").as_bytes(), ); Ok(base64::encode(digest)) } diff --git a/ext/net/lib.rs b/ext/net/lib.rs index 64e28fd00b6ac4..ad5b97a7a44935 100644 --- a/ext/net/lib.rs +++ b/ext/net/lib.rs @@ -45,8 +45,7 @@ impl UnstableChecker { pub fn check_unstable(&self, api_name: &str) { if !self.unstable { eprintln!( - "Unstable API '{}'. The --unstable flag must be provided.", - api_name + "Unstable API '{api_name}'. The --unstable flag must be provided." ); std::process::exit(70); } diff --git a/ext/net/ops.rs b/ext/net/ops.rs index 259703d1753eda..1d84a106768ac4 100644 --- a/ext/net/ops.rs +++ b/ext/net/ops.rs @@ -488,7 +488,7 @@ where .lookup(query, record_type) .await .map_err(|e| { - let message = format!("{}", e); + let message = format!("{e}"); match e.kind() { ResolveErrorKind::NoRecordsFound { .. } => { custom_error("NotFound", message) diff --git a/ext/net/ops_unix.rs b/ext/net/ops_unix.rs index d2933a573030ca..1161d275921b03 100644 --- a/ext/net/ops_unix.rs +++ b/ext/net/ops_unix.rs @@ -27,7 +27,7 @@ pub use tokio::net::UnixStream; /// A utility function to map OsStrings to Strings pub fn into_string(s: std::ffi::OsString) -> Result { s.into_string().map_err(|s| { - let message = format!("File name or path {:?} is not valid UTF-8", s); + let message = format!("File name or path {s:?} is not valid UTF-8"); custom_error("InvalidData", message) }) } diff --git a/ext/node/errors.rs b/ext/node/errors.rs index 9158ab0c5262a1..bad6696bae436d 100644 --- a/ext/node/errors.rs +++ b/ext/node/errors.rs @@ -13,12 +13,11 @@ pub fn err_invalid_module_specifier( maybe_base: Option, ) -> AnyError { let mut msg = format!( - "[ERR_INVALID_MODULE_SPECIFIER] Invalid module \"{}\" {}", - request, reason + "[ERR_INVALID_MODULE_SPECIFIER] Invalid module \"{request}\" {reason}" ); if let Some(base) = maybe_base { - msg = format!("{} imported from {}", msg, base); + msg = format!("{msg} imported from {base}"); } type_error(msg) @@ -30,17 +29,15 @@ pub fn err_invalid_package_config( maybe_base: Option, maybe_message: Option, ) -> AnyError { - let mut msg = format!( - "[ERR_INVALID_PACKAGE_CONFIG] Invalid package config {}", - path - ); + let mut msg = + format!("[ERR_INVALID_PACKAGE_CONFIG] Invalid package config {path}"); if let Some(base) = maybe_base { - msg = format!("{} while importing {}", msg, base); + msg = format!("{msg} while importing {base}"); } if let Some(message) = maybe_message { - msg = format!("{}. {}", msg, message); + msg = format!("{msg}. {message}"); } generic_error(msg) @@ -49,8 +46,7 @@ pub fn err_invalid_package_config( #[allow(unused)] pub fn err_module_not_found(path: &str, base: &str, typ: &str) -> AnyError { generic_error(format!( - "[ERR_MODULE_NOT_FOUND] Cannot find {} \"{}\" imported from \"{}\"", - typ, path, base + "[ERR_MODULE_NOT_FOUND] Cannot find {typ} \"{path}\" imported from \"{base}\"" )) } @@ -86,10 +82,10 @@ pub fn err_invalid_package_target( }; if let Some(base) = maybe_referrer { - msg = format!("{} imported from {}", msg, base); + msg = format!("{msg} imported from {base}"); }; if rel_error { - msg = format!("{}; target must start with \"./\"", msg); + msg = format!("{msg}; target must start with \"./\""); } generic_error(msg) @@ -116,16 +112,14 @@ pub fn err_package_path_not_exported( } if subpath == "." { - msg = format!( - "{} No \"exports\" main defined in '{}package.json'", - msg, pkg_path - ); + msg = + format!("{msg} No \"exports\" main defined in '{pkg_path}package.json'"); } else { - msg = format!("{} Package subpath '{}' is not defined by \"exports\" in '{}package.json'", msg, subpath, pkg_path); + msg = format!("{msg} Package subpath '{subpath}' is not defined by \"exports\" in '{pkg_path}package.json'"); }; if let Some(referrer) = maybe_referrer { - msg = format!("{} imported from '{}'", msg, referrer); + msg = format!("{msg} imported from '{referrer}'"); } generic_error(msg) @@ -137,21 +131,20 @@ pub fn err_package_import_not_defined( base: &str, ) -> AnyError { let mut msg = format!( - "[ERR_PACKAGE_IMPORT_NOT_DEFINED] Package import specifier \"{}\" is not defined in", - specifier + "[ERR_PACKAGE_IMPORT_NOT_DEFINED] Package import specifier \"{specifier}\" is not defined in" ); if let Some(package_path) = package_path { - msg = format!("{} in package {}package.json", msg, package_path); + msg = format!("{msg} in package {package_path}package.json"); } - msg = format!("{} imported from {}", msg, base); + msg = format!("{msg} imported from {base}"); type_error(msg) } pub fn err_unsupported_dir_import(path: &str, base: &str) -> AnyError { - generic_error(format!("[ERR_UNSUPPORTED_DIR_IMPORT] Directory import '{}' is not supported resolving ES modules imported from {}", path, base)) + generic_error(format!("[ERR_UNSUPPORTED_DIR_IMPORT] Directory import '{path}' is not supported resolving ES modules imported from {base}")) } pub fn err_unsupported_esm_url_scheme(url: &Url) -> AnyError { @@ -160,10 +153,8 @@ pub fn err_unsupported_esm_url_scheme(url: &Url) -> AnyError { .to_string(); if cfg!(window) && url.scheme().len() == 2 { - msg = format!( - "{}. On Windows, absolute path must be valid file:// URLs", - msg - ); + msg = + format!("{msg}. On Windows, absolute path must be valid file:// URLs"); } msg = format!("{}. Received protocol '{}'", msg, url.scheme()); diff --git a/ext/node/lib.rs b/ext/node/lib.rs index 3eda1895852cc6..3c0e323086f4f3 100644 --- a/ext/node/lib.rs +++ b/ext/node/lib.rs @@ -69,7 +69,7 @@ pub static NODE_GLOBAL_THIS_NAME: Lazy = Lazy::new(|| { .unwrap() .as_secs(); // use a changing variable name to make it hard to depend on this - format!("__DENO_NODE_GLOBAL_THIS_{}__", seconds) + format!("__DENO_NODE_GLOBAL_THIS_{seconds}__") }); pub static NODE_ENV_VAR_ALLOWLIST: Lazy> = Lazy::new(|| { @@ -497,7 +497,7 @@ where if request == pkg_name { // pass - } else if request.starts_with(&format!("{}/", pkg_name)) { + } else if request.starts_with(&format!("{pkg_name}/")) { expansion += &request[pkg_name.len()..]; } else { return Ok(None); @@ -579,7 +579,7 @@ where let referrer = Url::from_file_path(parent_path).unwrap(); resolution::package_exports_resolve( &pkg.path, - format!(".{}", expansion), + format!(".{expansion}"), exports, &referrer, NodeModuleKind::Cjs, diff --git a/ext/node/resolution.rs b/ext/node/resolution.rs index 81a2521b5644f3..ccd272741c68c1 100644 --- a/ext/node/resolution.rs +++ b/ext/node/resolution.rs @@ -117,7 +117,7 @@ pub fn with_known_extension(path: &Path, ext: &str) -> PathBuf { Some(period_index) => &file_name[..period_index], None => &file_name, }; - path.with_file_name(format!("{}.{}", file_name, ext)) + path.with_file_name(format!("{file_name}.{ext}")) } fn to_specifier_display_string(url: &ModuleSpecifier) -> String { @@ -350,7 +350,7 @@ fn resolve_package_target_string( .replace(&target, |_caps: ®ex::Captures| subpath.clone()) .to_string() } else { - format!("{}{}", target, subpath) + format!("{target}{subpath}") }; let package_json_url = ModuleSpecifier::from_file_path(package_json_path).unwrap(); @@ -404,7 +404,7 @@ fn resolve_package_target_string( let request = if pattern { match_.replace('*', &subpath) } else { - format!("{}{}", match_, subpath) + format!("{match_}{subpath}") }; return Err(throw_invalid_subpath( request, @@ -915,7 +915,7 @@ pub fn legacy_main_resolve( .path .parent() .unwrap() - .join(format!("{}{}", main, ending)) + .join(format!("{main}{ending}")) .clean(); if file_exists(&guess) { // TODO(bartlomieju): emitLegacyIndexDeprecation() diff --git a/ext/web/blob.rs b/ext/web/blob.rs index b43b3d17bab74a..1a799279216753 100644 --- a/ext/web/blob.rs +++ b/ext/web/blob.rs @@ -66,7 +66,7 @@ impl BlobStore { "null".to_string() }; let id = Uuid::new_v4(); - let url = Url::parse(&format!("blob:{}/{}", origin, id)).unwrap(); + let url = Url::parse(&format!("blob:{origin}/{id}")).unwrap(); let mut blob_store = self.object_urls.lock(); blob_store.insert(url.clone(), Arc::new(blob)); diff --git a/ext/web/lib.rs b/ext/web/lib.rs index 92cfcceeb91cbf..ac3fe59feee1f6 100644 --- a/ext/web/lib.rs +++ b/ext/web/lib.rs @@ -175,8 +175,7 @@ fn op_encoding_normalize_label(label: String) -> Result { let encoding = Encoding::for_label_no_replacement(label.as_bytes()) .ok_or_else(|| { range_error(format!( - "The encoding label provided ('{}') is invalid.", - label + "The encoding label provided ('{label}') is invalid." )) })?; Ok(encoding.name().to_lowercase()) @@ -224,8 +223,7 @@ fn op_encoding_decode_single( ) -> Result { let encoding = Encoding::for_label(label.as_bytes()).ok_or_else(|| { range_error(format!( - "The encoding label provided ('{}') is invalid.", - label + "The encoding label provided ('{label}') is invalid." )) })?; @@ -278,8 +276,7 @@ fn op_encoding_new_decoder( ) -> Result { let encoding = Encoding::for_label(label.as_bytes()).ok_or_else(|| { range_error(format!( - "The encoding label provided ('{}') is invalid.", - label + "The encoding label provided ('{label}') is invalid." )) })?; diff --git a/ext/webgpu/src/lib.rs b/ext/webgpu/src/lib.rs index 9ee220dd033bd0..d1fb55dbf6ce34 100644 --- a/ext/webgpu/src/lib.rs +++ b/ext/webgpu/src/lib.rs @@ -73,8 +73,7 @@ fn check_unstable(state: &OpState, api_name: &str) { let unstable = state.borrow::(); if !unstable.0 { eprintln!( - "Unstable API '{}'. The --unstable flag must be provided.", - api_name + "Unstable API '{api_name}'. The --unstable flag must be provided." ); std::process::exit(70); } diff --git a/ext/websocket/lib.rs b/ext/websocket/lib.rs index 8123f84fc5238f..baf5c396cc9143 100644 --- a/ext/websocket/lib.rs +++ b/ext/websocket/lib.rs @@ -321,7 +321,7 @@ where Some("ws") => 80, _ => unreachable!(), }); - let addr = format!("{}:{}", domain, port); + let addr = format!("{domain}:{port}"); let tcp_socket = TcpStream::connect(addr).await?; let socket: MaybeTlsStream = match uri.scheme_str() { @@ -359,8 +359,7 @@ where } .map_err(|err| { DomExceptionNetworkError::new(&format!( - "failed to connect to WebSocket: {}", - err + "failed to connect to WebSocket: {err}" )) })?; diff --git a/lockfile/lib.rs b/lockfile/lib.rs index eb1009e8ad06f6..ec91def1596111 100644 --- a/lockfile/lib.rs +++ b/lockfile/lib.rs @@ -32,7 +32,7 @@ fn gen_checksum(v: &[impl AsRef<[u8]>]) -> String { let out: Vec = digest .as_ref() .iter() - .map(|byte| format!("{:02x}", byte)) + .map(|byte| format!("{byte:02x}")) .collect(); out.join("") } diff --git a/ops/fast_call.rs b/ops/fast_call.rs index de11b389bb8b1f..9093190b287ec8 100644 --- a/ops/fast_call.rs +++ b/ops/fast_call.rs @@ -68,9 +68,9 @@ pub(crate) fn generate( // - op_foo_fast, the fast call type. // - op_foo_fast_fn, the fast call function. let ident = item_fn.sig.ident.clone(); - let fast_ident = Ident::new(&format!("{}_fast", ident), Span::call_site()); + let fast_ident = Ident::new(&format!("{ident}_fast"), Span::call_site()); let fast_fn_ident = - Ident::new(&format!("{}_fast_fn", ident), Span::call_site()); + Ident::new(&format!("{ident}_fast_fn"), Span::call_site()); // Deal with generics. let generics = &item_fn.sig.generics; diff --git a/ops/optimizer.rs b/ops/optimizer.rs index 1a6172b676de16..82593d2473c77d 100644 --- a/ops/optimizer.rs +++ b/ops/optimizer.rs @@ -735,7 +735,7 @@ mod tests { let mut op = Op::new(item, attrs); let mut optimizer = Optimizer::new(); if let Err(e) = optimizer.analyze(&mut op) { - let e_str = format!("{:?}", e); + let e_str = format!("{e:?}"); if update_expected { std::fs::write(input.with_extension("expected"), e_str) .expect("Failed to write expected file"); @@ -748,11 +748,11 @@ mod tests { if update_expected { std::fs::write( input.with_extension("expected"), - format!("{:#?}", optimizer), + format!("{optimizer:#?}"), ) .expect("Failed to write expected file"); } else { - assert_eq!(format!("{:#?}", optimizer), expected); + assert_eq!(format!("{optimizer:#?}"), expected); } } } diff --git a/runtime/build.rs b/runtime/build.rs index 3be20ad97c5b84..10490a87160328 100644 --- a/runtime/build.rs +++ b/runtime/build.rs @@ -1,12 +1,14 @@ // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. use std::env; -use std::path::Path; + use std::path::PathBuf; // This is a shim that allows to generate documentation on docs.rs #[cfg(not(feature = "docsrs"))] mod not_docs { + use std::path::Path; + use super::*; use deno_cache::SqliteBackedCache; use deno_core::snapshot_util::*; @@ -198,7 +200,6 @@ fn main() { if env::var_os("DOCS_RS").is_some() { let snapshot_slice = &[]; std::fs::write(&runtime_snapshot_path, snapshot_slice).unwrap(); - return; } #[cfg(not(feature = "docsrs"))] diff --git a/runtime/fmt_errors.rs b/runtime/fmt_errors.rs index e8c31629096a95..62764965d14a93 100644 --- a/runtime/fmt_errors.rs +++ b/runtime/fmt_errors.rs @@ -93,18 +93,18 @@ fn format_frame(frame: &JsStackFrame) -> String { if let Some(function_name) = &frame.function_name { if let Some(type_name) = &frame.type_name { if !function_name.starts_with(type_name) { - write!(formatted_method, "{}.", type_name).unwrap(); + write!(formatted_method, "{type_name}.").unwrap(); } } formatted_method += function_name; if let Some(method_name) = &frame.method_name { if !function_name.ends_with(method_name) { - write!(formatted_method, " [as {}]", method_name).unwrap(); + write!(formatted_method, " [as {method_name}]").unwrap(); } } } else { if let Some(type_name) = &frame.type_name { - write!(formatted_method, "{}.", type_name).unwrap(); + write!(formatted_method, "{type_name}.").unwrap(); } if let Some(method_name) = &frame.method_name { formatted_method += method_name @@ -149,7 +149,7 @@ fn format_maybe_source_line( return "".to_string(); } if source_line.contains("Couldn't format source line: ") { - return format!("\n{}", source_line); + return format!("\n{source_line}"); } let mut s = String::new(); @@ -178,7 +178,7 @@ fn format_maybe_source_line( let indent = format!("{:indent$}", "", indent = level); - format!("\n{}{}\n{}{}", indent, source_line, indent, color_underline) + format!("\n{indent}{source_line}\n{indent}{color_underline}") } fn find_recursive_cause(js_error: &JsError) -> Option { @@ -227,7 +227,7 @@ fn format_aggregated_error( ); for line in error_string.trim_start_matches("Uncaught ").lines() { - write!(s, "\n {}", line).unwrap(); + write!(s, "\n {line}").unwrap(); } } diff --git a/runtime/inspector_server.rs b/runtime/inspector_server.rs index 3567b964d395b5..a959bb8d4347a3 100644 --- a/runtime/inspector_server.rs +++ b/runtime/inspector_server.rs @@ -289,7 +289,7 @@ async fn server( // Create the server manually so it can use the Local Executor let server_handler = hyper::server::Builder::new( hyper::server::conn::AddrIncoming::bind(&host).unwrap_or_else(|e| { - eprintln!("Cannot start inspector server: {}.", e); + eprintln!("Cannot start inspector server: {e}."); process::exit(1); }), hyper::server::conn::Http::new().with_executor(LocalExecutor), @@ -299,7 +299,7 @@ async fn server( shutdown_server_rx.await.ok(); }) .unwrap_or_else(|err| { - eprintln!("Cannot start inspector server: {}.", err); + eprintln!("Cannot start inspector server: {err}."); process::exit(1); }) .fuse(); @@ -422,7 +422,7 @@ impl InspectorInfo { self .thread_name .as_ref() - .map(|n| format!(" - {}", n)) + .map(|n| format!(" - {n}")) .unwrap_or_default(), process::id(), ) diff --git a/runtime/ops/fs.rs b/runtime/ops/fs.rs index 342b0e35d5f9e3..f6b9a58ebfd97c 100644 --- a/runtime/ops/fs.rs +++ b/runtime/ops/fs.rs @@ -337,7 +337,7 @@ fn seek_helper(args: SeekArgs) -> Result<(u32, SeekFrom), AnyError> { 1 => SeekFrom::Current(offset), 2 => SeekFrom::End(offset), _ => { - return Err(type_error(format!("Invalid seek mode: {}", whence))); + return Err(type_error(format!("Invalid seek mode: {whence}"))); } }; @@ -542,7 +542,7 @@ fn op_chdir(state: &mut OpState, directory: String) -> Result<(), AnyError> { .borrow_mut::() .check_read(&d, "Deno.chdir()")?; set_current_dir(&d).map_err(|err| { - Error::new(err.kind(), format!("{}, chdir '{}'", err, directory)) + Error::new(err.kind(), format!("{err}, chdir '{directory}'")) })?; Ok(()) } @@ -1747,7 +1747,7 @@ fn make_temp( let mut rng = thread_rng(); loop { let unique = rng.gen::(); - buf.set_file_name(format!("{}{:08x}{}", prefix_, unique, suffix_)); + buf.set_file_name(format!("{prefix_}{unique:08x}{suffix_}")); let r = if is_dir { #[allow(unused_mut)] let mut builder = std::fs::DirBuilder::new(); diff --git a/runtime/ops/mod.rs b/runtime/ops/mod.rs index e42f61a7bb4c63..ce7c52d64b4c0d 100644 --- a/runtime/ops/mod.rs +++ b/runtime/ops/mod.rs @@ -36,8 +36,7 @@ impl UnstableChecker { pub fn check_unstable(&self, api_name: &str) { if !self.unstable { eprintln!( - "Unstable API '{}'. The --unstable flag must be provided.", - api_name + "Unstable API '{api_name}'. The --unstable flag must be provided." ); std::process::exit(70); } diff --git a/runtime/ops/os/mod.rs b/runtime/ops/os/mod.rs index c35d4fc9e75f55..f970c318bc687e 100644 --- a/runtime/ops/os/mod.rs +++ b/runtime/ops/os/mod.rs @@ -92,14 +92,12 @@ fn op_set_env( } if key.contains(&['=', '\0'] as &[char]) { return Err(type_error(format!( - "Key contains invalid characters: {:?}", - key + "Key contains invalid characters: {key:?}" ))); } if value.contains('\0') { return Err(type_error(format!( - "Value contains invalid characters: {:?}", - value + "Value contains invalid characters: {value:?}" ))); } env::set_var(key, value); @@ -129,8 +127,7 @@ fn op_get_env( if key.contains(&['=', '\0'] as &[char]) { return Err(type_error(format!( - "Key contains invalid characters: {:?}", - key + "Key contains invalid characters: {key:?}" ))); } @@ -215,7 +212,7 @@ impl From for NetworkInterface { }; let (address, range) = ifa.cidr(); - let cidr = format!("{:?}/{}", address, range); + let cidr = format!("{address:?}/{range}"); let name = ifa.name().to_owned(); let address = format!("{:?}", ifa.address()); @@ -223,10 +220,7 @@ impl From for NetworkInterface { let scopeid = ifa.scope_id(); let [b0, b1, b2, b3, b4, b5] = ifa.mac(); - let mac = format!( - "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", - b0, b1, b2, b3, b4, b5 - ); + let mac = format!("{b0:02x}:{b1:02x}:{b2:02x}:{b3:02x}:{b4:02x}:{b5:02x}"); Self { family, diff --git a/runtime/ops/permissions.rs b/runtime/ops/permissions.rs index 2b01da0a9e5589..3c48c1e8ddfba8 100644 --- a/runtime/ops/permissions.rs +++ b/runtime/ops/permissions.rs @@ -59,7 +59,7 @@ pub fn op_query_permission( n => { return Err(custom_error( "ReferenceError", - format!("No such permission name: {}", n), + format!("No such permission name: {n}"), )) } }; @@ -93,7 +93,7 @@ pub fn op_revoke_permission( n => { return Err(custom_error( "ReferenceError", - format!("No such permission name: {}", n), + format!("No such permission name: {n}"), )) } }; @@ -127,7 +127,7 @@ pub fn op_request_permission( n => { return Err(custom_error( "ReferenceError", - format!("No such permission name: {}", n), + format!("No such permission name: {n}"), )) } }; @@ -135,7 +135,7 @@ pub fn op_request_permission( } fn parse_host(host_str: &str) -> Result<(String, Option), AnyError> { - let url = url::Url::parse(&format!("http://{}/", host_str)) + let url = url::Url::parse(&format!("http://{host_str}/")) .map_err(|_| uri_error("Invalid host"))?; if url.path() != "/" { return Err(uri_error("Invalid host")); diff --git a/runtime/ops/process.rs b/runtime/ops/process.rs index eebf7e7af9cc95..9c7a3243a3675b 100644 --- a/runtime/ops/process.rs +++ b/runtime/ops/process.rs @@ -317,7 +317,7 @@ pub fn kill(pid: i32, signal: &str) -> Result<(), AnyError> { use winapi::um::winnt::PROCESS_TERMINATE; if !matches!(signal, "SIGKILL" | "SIGTERM") { - Err(type_error(format!("Invalid signal: {}", signal))) + Err(type_error(format!("Invalid signal: {signal}"))) } else if pid <= 0 { Err(type_error("Invalid pid")) } else { diff --git a/runtime/ops/signal.rs b/runtime/ops/signal.rs index ddee1fb5d2c5e4..f88d870582f001 100644 --- a/runtime/ops/signal.rs +++ b/runtime/ops/signal.rs @@ -222,7 +222,7 @@ pub fn signal_str_to_int(s: &str) -> Result { "SIGIO" => Ok(29), "SIGPWR" => Ok(30), "SIGSYS" => Ok(31), - _ => Err(type_error(format!("Invalid signal : {}", s))), + _ => Err(type_error(format!("Invalid signal : {s}"))), } } @@ -260,7 +260,7 @@ pub fn signal_int_to_str(s: libc::c_int) -> Result<&'static str, AnyError> { 29 => Ok("SIGIO"), 30 => Ok("SIGPWR"), 31 => Ok("SIGSYS"), - _ => Err(type_error(format!("Invalid signal : {}", s))), + _ => Err(type_error(format!("Invalid signal : {s}"))), } } @@ -468,8 +468,7 @@ fn op_signal_bind( let signo = signal_str_to_int(&sig)?; if signal_hook_registry::FORBIDDEN.contains(&signo) { return Err(type_error(format!( - "Binding to signal '{}' is not allowed", - sig + "Binding to signal '{sig}' is not allowed", ))); } let resource = SignalStreamResource { diff --git a/runtime/ops/utils.rs b/runtime/ops/utils.rs index 29cbaab912b309..bdbe7f6d065ca0 100644 --- a/runtime/ops/utils.rs +++ b/runtime/ops/utils.rs @@ -13,7 +13,7 @@ use std::sync::Arc; /// A utility function to map OsStrings to Strings pub fn into_string(s: std::ffi::OsString) -> Result { s.into_string().map_err(|s| { - let message = format!("File name or path {:?} is not valid UTF-8", s); + let message = format!("File name or path {s:?} is not valid UTF-8"); custom_error("InvalidData", message) }) } diff --git a/runtime/ops/web_worker/sync_fetch.rs b/runtime/ops/web_worker/sync_fetch.rs index a9a893572d156a..2049d5ab85899f 100644 --- a/runtime/ops/web_worker/sync_fetch.rs +++ b/runtime/ops/web_worker/sync_fetch.rs @@ -92,7 +92,7 @@ pub fn op_worker_sync_fetch( } "data" => { let data_url = DataUrl::process(&script) - .map_err(|e| type_error(format!("{:?}", e)))?; + .map_err(|e| type_error(format!("{e:?}")))?; let mime_type = { let mime = data_url.mime_type(); @@ -101,7 +101,7 @@ pub fn op_worker_sync_fetch( let (body, _) = data_url .decode_to_vec() - .map_err(|e| type_error(format!("{:?}", e)))?; + .map_err(|e| type_error(format!("{e:?}")))?; (Bytes::from(body), Some(mime_type), script) } @@ -132,7 +132,7 @@ pub fn op_worker_sync_fetch( Some(mime_type) => { return Err( DomExceptionNetworkError { - msg: format!("Invalid MIME type {:?}.", mime_type), + msg: format!("Invalid MIME type {mime_type:?}."), } .into(), ) diff --git a/runtime/ops/worker_host.rs b/runtime/ops/worker_host.rs index 8945ff1cc6b108..71009be8fc2422 100644 --- a/runtime/ops/worker_host.rs +++ b/runtime/ops/worker_host.rs @@ -193,8 +193,7 @@ fn op_create_worker( >(1); // Setup new thread - let thread_builder = - std::thread::Builder::new().name(format!("{}", worker_id)); + let thread_builder = std::thread::Builder::new().name(format!("{worker_id}")); // Spawn it thread_builder.spawn(move || { diff --git a/runtime/permissions/mod.rs b/runtime/permissions/mod.rs index 494e603a366a6b..2981463123ae6e 100644 --- a/runtime/permissions/mod.rs +++ b/runtime/permissions/mod.rs @@ -67,7 +67,7 @@ impl PermissionState { format!( "{} access{}", name, - info().map_or(String::new(), |info| { format!(" to {}", info) }), + info().map_or(String::new(), |info| { format!(" to {info}") }), ) } @@ -111,7 +111,7 @@ impl PermissionState { let msg = format!( "{} access{}", name, - info().map_or(String::new(), |info| { format!(" to {}", info) }), + info().map_or(String::new(), |info| { format!(" to {info}") }), ); if PromptResponse::Allow == permission_prompt(&msg, name, api_name) { Self::log_perm_access(name, info); @@ -314,7 +314,7 @@ pub fn parse_sys_kind(kind: &str) -> Result<&str, AnyError> { match kind { "hostname" | "osRelease" | "osUptime" | "loadavg" | "networkInterfaces" | "systemMemoryInfo" | "uid" | "gid" => Ok(kind), - _ => Err(type_error(format!("unknown system info kind \"{}\"", kind))), + _ => Err(type_error(format!("unknown system info kind \"{kind}\""))), } } @@ -451,7 +451,7 @@ impl UnaryPermission { let (result, prompted) = self.query(Some(&resolved_path)).check( self.name, Some(api_name), - Some(&format!("<{}>", display)), + Some(&format!("<{display}>")), self.prompt, ); if prompted { @@ -687,7 +687,7 @@ impl UnaryPermission { if state == PermissionState::Prompt { if PromptResponse::Allow == permission_prompt( - &format!("network access to \"{}\"", host), + &format!("network access to \"{host}\""), self.name, Some("Deno.permissions.query()"), ) @@ -759,7 +759,7 @@ impl UnaryPermission { let (result, prompted) = self.query(Some(host)).check( self.name, api_name, - Some(&format!("\"{}\"", new_host)), + Some(&format!("\"{new_host}\"")), self.prompt, ); if prompted { @@ -784,13 +784,13 @@ impl UnaryPermission { .to_string(); let display_host = match url.port() { None => hostname.clone(), - Some(port) => format!("{}:{}", hostname, port), + Some(port) => format!("{hostname}:{port}"), }; let host = &(&hostname, url.port_or_known_default()); let (result, prompted) = self.query(Some(host)).check( self.name, api_name, - Some(&format!("\"{}\"", display_host)), + Some(&format!("\"{display_host}\"")), self.prompt, ); if prompted { @@ -861,7 +861,7 @@ impl UnaryPermission { if state == PermissionState::Prompt { if PromptResponse::Allow == permission_prompt( - &format!("env access to \"{}\"", env), + &format!("env access to \"{env}\""), self.name, Some("Deno.permissions.query()"), ) @@ -918,7 +918,7 @@ impl UnaryPermission { let (result, prompted) = self.query(Some(env)).check( self.name, None, - Some(&format!("\"{}\"", env)), + Some(&format!("\"{env}\"")), self.prompt, ); if prompted { @@ -995,7 +995,7 @@ impl UnaryPermission { let desc = SysDescriptor(kind.to_string()); if PromptResponse::Allow == permission_prompt( - &format!("sys access to \"{}\"", kind), + &format!("sys access to \"{kind}\""), self.name, Some("Deno.permissions.query()"), ) @@ -1044,7 +1044,7 @@ impl UnaryPermission { let (result, prompted) = self.query(Some(kind)).check( self.name, api_name, - Some(&format!("\"{}\"", kind)), + Some(&format!("\"{kind}\"")), self.prompt, ); if prompted { @@ -1118,7 +1118,7 @@ impl UnaryPermission { if state == PermissionState::Prompt { if PromptResponse::Allow == permission_prompt( - &format!("run access to \"{}\"", cmd), + &format!("run access to \"{cmd}\""), self.name, Some("Deno.permissions.query()"), ) @@ -1187,7 +1187,7 @@ impl UnaryPermission { let (result, prompted) = self.query(Some(cmd)).check( self.name, api_name, - Some(&format!("\"{}\"", cmd)), + Some(&format!("\"{cmd}\"")), self.prompt, ); if prompted { @@ -1606,8 +1606,7 @@ impl Permissions { "file" => match specifier.to_file_path() { Ok(path) => self.read.check(&path, Some("import()")), Err(_) => Err(uri_error(format!( - "Invalid file path.\n Specifier: {}", - specifier + "Invalid file path.\n Specifier: {specifier}" ))), }, "data" => Ok(()), @@ -2121,42 +2120,42 @@ impl<'de> Deserialize<'de> for ChildPermissionsArg { if key == "env" { let arg = serde_json::from_value::(value); child_permissions_arg.env = arg.map_err(|e| { - de::Error::custom(format!("(deno.permissions.env) {}", e)) + de::Error::custom(format!("(deno.permissions.env) {e}")) })?; } else if key == "hrtime" { let arg = serde_json::from_value::(value); child_permissions_arg.hrtime = arg.map_err(|e| { - de::Error::custom(format!("(deno.permissions.hrtime) {}", e)) + de::Error::custom(format!("(deno.permissions.hrtime) {e}")) })?; } else if key == "net" { let arg = serde_json::from_value::(value); child_permissions_arg.net = arg.map_err(|e| { - de::Error::custom(format!("(deno.permissions.net) {}", e)) + de::Error::custom(format!("(deno.permissions.net) {e}")) })?; } else if key == "ffi" { let arg = serde_json::from_value::(value); child_permissions_arg.ffi = arg.map_err(|e| { - de::Error::custom(format!("(deno.permissions.ffi) {}", e)) + de::Error::custom(format!("(deno.permissions.ffi) {e}")) })?; } else if key == "read" { let arg = serde_json::from_value::(value); child_permissions_arg.read = arg.map_err(|e| { - de::Error::custom(format!("(deno.permissions.read) {}", e)) + de::Error::custom(format!("(deno.permissions.read) {e}")) })?; } else if key == "run" { let arg = serde_json::from_value::(value); child_permissions_arg.run = arg.map_err(|e| { - de::Error::custom(format!("(deno.permissions.run) {}", e)) + de::Error::custom(format!("(deno.permissions.run) {e}")) })?; } else if key == "sys" { let arg = serde_json::from_value::(value); child_permissions_arg.sys = arg.map_err(|e| { - de::Error::custom(format!("(deno.permissions.sys) {}", e)) + de::Error::custom(format!("(deno.permissions.sys) {e}")) })?; } else if key == "write" { let arg = serde_json::from_value::(value); child_permissions_arg.write = arg.map_err(|e| { - de::Error::custom(format!("(deno.permissions.write) {}", e)) + de::Error::custom(format!("(deno.permissions.write) {e}")) })?; } else { return Err(de::Error::custom("unknown permission name")); diff --git a/runtime/permissions/prompter.rs b/runtime/permissions/prompter.rs index ae07e004c87ec3..e311bc9785623d 100644 --- a/runtime/permissions/prompter.rs +++ b/runtime/permissions/prompter.rs @@ -182,13 +182,13 @@ impl PermissionPrompter for TtyPrompter { // Clear n-lines in terminal and move cursor to the beginning of the line. fn clear_n_lines(n: usize) { - eprint!("\x1B[{}A\x1B[0J", n); + eprint!("\x1B[{n}A\x1B[0J"); } // For security reasons we must consume everything in stdin so that previously // buffered data cannot effect the prompt. if let Err(err) = clear_stdin() { - eprintln!("Error clearing stdin for permission prompt. {:#}", err); + eprintln!("Error clearing stdin for permission prompt. {err:#}"); return PromptResponse::Deny; // don't grant permission if this fails } @@ -199,17 +199,17 @@ impl PermissionPrompter for TtyPrompter { // print to stderr so that if stdout is piped this is still displayed. const OPTS: &str = "[y/n] (y = yes, allow; n = no, deny)"; - eprint!("{} ┌ ", PERMISSION_EMOJI); + eprint!("{PERMISSION_EMOJI} ┌ "); eprint!("{}", colors::bold("Deno requests ")); eprint!("{}", colors::bold(message)); eprintln!("{}", colors::bold(".")); if let Some(api_name) = api_name { - eprintln!(" ├ Requested by `{}` API", api_name); + eprintln!(" ├ Requested by `{api_name}` API"); } - let msg = format!("Run again with --allow-{} to bypass this prompt.", name); + let msg = format!("Run again with --allow-{name} to bypass this prompt."); eprintln!(" ├ {}", colors::italic(&msg)); eprint!(" └ {}", colors::bold("Allow?")); - eprint!(" {} > ", OPTS); + eprint!(" {OPTS} > "); let value = loop { let mut input = String::new(); let stdin = std::io::stdin(); @@ -224,13 +224,13 @@ impl PermissionPrompter for TtyPrompter { match ch.to_ascii_lowercase() { 'y' => { clear_n_lines(if api_name.is_some() { 4 } else { 3 }); - let msg = format!("Granted {}.", message); + let msg = format!("Granted {message}."); eprintln!("✅ {}", colors::bold(&msg)); break PromptResponse::Allow; } 'n' => { clear_n_lines(if api_name.is_some() { 4 } else { 3 }); - let msg = format!("Denied {}.", message); + let msg = format!("Denied {message}."); eprintln!("❌ {}", colors::bold(&msg)); break PromptResponse::Deny; } @@ -238,7 +238,7 @@ impl PermissionPrompter for TtyPrompter { // If we don't get a recognized option try again. clear_n_lines(1); eprint!(" └ {}", colors::bold("Unrecognized option. Allow?")); - eprint!(" {} > ", OPTS); + eprint!(" {OPTS} > "); } }; }; diff --git a/runtime/worker_bootstrap.rs b/runtime/worker_bootstrap.rs index 17aa8a85b96071..5563b6eadb5b18 100644 --- a/runtime/worker_bootstrap.rs +++ b/runtime/worker_bootstrap.rs @@ -37,7 +37,7 @@ impl Default for BootstrapOptions { .unwrap_or(1); let runtime_version = env!("CARGO_PKG_VERSION").into(); - let user_agent = format!("Deno/{}", runtime_version); + let user_agent = format!("Deno/{runtime_version}"); Self { runtime_version, diff --git a/rust-toolchain.toml b/rust-toolchain.toml index d1df584a7dbad9..b42ddcf07f0f33 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,3 +1,3 @@ [toolchain] -channel = "1.66.0" +channel = "1.67.0" components = ["rustfmt", "clippy"] diff --git a/serde_v8/benches/de.rs b/serde_v8/benches/de.rs index 9cd2da68939c1d..b7cd0bf321add1 100644 --- a/serde_v8/benches/de.rs +++ b/serde_v8/benches/de.rs @@ -32,7 +32,7 @@ fn dedo( } fn dedo_json(code: &str, f: impl FnOnce(String)) { - let code = format!("JSON.stringify({})", code); + let code = format!("JSON.stringify({code})"); dedo(&code[..], |scope, v| { let s: String = serde_v8::from_v8(scope, v).unwrap(); f(s); diff --git a/serde_v8/error.rs b/serde_v8/error.rs index fd763bb1e0a0a1..2cd8eab655f512 100644 --- a/serde_v8/error.rs +++ b/serde_v8/error.rs @@ -45,7 +45,7 @@ impl Display for Error { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { match self { Error::Message(msg) => formatter.write_str(msg), - err => formatter.write_str(format!("serde_v8 error: {:?}", err).as_ref()), + err => formatter.write_str(format!("serde_v8 error: {err:?}").as_ref()), } } } diff --git a/serde_v8/examples/basic.rs b/serde_v8/examples/basic.rs index f1ea4d6a57d691..29fb980854e689 100644 --- a/serde_v8/examples/basic.rs +++ b/serde_v8/examples/basic.rs @@ -30,7 +30,7 @@ fn main() { let v = exec(scope, "32"); let x32: u64 = serde_v8::from_v8(scope, v).unwrap(); - println!("x32 = {}", x32); + println!("x32 = {x32}"); let v = exec(scope, "({a: 1, b: 3, c: 'ignored'})"); let mop: MathOp = serde_v8::from_v8(scope, v).unwrap(); @@ -41,15 +41,15 @@ fn main() { let v = exec(scope, "[1,2,3,4,5]"); let arr: Vec = serde_v8::from_v8(scope, v).unwrap(); - println!("arr = {:?}", arr); + println!("arr = {arr:?}"); let v = exec(scope, "['hello', 'world']"); let hi: Vec = serde_v8::from_v8(scope, v).unwrap(); - println!("hi = {:?}", hi); + println!("hi = {hi:?}"); let v: v8::Local = v8::Number::new(scope, 12345.0).into(); let x: f64 = serde_v8::from_v8(scope, v).unwrap(); - println!("x = {}", x); + println!("x = {x}"); } // SAFETY: all isolates have been destroyed, so we can now safely let V8 clean diff --git a/serde_v8/tests/de.rs b/serde_v8/tests/de.rs index b487b394e7ce3d..5f3e262e750d86 100644 --- a/serde_v8/tests/de.rs +++ b/serde_v8/tests/de.rs @@ -292,7 +292,7 @@ impl<'de> serde::de::Visitor<'de> for StructVisitor { match key.as_ref() { "a" => payload.a = map.next_value()?, "b" => payload.b = map.next_value()?, - f => panic!("Unknown field {}", f), + f => panic!("Unknown field {f}"), } } Ok(payload) diff --git a/serde_v8/tests/ser.rs b/serde_v8/tests/ser.rs index 485a3ad6f7bfb5..d6de3a62a221ba 100644 --- a/serde_v8/tests/ser.rs +++ b/serde_v8/tests/ser.rs @@ -65,7 +65,7 @@ fn sercheck(val: T, code: &str, pollute: bool) -> bool { // Pollution check if let Some(message) = scope.message() { let msg = message.get(scope).to_rust_string_lossy(scope); - panic!("JS Exception: {}", msg); + panic!("JS Exception: {msg}"); } // Execute equality check in JS (e.g: x == ...) diff --git a/test_ffi/src/lib.rs b/test_ffi/src/lib.rs index ad15ee5aee94d8..0ddccf4dc1a4ba 100644 --- a/test_ffi/src/lib.rs +++ b/test_ffi/src/lib.rs @@ -20,7 +20,7 @@ pub extern "C" fn print_something() { #[no_mangle] pub unsafe extern "C" fn print_buffer(ptr: *const u8, len: usize) { let buf = std::slice::from_raw_parts(ptr, len); - println!("{:?}", buf); + println!("{buf:?}"); } /// # Safety @@ -36,7 +36,7 @@ pub unsafe extern "C" fn print_buffer2( ) { let buf1 = std::slice::from_raw_parts(ptr1, len1); let buf2 = std::slice::from_raw_parts(ptr2, len2); - println!("{:?} {:?}", buf1, buf2); + println!("{buf1:?} {buf2:?}"); } #[no_mangle] @@ -189,7 +189,7 @@ pub extern "C" fn call_fn_ptr_return_buffer( let func = func.unwrap(); let ptr = func(); let buf = unsafe { std::slice::from_raw_parts(ptr, 8) }; - println!("buf: {:?}", buf); + println!("buf: {buf:?}"); } static mut STORED_FUNCTION: Option = None; @@ -502,7 +502,7 @@ pub extern "C" fn make_rect(x: f64, y: f64, w: f64, h: f64) -> Rect { #[no_mangle] pub extern "C" fn print_rect(rect: Rect) { - println!("{:?}", rect); + println!("{rect:?}"); } #[derive(Debug)] @@ -541,5 +541,5 @@ pub unsafe extern "C" fn create_mixed( #[no_mangle] pub extern "C" fn print_mixed(mixed: Mixed) { - println!("{:?}", mixed); + println!("{mixed:?}"); } diff --git a/test_ffi/tests/integration_tests.rs b/test_ffi/tests/integration_tests.rs index 3c86d6d4d4b005..c213f829512089 100644 --- a/test_ffi/tests/integration_tests.rs +++ b/test_ffi/tests/integration_tests.rs @@ -38,8 +38,8 @@ fn basic() { let stdout = std::str::from_utf8(&output.stdout).unwrap(); let stderr = std::str::from_utf8(&output.stderr).unwrap(); if !output.status.success() { - println!("stdout {}", stdout); - println!("stderr {}", stderr); + println!("stdout {stdout}"); + println!("stderr {stderr}"); } println!("{:?}", output.status); assert!(output.status.success()); @@ -158,8 +158,8 @@ fn symbol_types() { let stdout = std::str::from_utf8(&output.stdout).unwrap(); let stderr = std::str::from_utf8(&output.stderr).unwrap(); if !output.status.success() { - println!("stdout {}", stdout); - println!("stderr {}", stderr); + println!("stdout {stdout}"); + println!("stderr {stderr}"); } println!("{:?}", output.status); assert!(output.status.success()); @@ -183,8 +183,8 @@ fn thread_safe_callback() { let stdout = std::str::from_utf8(&output.stdout).unwrap(); let stderr = std::str::from_utf8(&output.stderr).unwrap(); if !output.status.success() { - println!("stdout {}", stdout); - println!("stderr {}", stderr); + println!("stdout {stdout}"); + println!("stderr {stderr}"); } println!("{:?}", output.status); assert!(output.status.success()); @@ -215,8 +215,8 @@ fn event_loop_integration() { let stdout = std::str::from_utf8(&output.stdout).unwrap(); let stderr = std::str::from_utf8(&output.stderr).unwrap(); if !output.status.success() { - println!("stdout {}", stdout); - println!("stderr {}", stderr); + println!("stdout {stdout}"); + println!("stderr {stderr}"); } println!("{:?}", output.status); assert!(output.status.success()); diff --git a/test_napi/src/properties.rs b/test_napi/src/properties.rs index 9d90d0b7f27182..a54738cb571ff9 100644 --- a/test_napi/src/properties.rs +++ b/test_napi/src/properties.rs @@ -36,7 +36,7 @@ pub fn init(env: napi_env, exports: napi_value) { let properties = &[ napi_property_descriptor { - utf8name: "test_property_rw".as_ptr() as *const c_char, + utf8name: "test_property_rw\0".as_ptr() as *const c_char, name: ptr::null_mut(), method: None, getter: None, @@ -46,7 +46,7 @@ pub fn init(env: napi_env, exports: napi_value) { value: number, }, napi_property_descriptor { - utf8name: "test_property_r".as_ptr() as *const c_char, + utf8name: "test_property_r\0".as_ptr() as *const c_char, name: ptr::null_mut(), method: None, getter: None, diff --git a/test_napi/tests/napi_tests.rs b/test_napi/tests/napi_tests.rs index 3351d74c1ecbac..cba96079ea74b9 100644 --- a/test_napi/tests/napi_tests.rs +++ b/test_napi/tests/napi_tests.rs @@ -40,8 +40,8 @@ fn napi_tests() { let stderr = std::str::from_utf8(&output.stderr).unwrap(); if !output.status.success() { - println!("stdout {}", stdout); - println!("stderr {}", stderr); + println!("stdout {stdout}"); + println!("stderr {stderr}"); } assert!(output.status.success()); } diff --git a/test_util/src/lib.rs b/test_util/src/lib.rs index 5781f434b20b43..45008cf1fb1d7c 100644 --- a/test_util/src/lib.rs +++ b/test_util/src/lib.rs @@ -214,7 +214,7 @@ async fn hyper_hello(port: u16) { let server = Server::bind(&addr).serve(hello_svc); if let Err(e) = server.await { - eprintln!("server error: {}", e); + eprintln!("server error: {e}"); } } @@ -232,7 +232,7 @@ fn redirect_resp(url: String) -> Response { async fn redirect(req: Request) -> hyper::Result> { let p = req.uri().path(); assert_eq!(&p[0..1], "/"); - let url = format!("http://localhost:{}{}", PORT, p); + let url = format!("http://localhost:{PORT}{p}"); Ok(redirect_resp(url)) } @@ -240,7 +240,7 @@ async fn redirect(req: Request) -> hyper::Result> { async fn double_redirects(req: Request) -> hyper::Result> { let p = req.uri().path(); assert_eq!(&p[0..1], "/"); - let url = format!("http://localhost:{}{}", REDIRECT_PORT, p); + let url = format!("http://localhost:{REDIRECT_PORT}{p}"); Ok(redirect_resp(url)) } @@ -248,7 +248,7 @@ async fn double_redirects(req: Request) -> hyper::Result> { async fn inf_redirects(req: Request) -> hyper::Result> { let p = req.uri().path(); assert_eq!(&p[0..1], "/"); - let url = format!("http://localhost:{}{}", INF_REDIRECTS_PORT, p); + let url = format!("http://localhost:{INF_REDIRECTS_PORT}{p}"); Ok(redirect_resp(url)) } @@ -256,7 +256,7 @@ async fn inf_redirects(req: Request) -> hyper::Result> { async fn another_redirect(req: Request) -> hyper::Result> { let p = req.uri().path(); assert_eq!(&p[0..1], "/"); - let url = format!("http://localhost:{}/subdir{}", PORT, p); + let url = format!("http://localhost:{PORT}/subdir{p}"); Ok(redirect_resp(url)) } @@ -267,10 +267,10 @@ async fn auth_redirect(req: Request) -> hyper::Result> { .get("authorization") .map(|v| v.to_str().unwrap()) { - if auth.to_lowercase() == format!("bearer {}", TEST_AUTH_TOKEN) { + if auth.to_lowercase() == format!("bearer {TEST_AUTH_TOKEN}") { let p = req.uri().path(); assert_eq!(&p[0..1], "/"); - let url = format!("http://localhost:{}{}", PORT, p); + let url = format!("http://localhost:{PORT}{p}"); return Ok(redirect_resp(url)); } } @@ -289,11 +289,11 @@ async fn basic_auth_redirect( .map(|v| v.to_str().unwrap()) { let credentials = - format!("{}:{}", TEST_BASIC_AUTH_USERNAME, TEST_BASIC_AUTH_PASSWORD); + format!("{TEST_BASIC_AUTH_USERNAME}:{TEST_BASIC_AUTH_PASSWORD}"); if auth == format!("Basic {}", base64::encode(credentials)) { let p = req.uri().path(); assert_eq!(&p[0..1], "/"); - let url = format!("http://localhost:{}{}", PORT, p); + let url = format!("http://localhost:{PORT}{p}"); return Ok(redirect_resp(url)); } } @@ -316,7 +316,7 @@ async fn run_ws_server(addr: &SocketAddr) { rx.forward(tx) .map(|result| { if let Err(e) = result { - println!("websocket server error: {:?}", e); + println!("websocket server error: {e:?}"); } }) .await; @@ -452,14 +452,14 @@ async fn run_wss_server(addr: &SocketAddr) { rx.forward(tx) .map(|result| { if let Err(e) = result { - println!("Websocket server error: {:?}", e); + println!("Websocket server error: {e:?}"); } }) .await; } } Err(e) => { - eprintln!("TLS accept error: {:?}", e); + eprintln!("TLS accept error: {e:?}"); } } }); @@ -490,12 +490,12 @@ async fn run_tls_client_auth_server() { .boxed() }; - let host_and_port = &format!("localhost:{}", TLS_CLIENT_AUTH_PORT); + let host_and_port = &format!("localhost:{TLS_CLIENT_AUTH_PORT}"); let listeners = tokio::net::lookup_host(host_and_port) .await .expect(host_and_port) - .inspect(|address| println!("{} -> {}", host_and_port, address)) + .inspect(|address| println!("{host_and_port} -> {address}")) .map(tokio::net::TcpListener::bind) .collect::>() .collect::>() @@ -525,7 +525,7 @@ async fn run_tls_client_auth_server() { } Err(e) => { - eprintln!("TLS accept error: {:?}", e); + eprintln!("TLS accept error: {e:?}"); } } }); @@ -554,12 +554,12 @@ async fn run_tls_server() { .boxed() }; - let host_and_port = &format!("localhost:{}", TLS_PORT); + let host_and_port = &format!("localhost:{TLS_PORT}"); let listeners = tokio::net::lookup_host(host_and_port) .await .expect(host_and_port) - .inspect(|address| println!("{} -> {}", host_and_port, address)) + .inspect(|address| println!("{host_and_port} -> {address}")) .map(tokio::net::TcpListener::bind) .collect::>() .collect::>() @@ -582,7 +582,7 @@ async fn run_tls_server() { } Err(e) => { - eprintln!("TLS accept error: {:?}", e); + eprintln!("TLS accept error: {e:?}"); } } }); @@ -596,7 +596,7 @@ async fn absolute_redirect( if path.starts_with("/REDIRECT") { let url = &req.uri().path()[9..]; - println!("URL: {:?}", url); + println!("URL: {url:?}"); let redirect = redirect_resp(url.to_string()); return Ok(redirect); } @@ -1009,7 +1009,7 @@ async fn main_server( Err(err) => { return Response::builder() .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(format!("{:#}", err).into()); + .body(format!("{err:#}").into()); } } } else if req.uri().path().starts_with("/npm/registry/") { @@ -1027,7 +1027,7 @@ async fn main_server( { return Response::builder() .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(format!("{:#}", err).into()); + .body(format!("{err:#}").into()); }; // serve the file @@ -1095,12 +1095,9 @@ async fn download_npm_registry_file( }; let url = if is_tarball { let file_name = file_path.file_name().unwrap().to_string_lossy(); - format!( - "https://registry.npmjs.org/{}/-/{}", - package_name, file_name - ) + format!("https://registry.npmjs.org/{package_name}/-/{file_name}") } else { - format!("https://registry.npmjs.org/{}", package_name) + format!("https://registry.npmjs.org/{package_name}") }; let client = reqwest::Client::new(); let response = client.get(url).send().await?; @@ -1111,8 +1108,8 @@ async fn download_npm_registry_file( String::from_utf8(bytes.to_vec()) .unwrap() .replace( - &format!("https://registry.npmjs.org/{}/-/", package_name), - &format!("http://localhost:4545/npm/registry/{}/", package_name), + &format!("https://registry.npmjs.org/{package_name}/-/"), + &format!("http://localhost:4545/npm/registry/{package_name}/"), ) .into_bytes() }; @@ -1153,7 +1150,7 @@ async fn wrap_redirect_server() { let redirect_addr = SocketAddr::from(([127, 0, 0, 1], REDIRECT_PORT)); let redirect_server = Server::bind(&redirect_addr).serve(redirect_svc); if let Err(e) = redirect_server.await { - eprintln!("Redirect error: {:?}", e); + eprintln!("Redirect error: {e:?}"); } } @@ -1166,7 +1163,7 @@ async fn wrap_double_redirect_server() { let double_redirects_server = Server::bind(&double_redirects_addr).serve(double_redirects_svc); if let Err(e) = double_redirects_server.await { - eprintln!("Double redirect error: {:?}", e); + eprintln!("Double redirect error: {e:?}"); } } @@ -1179,7 +1176,7 @@ async fn wrap_inf_redirect_server() { let inf_redirects_server = Server::bind(&inf_redirects_addr).serve(inf_redirects_svc); if let Err(e) = inf_redirects_server.await { - eprintln!("Inf redirect error: {:?}", e); + eprintln!("Inf redirect error: {e:?}"); } } @@ -1192,7 +1189,7 @@ async fn wrap_another_redirect_server() { let another_redirect_server = Server::bind(&another_redirect_addr).serve(another_redirect_svc); if let Err(e) = another_redirect_server.await { - eprintln!("Another redirect error: {:?}", e); + eprintln!("Another redirect error: {e:?}"); } } @@ -1205,7 +1202,7 @@ async fn wrap_auth_redirect_server() { let auth_redirect_server = Server::bind(&auth_redirect_addr).serve(auth_redirect_svc); if let Err(e) = auth_redirect_server.await { - eprintln!("Auth redirect error: {:?}", e); + eprintln!("Auth redirect error: {e:?}"); } } @@ -1218,7 +1215,7 @@ async fn wrap_basic_auth_redirect_server() { let basic_auth_redirect_server = Server::bind(&basic_auth_redirect_addr).serve(basic_auth_redirect_svc); if let Err(e) = basic_auth_redirect_server.await { - eprintln!("Basic auth redirect error: {:?}", e); + eprintln!("Basic auth redirect error: {e:?}"); } } @@ -1231,7 +1228,7 @@ async fn wrap_abs_redirect_server() { let abs_redirect_server = Server::bind(&abs_redirect_addr).serve(abs_redirect_svc); if let Err(e) = abs_redirect_server.await { - eprintln!("Absolute redirect error: {:?}", e); + eprintln!("Absolute redirect error: {e:?}"); } } @@ -1241,7 +1238,7 @@ async fn wrap_main_server() { let main_server_addr = SocketAddr::from(([127, 0, 0, 1], PORT)); let main_server = Server::bind(&main_server_addr).serve(main_server_svc); if let Err(e) = main_server.await { - eprintln!("HTTP server error: {:?}", e); + eprintln!("HTTP server error: {e:?}"); } } @@ -1389,7 +1386,7 @@ async fn wrap_client_auth_https_server() { let tcp = TcpListener::bind(&main_server_https_addr) .await .expect("Cannot bind TCP"); - println!("ready: https_client_auth on :{:?}", HTTPS_CLIENT_AUTH_PORT); // Eye catcher for HttpServerCount + println!("ready: https_client_auth on :{HTTPS_CLIENT_AUTH_PORT:?}"); // Eye catcher for HttpServerCount let tls_acceptor = TlsAcceptor::from(tls_config.clone()); // Prepare a long-running future stream to accept and serve cients. let incoming_tls_stream = async_stream::stream! { @@ -1538,7 +1535,7 @@ fn custom_headers(p: &str, body: Vec) -> Response { response.headers_mut().insert( "Content-Type", HeaderValue::from_str( - &format!("application/typescript;charset={}", charset)[..], + &format!("application/typescript;charset={charset}")[..], ) .unwrap(), ); @@ -1643,9 +1640,9 @@ impl HttpServerCount { let _ = test_server.wait(); } Ok(Some(status)) => { - panic!("test_server exited unexpectedly {}", status) + panic!("test_server exited unexpectedly {status}") } - Err(e) => panic!("test_server error: {}", e), + Err(e) => panic!("test_server error: {e}"), } } } @@ -1755,8 +1752,8 @@ pub fn run_collect( let stdout = String::from_utf8(stdout).unwrap(); let stderr = String::from_utf8(stderr).unwrap(); if expect_success != status.success() { - eprintln!("stdout: <<<{}>>>", stdout); - eprintln!("stderr: <<<{}>>>", stderr); + eprintln!("stdout: <<<{stdout}>>>"); + eprintln!("stderr: <<<{stderr}>>>"); panic!("Unexpected exit code: {:?}", status.code()); } (stdout, stderr) @@ -1817,8 +1814,8 @@ pub fn run_and_collect_output_with_args( let stdout = String::from_utf8(stdout).unwrap(); let stderr = String::from_utf8(stderr).unwrap(); if expect_success != status.success() { - eprintln!("stdout: <<<{}>>>", stdout); - eprintln!("stderr: <<<{}>>>", stderr); + eprintln!("stdout: <<<{stdout}>>>"); + eprintln!("stderr: <<<{stderr}>>>"); panic!("Unexpected exit code: {:?}", status.code()); } (stdout, stderr) @@ -1883,11 +1880,10 @@ pub fn run_powershell_script_file( let output = command.output().expect("failed to spawn script"); let stdout = String::from_utf8(output.stdout).unwrap(); let stderr = String::from_utf8(output.stderr).unwrap(); - println!("{}", stdout); + println!("{stdout}"); if !output.status.success() { panic!( - "{} executed with failing error code\n{}{}", - script_file_path, stdout, stderr + "{script_file_path} executed with failing error code\n{stdout}{stderr}" ); } @@ -1958,7 +1954,7 @@ impl<'a> CheckOutputIntegrationTest<'a> { if let Some(input) = self.input { let mut p_stdin = process.stdin.take().unwrap(); - write!(p_stdin, "{}", input).unwrap(); + write!(p_stdin, "{input}").unwrap(); } // Very important when using pipes: This parent process is still @@ -1974,7 +1970,7 @@ impl<'a> CheckOutputIntegrationTest<'a> { if let Some(exit_code) = status.code() { if self.exit_code != exit_code { - println!("OUTPUT\n{}\nOUTPUT", actual); + println!("OUTPUT\n{actual}\nOUTPUT"); panic!( "bad exit code, expected: {:?}, actual: {:?}", self.exit_code, exit_code @@ -1985,15 +1981,15 @@ impl<'a> CheckOutputIntegrationTest<'a> { { use std::os::unix::process::ExitStatusExt; let signal = status.signal().unwrap(); - println!("OUTPUT\n{}\nOUTPUT", actual); + println!("OUTPUT\n{actual}\nOUTPUT"); panic!( "process terminated by signal, expected exit code: {:?}, actual signal: {:?}", - self.exit_code, signal + self.exit_code, signal, ); } #[cfg(not(unix))] { - println!("OUTPUT\n{}\nOUTPUT", actual); + println!("OUTPUT\n{actual}\nOUTPUT"); panic!("process terminated without status code on non unix platform, expected exit code: {:?}", self.exit_code); } } @@ -2020,8 +2016,8 @@ impl<'a> CheckOutputIntegrationTest<'a> { if !expected.contains("[WILDCARD]") { assert_eq!(actual, expected) } else if !wildcard_match(&expected, &actual) { - println!("OUTPUT\n{}\nOUTPUT", actual); - println!("EXPECTED\n{}\nEXPECTED", expected); + println!("OUTPUT\n{actual}\nOUTPUT"); + println!("EXPECTED\n{expected}\nEXPECTED"); panic!("pattern match failed"); } } @@ -2432,14 +2428,13 @@ foo: fn multi_line_builder(input: &str, leading_text: Option<&str>) -> String { // If there is leading text add a newline so it's on it's own line let head = match leading_text { - Some(v) => format!("{}\n", v), + Some(v) => format!("{v}\n"), None => "".to_string(), }; format!( - "{}foo: -quuz {} corge -grault", - head, input + "{head}foo: +quuz {input} corge +grault" ) } diff --git a/test_util/src/lsp.rs b/test_util/src/lsp.rs index 465e2a9ba6534a..5694287eb71004 100644 --- a/test_util/src/lsp.rs +++ b/test_util/src/lsp.rs @@ -170,8 +170,8 @@ impl Drop for LspClient { self.child.kill().unwrap(); let _ = self.child.wait(); } - Ok(Some(status)) => panic!("deno lsp exited unexpectedly {}", status), - Err(e) => panic!("pebble error: {}", e), + Ok(Some(status)) => panic!("deno lsp exited unexpectedly {status}"), + Err(e) => panic!("pebble error: {e}"), } } } diff --git a/test_util/src/npm.rs b/test_util/src/npm.rs index 738a1090aad6f0..9600b0bce583a6 100644 --- a/test_util/src/npm.rs +++ b/test_util/src/npm.rs @@ -113,14 +113,13 @@ fn get_npm_package(package_name: &str) -> Result> { let mut dist = serde_json::Map::new(); dist.insert( "integrity".to_string(), - format!("sha512-{}", tarball_checksum).into(), + format!("sha512-{tarball_checksum}").into(), ); dist.insert("shasum".to_string(), "dummy-value".into()); dist.insert( "tarball".to_string(), format!( - "http://localhost:4545/npm/registry/{}/{}.tgz", - package_name, version + "http://localhost:4545/npm/registry/{package_name}/{version}.tgz" ) .into(), ); diff --git a/test_util/src/pty.rs b/test_util/src/pty.rs index b2d7201ae455ce..f3bb2829f17e19 100644 --- a/test_util/src/pty.rs +++ b/test_util/src/pty.rs @@ -8,7 +8,7 @@ pub trait Pty: Read { fn write_text(&mut self, text: &str); fn write_line(&mut self, text: &str) { - self.write_text(&format!("{}\n", text)); + self.write_text(&format!("{text}\n")); } /// Reads the output to the EOF. @@ -442,7 +442,7 @@ mod windows { let mut parts = env_vars .into_iter() // each environment variable is in the form `name=value\0` - .map(|(key, value)| format!("{}={}\0", key, value)) + .map(|(key, value)| format!("{key}={value}\0")) .collect::>(); // all strings in an environment block must be case insensitively