From 4bdeb53cb514100e1cfe8267adc9774c443d34ba Mon Sep 17 00:00:00 2001 From: hi-rustin Date: Fri, 7 Jul 2023 09:33:41 +0800 Subject: [PATCH 01/17] Bail out an error when using `cargo::` in custom build script Signed-off-by: hi-rustin --- src/cargo/core/compiler/custom_build.rs | 12 +++++++++- tests/testsuite/build_script.rs | 29 +++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/cargo/core/compiler/custom_build.rs b/src/cargo/core/compiler/custom_build.rs index d1746217497c..85306aaac878 100644 --- a/src/cargo/core/compiler/custom_build.rs +++ b/src/cargo/core/compiler/custom_build.rs @@ -690,7 +690,17 @@ impl BuildOutput { continue; } let data = match iter.next() { - Some(val) => val, + Some(val) => { + if val.starts_with(":") { + // Line started with `cargo::`. + bail!("unsupported output in {}: `{}`\n\ + Found a `cargo::key=value` build directive which is reserved for future use.\n\ + Either change the directive to `cargo:key=value` syntax (note the single `:`) or upgrade your version of Rust.\n\ + See https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script \ + for more information about build script outputs.", whence, line); + } + val + } None => continue, }; diff --git a/tests/testsuite/build_script.rs b/tests/testsuite/build_script.rs index 4840356c6bae..400d10547c43 100644 --- a/tests/testsuite/build_script.rs +++ b/tests/testsuite/build_script.rs @@ -5140,6 +5140,35 @@ for more information about build script outputs. .run(); } +#[cargo_test] +fn wrong_syntax_with_two_colons() { + let p = project() + .file("src/lib.rs", "") + .file( + "build.rs", + r#" + fn main() { + println!("cargo::foo=bar"); + } + "#, + ) + .build(); + + p.cargo("build") + .with_status(101) + .with_stderr( + "\ +[COMPILING] foo [..] +error: unsupported output in build script of `foo v0.0.1 ([ROOT]/foo)`: `cargo::foo=bar` +Found a `cargo::key=value` build directive which is reserved for future use. +Either change the directive to `cargo:key=value` syntax (note the single `:`) or upgrade your version of Rust. +See https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script \ +for more information about build script outputs. +", + ) + .run(); +} + #[cargo_test] fn custom_build_closes_stdin() { // Ensure stdin is closed to prevent deadlock. From 65ec65fe1eec74f1aa78b2c5d4dcd8b5eb3b0c9d Mon Sep 17 00:00:00 2001 From: Arlo Siemsen Date: Wed, 2 Aug 2023 18:03:04 -0500 Subject: [PATCH 02/17] Fix printing multiple warning messages for unused fields in [registries] table --- src/cargo/util/auth/mod.rs | 36 +++++++++++++++++++++-------- src/cargo/util/config/mod.rs | 12 ++++++++++ tests/testsuite/alt_registry.rs | 41 +++++++++++++++++++++++++++++++++ 3 files changed, 79 insertions(+), 10 deletions(-) diff --git a/src/cargo/util/auth/mod.rs b/src/cargo/util/auth/mod.rs index 1e221a2c7b74..8a85fceb3ab4 100644 --- a/src/cargo/util/auth/mod.rs +++ b/src/cargo/util/auth/mod.rs @@ -12,7 +12,6 @@ use cargo_credential::{ use core::fmt; use serde::Deserialize; -use std::collections::HashMap; use std::error::Error; use time::{Duration, OffsetDateTime}; use url::Url; @@ -31,7 +30,7 @@ use super::{ /// `[registries.NAME]` tables. /// /// The values here should be kept in sync with `RegistryConfigExtended` -#[derive(Deserialize)] +#[derive(Deserialize, Clone, Debug)] #[serde(rename_all = "kebab-case")] pub struct RegistryConfig { pub index: Option, @@ -207,6 +206,19 @@ fn credential_provider(config: &Config, sid: &SourceId) -> CargoResult CargoResult> { + let mut cache = config.registry_config(); + if let Some(cfg) = cache.get(&sid) { + return Ok(cfg.clone()); + } + let cfg = registry_credential_config_raw_uncached(config, sid)?; + cache.insert(*sid, cfg.clone()); + return Ok(cfg); +} + +fn registry_credential_config_raw_uncached( + config: &Config, + sid: &SourceId, ) -> CargoResult> { log::trace!("loading credential config for {}", sid); config.load_credentials()?; @@ -237,6 +249,7 @@ pub fn registry_credential_config_raw( // This also allows the authorization token for a registry to be set // without knowing the registry name by using the _INDEX and _TOKEN // environment variables. + let name = { // Discover names from environment variables. let index = sid.canonical_url(); @@ -256,14 +269,17 @@ pub fn registry_credential_config_raw( // Discover names from the configuration only if none were found in the environment. if names.len() == 0 { - names = config - .get::>("registries")? - .iter() - .filter_map(|(k, v)| Some((k, v.index.as_deref()?))) - .filter_map(|(k, v)| Some((k, CanonicalUrl::new(&v.into_url().ok()?).ok()?))) - .filter(|(_, v)| v == index) - .map(|(k, _)| k.to_string()) - .collect(); + if let Some(registries) = config.values()?.get("registries") { + let (registries, _) = registries.table("registries")?; + for (name, value) in registries { + if let Some(v) = value.table(&format!("registries.{name}"))?.0.get("index") { + let (v, _) = v.string(&format!("registries.{name}.index"))?; + if index == &CanonicalUrl::new(&v.into_url()?)? { + names.push(name.clone()); + } + } + } + } } names.sort(); match names.len() { diff --git a/src/cargo/util/config/mod.rs b/src/cargo/util/config/mod.rs index 8f1cfe073f5e..024137dd79a9 100644 --- a/src/cargo/util/config/mod.rs +++ b/src/cargo/util/config/mod.rs @@ -106,6 +106,8 @@ pub use target::{TargetCfgConfig, TargetConfig}; mod environment; use environment::Env; +use super::auth::RegistryConfig; + // Helper macro for creating typed access methods. macro_rules! get_value_typed { ($name:ident, $ty:ty, $variant:ident, $expected:expr) => { @@ -208,6 +210,8 @@ pub struct Config { /// Cache of credentials from configuration or credential providers. /// Maps from url to credential value. credential_cache: LazyCell>>, + /// Cache of registry config from from the `[registries]` table. + registry_config: LazyCell>>>, /// Lock, if held, of the global package cache along with the number of /// acquisitions so far. package_cache_lock: RefCell, usize)>>, @@ -299,6 +303,7 @@ impl Config { env, updated_sources: LazyCell::new(), credential_cache: LazyCell::new(), + registry_config: LazyCell::new(), package_cache_lock: RefCell::new(None), http_config: LazyCell::new(), future_incompat_config: LazyCell::new(), @@ -488,6 +493,13 @@ impl Config { .borrow_mut() } + /// Cache of already parsed registries from the `[registries]` table. + pub(crate) fn registry_config(&self) -> RefMut<'_, HashMap>> { + self.registry_config + .borrow_with(|| RefCell::new(HashMap::new())) + .borrow_mut() + } + /// Gets all config values from disk. /// /// This will lazy-load the values as necessary. Callers are responsible diff --git a/tests/testsuite/alt_registry.rs b/tests/testsuite/alt_registry.rs index ac60ca92fa88..91157cd5327c 100644 --- a/tests/testsuite/alt_registry.rs +++ b/tests/testsuite/alt_registry.rs @@ -1506,3 +1506,44 @@ fn publish_with_transitive_dep() { .build(); p2.cargo("publish").run(); } + +#[cargo_test] +fn warn_for_unused_fields() { + let _ = RegistryBuilder::new() + .no_configure_token() + .alternative() + .build(); + let p = project() + .file("src/lib.rs", "") + .file( + ".cargo/config.toml", + "[registry] + unexpected-field = 'foo' + [registries.alternative] + unexpected-field = 'foo' + ", + ) + .build(); + + p.cargo("publish --registry alternative") + .with_status(101) + .with_stderr( + "\ +[UPDATING] `alternative` index +[WARNING] unused config key `registries.alternative.unexpected-field` in `[..]config.toml` +[ERROR] no token found for `alternative`, please run `cargo login --registry alternative` +or use environment variable CARGO_REGISTRIES_ALTERNATIVE_TOKEN", + ) + .run(); + + p.cargo("publish --registry crates-io") + .with_status(101) + .with_stderr( + "\ +[UPDATING] crates.io index +[WARNING] unused config key `registry.unexpected-field` in `[..]config.toml` +[ERROR] no token found, please run `cargo login` +or use environment variable CARGO_REGISTRY_TOKEN", + ) + .run(); +} From 580bbf90f88a3f0dcb563a8632414bc175dbc3ef Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Thu, 3 Aug 2023 15:14:02 -0700 Subject: [PATCH 03/17] Update pretty_env_logger to 0.5 --- Cargo.lock | 56 +++++++----------------------------------------------- Cargo.toml | 2 +- 2 files changed, 8 insertions(+), 50 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cffb6b1dd024..220494c9490e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -111,17 +111,6 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" -[[package]] -name = "atty" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" -dependencies = [ - "hermit-abi 0.1.19", - "libc", - "winapi", -] - [[package]] name = "autocfg" version = "1.1.0" @@ -285,7 +274,7 @@ dependencies = [ "crates-io", "curl", "curl-sys", - "env_logger 0.10.0", + "env_logger", "filetime", "flate2", "fwdansi", @@ -298,7 +287,7 @@ dependencies = [ "hmac", "home 0.5.5", "http-auth", - "humantime 2.1.0", + "humantime", "ignore", "im-rc", "indexmap", @@ -838,26 +827,13 @@ dependencies = [ "zeroize", ] -[[package]] -name = "env_logger" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44533bbbb3bb3c1fa17d9f2e4e38bbbaf8396ba82193c4cb1b6445d711445d36" -dependencies = [ - "atty", - "humantime 1.3.0", - "log", - "regex", - "termcolor", -] - [[package]] name = "env_logger" version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85cdab6a89accf66733ad5a1693a4dcced6aeff64602b634530dd73c1f3ee9f0" dependencies = [ - "humantime 2.1.0", + "humantime", "is-terminal", "log", "regex", @@ -1742,15 +1718,6 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a" -[[package]] -name = "hermit-abi" -version = "0.1.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" -dependencies = [ - "libc", -] - [[package]] name = "hermit-abi" version = "0.2.6" @@ -1815,15 +1782,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "humantime" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df004cfca50ef23c36850aaaa59ad52cc70d0e90243c3c7737a4dd32dc7a3c4f" -dependencies = [ - "quick-error 1.2.3", -] - [[package]] name = "humantime" version = "2.1.0" @@ -2526,11 +2484,11 @@ dependencies = [ [[package]] name = "pretty_env_logger" -version = "0.4.0" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "926d36b9553851b8b0005f1275891b392ee4d2d833852c417ed025477350fb9d" +checksum = "865724d4dbe39d9f3dd3b52b88d859d66bcb2d6a0acfd5ea68a65fb66d4bdc1c" dependencies = [ - "env_logger 0.7.1", + "env_logger", "log", ] @@ -3779,7 +3737,7 @@ dependencies = [ "cargo", "cargo-util", "clap", - "env_logger 0.10.0", + "env_logger", "git2", "log", ] diff --git a/Cargo.toml b/Cargo.toml index d1bfa0016e96..eea85947bd17 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ pathdiff = "0.2" percent-encoding = "2.3" pkg-config = "0.3.27" pretty_assertions = "1.4.0" -pretty_env_logger = "0.4" +pretty_env_logger = "0.5.0" proptest = "1.2.0" pulldown-cmark = { version = "0.9.3", default-features = false } rand = "0.8.5" From 1df0f1d7349647fdf66d95e628d96495debb0e3c Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Sat, 5 Aug 2023 12:11:07 -0700 Subject: [PATCH 04/17] Add allow(internal_features) --- tests/testsuite/cargo_features.rs | 1 + tests/testsuite/custom_target.rs | 2 ++ tests/testsuite/doc.rs | 1 + 3 files changed, 4 insertions(+) diff --git a/tests/testsuite/cargo_features.rs b/tests/testsuite/cargo_features.rs index 6e5531431749..ed5f53a1e6d4 100644 --- a/tests/testsuite/cargo_features.rs +++ b/tests/testsuite/cargo_features.rs @@ -295,6 +295,7 @@ fn allow_features_to_rustc() { .file( "src/lib.rs", r#" + #![allow(internal_features)] #![feature(test_2018_feature)] "#, ) diff --git a/tests/testsuite/custom_target.rs b/tests/testsuite/custom_target.rs index b7ad4d835ec3..491d3233ca3e 100644 --- a/tests/testsuite/custom_target.rs +++ b/tests/testsuite/custom_target.rs @@ -4,6 +4,7 @@ use cargo_test_support::{basic_manifest, project}; use std::fs; const MINIMAL_LIB: &str = r#" +#![allow(internal_features)] #![feature(no_core)] #![feature(lang_items)] #![no_core] @@ -80,6 +81,7 @@ fn custom_target_dependency() { .file( "src/lib.rs", r#" + #![allow(internal_features)] #![feature(no_core)] #![feature(lang_items)] #![feature(auto_traits)] diff --git a/tests/testsuite/doc.rs b/tests/testsuite/doc.rs index 265457eb9a54..481df859045f 100644 --- a/tests/testsuite/doc.rs +++ b/tests/testsuite/doc.rs @@ -756,6 +756,7 @@ fn doc_target() { .file( "src/lib.rs", r#" + #![allow(internal_features)] #![feature(no_core, lang_items)] #![no_core] From 988eebe2220a0f3dec9b780cd671fcf2e3526f0b Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Sat, 5 Aug 2023 12:13:08 -0700 Subject: [PATCH 05/17] Rustfmt a let-else statement --- src/cargo/util/errors.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cargo/util/errors.rs b/src/cargo/util/errors.rs index 91258c53c08b..9589e1ae33ec 100644 --- a/src/cargo/util/errors.rs +++ b/src/cargo/util/errors.rs @@ -87,7 +87,9 @@ impl HttpNotSuccessful { .headers .iter() .filter(|header| { - let Some((name, _)) = header.split_once(":") else { return false }; + let Some((name, _)) = header.split_once(":") else { + return false; + }; DEBUG_HEADERS.contains(&name.to_ascii_lowercase().trim()) }) .collect(); From 850ff884e8dab739ca6fbeabdc8c7b9664a4babf Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Sat, 5 Aug 2023 14:27:40 -0700 Subject: [PATCH 06/17] Update miow from 0.5.0 to 0.6.0 --- Cargo.lock | 6 +++--- Cargo.toml | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 220494c9490e..9a6326e01bf2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2112,11 +2112,11 @@ dependencies = [ [[package]] name = "miow" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ffbca2f655e33c08be35d87278e5b18b89550a37dbd598c20db92f6a471123" +checksum = "359f76430b20a79f9e20e115b3428614e654f04fab314482fc0fda0ebd3c6044" dependencies = [ - "windows-sys 0.42.0", + "windows-sys 0.48.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 34f1258bf2b2..218d26606523 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -60,7 +60,7 @@ libc = "0.2.147" libgit2-sys = "0.15.2" log = "0.4.19" memchr = "2.5.0" -miow = "0.5.0" +miow = "0.6.0" opener = "0.6.1" openssl ="0.10.55" os_info = "3.7.0" From c4b0e6b95a5fdd1a40934894ce2fa6941cf76cc2 Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Sat, 5 Aug 2023 14:28:15 -0700 Subject: [PATCH 07/17] Update schannel from 0.1.21 to 0.1.22 --- Cargo.lock | 113 +++++++++++++---------------------------------------- 1 file changed, 28 insertions(+), 85 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9a6326e01bf2..0d997e2c2150 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -80,7 +80,7 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5ca11d4be1bab0c8bc8734a9aa7bf4ee8316d462a08c6ac5052f888fef5b494b" dependencies = [ - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -90,7 +90,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "180abfa45703aebe0093f79badacc01b8fd4ea2e35118747e5811127f926e188" dependencies = [ "anstyle", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -329,7 +329,7 @@ dependencies = [ "unicode-xid", "url", "walkdir", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -373,7 +373,7 @@ name = "cargo-credential-wincred" version = "0.3.0" dependencies = [ "cargo-credential", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -419,7 +419,7 @@ dependencies = [ "time", "toml", "url", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -439,7 +439,7 @@ dependencies = [ "shell-escape", "tempfile", "walkdir", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -854,7 +854,7 @@ checksum = "4bcfec3a70f97c962c307b2d2c56e358cf1d00b558d74262b5f929ee8cc7e73a" dependencies = [ "errno-dragonfly", "libc", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -907,7 +907,7 @@ dependencies = [ "cfg-if", "libc", "redox_syscall 0.2.16", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -1763,14 +1763,14 @@ version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5444c27eef6923071f7ebcc33e3444508466a76f7a2b93da00ed6e19f30c1ddb" dependencies = [ - "windows-sys 0.48.0", + "windows-sys", ] [[package]] name = "home" version = "0.5.7" dependencies = [ - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -1876,7 +1876,7 @@ checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" dependencies = [ "hermit-abi 0.3.1", "libc", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -1888,7 +1888,7 @@ dependencies = [ "hermit-abi 0.3.1", "io-lifetimes", "rustix 0.37.20", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -2116,7 +2116,7 @@ version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "359f76430b20a79f9e20e115b3428614e654f04fab314482fc0fda0ebd3c6044" dependencies = [ - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -2141,7 +2141,7 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec60c60a693226186f5d6edf073232bfb6464ed97eb22cf3b01c1e8198fd97f5" dependencies = [ - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -2738,7 +2738,7 @@ dependencies = [ "io-lifetimes", "libc", "linux-raw-sys 0.3.8", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -2751,7 +2751,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.4.5", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -2783,11 +2783,11 @@ dependencies = [ [[package]] name = "schannel" -version = "0.1.21" +version = "0.1.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "713cfb06c7059f3588fb8044c0fad1d09e3c01d225e25b9220dbfdcf16dbb1b3" +checksum = "0c3733bf4cf7ea0880754e19cb5a462007c4a8c1914bff372ccc95b464f1df88" dependencies = [ - "windows-sys 0.42.0", + "windows-sys", ] [[package]] @@ -3121,7 +3121,7 @@ dependencies = [ "fastrand 2.0.0", "redox_syscall 0.3.5", "rustix 0.38.6", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -3140,7 +3140,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e6bf6f19e9f8ed8d4048dc22981458ebcf406d67e94cd422e5ecd73d63b3237" dependencies = [ "rustix 0.37.20", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -3593,21 +3593,6 @@ dependencies = [ "windows-targets", ] -[[package]] -name = "windows-sys" -version = "0.42.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" -dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", -] - [[package]] name = "windows-sys" version = "0.48.0" @@ -3623,93 +3608,51 @@ version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b1eb6f0cd7c80c79759c929114ef071b87354ce476d9d94271031c0497adfd5" dependencies = [ - "windows_aarch64_gnullvm 0.48.0", - "windows_aarch64_msvc 0.48.0", - "windows_i686_gnu 0.48.0", - "windows_i686_msvc 0.48.0", - "windows_x86_64_gnu 0.48.0", - "windows_x86_64_gnullvm 0.48.0", - "windows_x86_64_msvc 0.48.0", + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", ] -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" - [[package]] name = "windows_aarch64_gnullvm" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc" -[[package]] -name = "windows_aarch64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" - [[package]] name = "windows_aarch64_msvc" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3" -[[package]] -name = "windows_i686_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" - [[package]] name = "windows_i686_gnu" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241" -[[package]] -name = "windows_i686_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" - [[package]] name = "windows_i686_msvc" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00" -[[package]] -name = "windows_x86_64_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" - [[package]] name = "windows_x86_64_gnu" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" - [[package]] name = "windows_x86_64_gnullvm" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953" -[[package]] -name = "windows_x86_64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" - [[package]] name = "windows_x86_64_msvc" version = "0.48.0" From 9f0565e985b85528166aa5011b8088c014c15646 Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Sat, 5 Aug 2023 09:31:50 +0100 Subject: [PATCH 08/17] chore: add `tracing` crate --- Cargo.lock | 41 ++++++++++++++++++++++++++++++ Cargo.toml | 2 ++ crates/cargo-util/Cargo.toml | 1 + crates/xtask-bump-check/Cargo.toml | 1 + 4 files changed, 45 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 0d997e2c2150..972c9749940a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -324,6 +324,7 @@ dependencies = [ "time", "toml", "toml_edit", + "tracing", "unicase", "unicode-width", "unicode-xid", @@ -438,6 +439,7 @@ dependencies = [ "sha2", "shell-escape", "tempfile", + "tracing", "walkdir", "windows-sys", ] @@ -2422,6 +2424,12 @@ dependencies = [ "sha2", ] +[[package]] +name = "pin-project-lite" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c40d25201921e5ff0c862a505c6557ea88568a4e3ace775ab55e93f2f4f9d57" + [[package]] name = "pkcs8" version = "0.10.2" @@ -3261,6 +3269,38 @@ dependencies = [ "winnow", ] +[[package]] +name = "tracing" +version = "0.1.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8" +dependencies = [ + "cfg-if", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f4f31f56159e98206da9efd823404b79b6ef3143b4a7ab76e67b1751b25a4ab" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.28", +] + +[[package]] +name = "tracing-core" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0955b8137a1df6f1a2e9a37d8a6656291ff0297c1a97c24e0d8425fe2312f79a" +dependencies = [ + "once_cell", +] + [[package]] name = "typenum" version = "1.16.0" @@ -3683,6 +3723,7 @@ dependencies = [ "env_logger", "git2", "log", + "tracing", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 218d26606523..d2ee3275ac76 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -94,6 +94,7 @@ thiserror = "1.0.44" time = { version = "0.3", features = ["parsing", "formatting", "serde"] } toml = "0.7.6" toml_edit = "0.19.14" +tracing = "0.1.37" unicase = "2.6.0" unicode-width = "0.1.10" unicode-xid = "0.2.4" @@ -178,6 +179,7 @@ termcolor.workspace = true time.workspace = true toml.workspace = true toml_edit.workspace = true +tracing.workspace = true unicase.workspace = true unicode-width.workspace = true unicode-xid.workspace = true diff --git a/crates/cargo-util/Cargo.toml b/crates/cargo-util/Cargo.toml index 6c5efba83778..4f5a50b1bf34 100644 --- a/crates/cargo-util/Cargo.toml +++ b/crates/cargo-util/Cargo.toml @@ -18,6 +18,7 @@ log.workspace = true same-file.workspace = true shell-escape.workspace = true tempfile.workspace = true +tracing.workspace = true walkdir.workspace = true [target.'cfg(target_os = "macos")'.dependencies] diff --git a/crates/xtask-bump-check/Cargo.toml b/crates/xtask-bump-check/Cargo.toml index b29e5595fcbe..13e100e286bb 100644 --- a/crates/xtask-bump-check/Cargo.toml +++ b/crates/xtask-bump-check/Cargo.toml @@ -12,3 +12,4 @@ clap.workspace = true env_logger.workspace = true git2.workspace = true log.workspace = true +tracing.workspace = true From af1a78b424db7d517a359fd23d548e7fb30be98f Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Sat, 5 Aug 2023 09:07:45 +0100 Subject: [PATCH 09/17] refactor: find & replace `log::` -> `tracing::` Except HTTP network debugging --- crates/cargo-util/src/paths.rs | 20 +++++++++---------- crates/cargo-util/src/process_builder.rs | 4 ++-- crates/xtask-bump-check/src/xtask.rs | 12 +++++------ .../compiler/build_context/target_info.rs | 6 +++--- .../compiler/context/compilation_files.rs | 2 +- src/cargo/core/compiler/fingerprint/mod.rs | 4 ++-- src/cargo/core/compiler/future_incompat.rs | 2 +- src/cargo/core/compiler/job_queue/mod.rs | 4 ++-- src/cargo/core/compiler/mod.rs | 4 ++-- src/cargo/core/compiler/output_depinfo.rs | 2 +- src/cargo/core/compiler/rustdoc.rs | 6 +++--- src/cargo/core/compiler/timings.rs | 4 ++-- src/cargo/core/compiler/unit_dependencies.rs | 2 +- src/cargo/core/dependency.rs | 2 +- src/cargo/core/package.rs | 2 +- src/cargo/core/registry.rs | 6 +++--- src/cargo/core/resolver/conflict_cache.rs | 2 +- src/cargo/core/resolver/context.rs | 2 +- src/cargo/core/resolver/dep_cache.rs | 2 +- src/cargo/core/resolver/encode.rs | 2 +- src/cargo/core/resolver/features.rs | 14 ++++++------- src/cargo/core/resolver/mod.rs | 2 +- src/cargo/core/source/source_id.rs | 2 +- src/cargo/core/workspace.rs | 2 +- src/cargo/lib.rs | 2 +- src/cargo/ops/cargo_compile/mod.rs | 2 +- src/cargo/ops/cargo_generate_lockfile.rs | 2 +- src/cargo/ops/cargo_new.rs | 2 +- src/cargo/ops/cargo_package.rs | 2 +- src/cargo/ops/cargo_read_manifest.rs | 2 +- src/cargo/ops/fix.rs | 2 +- src/cargo/ops/resolve.rs | 2 +- src/cargo/ops/tree/graph.rs | 2 +- src/cargo/sources/config.rs | 2 +- src/cargo/sources/git/known_hosts.rs | 2 +- src/cargo/sources/git/oxide.rs | 2 +- src/cargo/sources/git/source.rs | 2 +- src/cargo/sources/git/utils.rs | 8 ++++---- src/cargo/sources/path.rs | 6 +++--- src/cargo/sources/registry/http_remote.rs | 8 ++++---- src/cargo/sources/registry/index.rs | 20 +++++++++---------- src/cargo/sources/registry/mod.rs | 6 +++--- src/cargo/sources/registry/remote.rs | 2 +- src/cargo/util/auth/mod.rs | 16 +++++++-------- src/cargo/util/config/mod.rs | 4 ++-- src/cargo/util/config/target.rs | 2 +- src/cargo/util/credential/process.rs | 10 +++++----- src/cargo/util/diagnostic_server.rs | 2 +- src/cargo/util/job.rs | 2 +- src/cargo/util/network/mod.rs | 2 +- src/cargo/util/network/sleep.rs | 2 +- src/cargo/util/rustc.rs | 2 +- src/cargo/util/toml/embedded.rs | 4 ++-- src/cargo/util/toml/mod.rs | 2 +- 54 files changed, 117 insertions(+), 117 deletions(-) diff --git a/crates/cargo-util/src/paths.rs b/crates/cargo-util/src/paths.rs index 4a917821b7e8..ce675585979f 100644 --- a/crates/cargo-util/src/paths.rs +++ b/crates/cargo-util/src/paths.rs @@ -237,7 +237,7 @@ pub fn mtime_recursive(path: &Path) -> Result { Err(e) => { // Ignore errors while walking. If Cargo can't access it, the // build script probably can't access it, either. - log::debug!("failed to determine mtime while walking directory: {}", e); + tracing::debug!("failed to determine mtime while walking directory: {}", e); None } }) @@ -252,7 +252,7 @@ pub fn mtime_recursive(path: &Path) -> Result { // I'm not sure when this is really possible (maybe a // race with unlinking?). Regardless, if Cargo can't // read it, the build script probably can't either. - log::debug!( + tracing::debug!( "failed to determine mtime while fetching symlink metadata of {}: {}", e.path().display(), err @@ -271,7 +271,7 @@ pub fn mtime_recursive(path: &Path) -> Result { // Can't access the symlink target. If Cargo can't // access it, the build script probably can't access // it either. - log::debug!( + tracing::debug!( "failed to determine mtime of symlink target for {}: {}", e.path().display(), err @@ -286,7 +286,7 @@ pub fn mtime_recursive(path: &Path) -> Result { // I'm not sure when this is really possible (maybe a // race with unlinking?). Regardless, if Cargo can't // read it, the build script probably can't either. - log::debug!( + tracing::debug!( "failed to determine mtime while fetching metadata of {}: {}", e.path().display(), err @@ -314,7 +314,7 @@ pub fn set_invocation_time(path: &Path) -> Result { "This file has an mtime of when this was started.", )?; let ft = mtime(×tamp)?; - log::debug!("invocation time for {:?} is {}", path, ft); + tracing::debug!("invocation time for {:?} is {}", path, ft); Ok(ft) } @@ -508,7 +508,7 @@ pub fn link_or_copy(src: impl AsRef, dst: impl AsRef) -> Result<()> } fn _link_or_copy(src: &Path, dst: &Path) -> Result<()> { - log::debug!("linking {} to {}", src.display(), dst.display()); + tracing::debug!("linking {} to {}", src.display(), dst.display()); if same_file::is_same_file(src, dst).unwrap_or(false) { return Ok(()); } @@ -567,7 +567,7 @@ fn _link_or_copy(src: &Path, dst: &Path) -> Result<()> { }; link_result .or_else(|err| { - log::debug!("link failed {}. falling back to fs::copy", err); + tracing::debug!("link failed {}. falling back to fs::copy", err); fs::copy(src, dst).map(|_| ()) }) .with_context(|| { @@ -598,8 +598,8 @@ pub fn copy, Q: AsRef>(from: P, to: Q) -> Result { pub fn set_file_time_no_err>(path: P, time: FileTime) { let path = path.as_ref(); match filetime::set_file_times(path, time, time) { - Ok(()) => log::debug!("set file mtime {} to {}", path.display(), time), - Err(e) => log::warn!( + Ok(()) => tracing::debug!("set file mtime {} to {}", path.display(), time), + Err(e) => tracing::warn!( "could not set mtime of {} to {}: {:?}", path.display(), time, @@ -621,7 +621,7 @@ pub fn strip_prefix_canonical>( let safe_canonicalize = |path: &Path| match path.canonicalize() { Ok(p) => p, Err(e) => { - log::warn!("cannot canonicalize {:?}: {:?}", path, e); + tracing::warn!("cannot canonicalize {:?}: {:?}", path, e); path.to_path_buf() } }; diff --git a/crates/cargo-util/src/process_builder.rs b/crates/cargo-util/src/process_builder.rs index 76392f2564b0..b197b95b1306 100644 --- a/crates/cargo-util/src/process_builder.rs +++ b/crates/cargo-util/src/process_builder.rs @@ -449,7 +449,7 @@ impl ProcessBuilder { arg.push(tmp.path()); let mut cmd = self.build_command_without_args(); cmd.arg(arg); - log::debug!("created argfile at {} for {self}", tmp.path().display()); + tracing::debug!("created argfile at {} for {self}", tmp.path().display()); let cap = self.get_args().map(|arg| arg.len() + 1).sum::(); let mut buf = Vec::with_capacity(cap); @@ -558,7 +558,7 @@ fn piped(cmd: &mut Command, pipe_stdin: bool) -> &mut Command { fn close_tempfile_and_log_error(file: NamedTempFile) { file.close().unwrap_or_else(|e| { - log::warn!("failed to close temporary file: {e}"); + tracing::warn!("failed to close temporary file: {e}"); }); } diff --git a/crates/xtask-bump-check/src/xtask.rs b/crates/xtask-bump-check/src/xtask.rs index 042615f4ed0e..b020e62da80d 100644 --- a/crates/xtask-bump-check/src/xtask.rs +++ b/crates/xtask-bump-check/src/xtask.rs @@ -126,7 +126,7 @@ fn bump_check(args: &clap::ArgMatches, config: &mut cargo::util::Config) -> Carg for referenced_member in checkout_ws(&ws, &repo, referenced_commit)?.members() { let Some(changed_member) = changed_members.get(referenced_member) else { let name = referenced_member.name().as_str(); - log::trace!("skipping {name}, may be removed or not published"); + tracing::trace!("skipping {name}, may be removed or not published"); continue; }; @@ -264,10 +264,10 @@ fn get_referenced_commit<'a>( let referenced_commit = if rev_id == stable_commit.id() { None } else if rev_id == beta_commit.id() { - log::trace!("stable branch from `{}`", stable.name().unwrap().unwrap()); + tracing::trace!("stable branch from `{}`", stable.name().unwrap().unwrap()); Some(stable_commit) } else { - log::trace!("beta branch from `{}`", beta.name().unwrap().unwrap()); + tracing::trace!("beta branch from `{}`", beta.name().unwrap().unwrap()); Some(beta_commit) }; @@ -287,11 +287,11 @@ fn beta_and_stable_branch(repo: &git2::Repository) -> CargoResult<[git2::Branch< let (branch, _) = branch?; let name = branch.name()?.unwrap(); let Some((_, version)) = name.split_once("/rust-") else { - log::trace!("branch `{name}` is not in the format of `/rust-`"); + tracing::trace!("branch `{name}` is not in the format of `/rust-`"); continue; }; let Ok(version) = version.to_semver() else { - log::trace!("branch `{name}` is not a valid semver: `{version}`"); + tracing::trace!("branch `{name}` is not a valid semver: `{version}`"); continue; }; release_branches.push((version, branch)); @@ -380,7 +380,7 @@ fn check_crates_io<'a>( } }; if possibilities.is_empty() { - log::trace!("dep `{name}` has no version greater than or equal to `{current}`"); + tracing::trace!("dep `{name}` has no version greater than or equal to `{current}`"); } else { needs_bump.push(member); } diff --git a/src/cargo/core/compiler/build_context/target_info.rs b/src/cargo/core/compiler/build_context/target_info.rs index e6e41c5226fb..632ca9cf13de 100644 --- a/src/cargo/core/compiler/build_context/target_info.rs +++ b/src/cargo/core/compiler/build_context/target_info.rs @@ -1065,7 +1065,7 @@ impl RustDocFingerprint { if fingerprint.rustc_vv == actual_rustdoc_target_data.rustc_vv { return Ok(()); } else { - log::debug!( + tracing::debug!( "doc fingerprint changed:\noriginal:\n{}\nnew:\n{}", fingerprint.rustc_vv, actual_rustdoc_target_data.rustc_vv @@ -1073,11 +1073,11 @@ impl RustDocFingerprint { } } Err(e) => { - log::debug!("could not deserialize {:?}: {}", fingerprint_path, e); + tracing::debug!("could not deserialize {:?}: {}", fingerprint_path, e); } }; // Fingerprint does not match, delete the doc directories and write a new fingerprint. - log::debug!( + tracing::debug!( "fingerprint {:?} mismatch, clearing doc directories", fingerprint_path ); diff --git a/src/cargo/core/compiler/context/compilation_files.rs b/src/cargo/core/compiler/context/compilation_files.rs index 1c9d28461f98..f781effdfd19 100644 --- a/src/cargo/core/compiler/context/compilation_files.rs +++ b/src/cargo/core/compiler/context/compilation_files.rs @@ -7,7 +7,7 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; use lazycell::LazyCell; -use log::debug; +use tracing::debug; use super::{BuildContext, CompileKind, Context, FileFlavor, Layout}; use crate::core::compiler::{CompileMode, CompileTarget, CrateType, FileType, Unit}; diff --git a/src/cargo/core/compiler/fingerprint/mod.rs b/src/cargo/core/compiler/fingerprint/mod.rs index 7bb852e79e5f..54fbcc9a4ae5 100644 --- a/src/cargo/core/compiler/fingerprint/mod.rs +++ b/src/cargo/core/compiler/fingerprint/mod.rs @@ -366,7 +366,7 @@ use std::time::SystemTime; use anyhow::{bail, format_err, Context as _}; use cargo_util::{paths, ProcessBuilder}; use filetime::FileTime; -use log::{debug, info}; +use tracing::{debug, info}; use serde::de; use serde::ser; use serde::{Deserialize, Serialize}; @@ -1815,7 +1815,7 @@ pub fn parse_dep_info( let info = match EncodedDepInfo::parse(&data) { Some(info) => info, None => { - log::warn!("failed to parse cargo's dep-info at {:?}", dep_info); + tracing::warn!("failed to parse cargo's dep-info at {:?}", dep_info); return Ok(None); } }; diff --git a/src/cargo/core/compiler/future_incompat.rs b/src/cargo/core/compiler/future_incompat.rs index 955dfb8f2d0e..ccea28b9416a 100644 --- a/src/cargo/core/compiler/future_incompat.rs +++ b/src/cargo/core/compiler/future_incompat.rs @@ -417,7 +417,7 @@ pub fn save_and_display_report( let current_reports = match OnDiskReports::load(bcx.ws) { Ok(r) => r, Err(e) => { - log::debug!( + tracing::debug!( "saving future-incompatible reports failed to load current reports: {:?}", e ); diff --git a/src/cargo/core/compiler/job_queue/mod.rs b/src/cargo/core/compiler/job_queue/mod.rs index 6e8866b2b064..96bf1543f1ea 100644 --- a/src/cargo/core/compiler/job_queue/mod.rs +++ b/src/cargo/core/compiler/job_queue/mod.rs @@ -125,7 +125,7 @@ use std::time::Duration; use anyhow::{format_err, Context as _}; use cargo_util::ProcessBuilder; use jobserver::{Acquired, HelperThread}; -use log::{debug, trace}; +use tracing::{debug, trace}; use semver::Version; pub use self::job::Freshness::{self, Dirty, Fresh}; @@ -840,7 +840,7 @@ impl<'cfg> DrainState<'cfg> { } err_state.count += 1; } else { - log::warn!("{:?}", new_err.error); + tracing::warn!("{:?}", new_err.error); } } diff --git a/src/cargo/core/compiler/mod.rs b/src/cargo/core/compiler/mod.rs index 31e63c226b77..7024a2ac561f 100644 --- a/src/cargo/core/compiler/mod.rs +++ b/src/cargo/core/compiler/mod.rs @@ -65,7 +65,7 @@ use std::sync::Arc; use anyhow::{Context as _, Error}; use lazycell::LazyCell; -use log::{debug, trace}; +use tracing::{debug, trace}; pub use self::build_config::{BuildConfig, CompileMode, MessageFormat, TimingOutput}; pub use self::build_context::{ @@ -368,7 +368,7 @@ fn rustc(cx: &mut Context<'_, '_>, unit: &Unit, exec: &Arc) -> Car // See rust-lang/cargo#8348. if output.hardlink.is_some() && output.path.exists() { _ = paths::remove_file(&output.path).map_err(|e| { - log::debug!( + tracing::debug!( "failed to delete previous output file `{:?}`: {e:?}", output.path ); diff --git a/src/cargo/core/compiler/output_depinfo.rs b/src/cargo/core/compiler/output_depinfo.rs index d659d620cbc3..db98adf92bb6 100644 --- a/src/cargo/core/compiler/output_depinfo.rs +++ b/src/cargo/core/compiler/output_depinfo.rs @@ -9,7 +9,7 @@ use std::path::{Path, PathBuf}; use super::{fingerprint, Context, FileFlavor, Unit}; use crate::util::{internal, CargoResult}; use cargo_util::paths; -use log::debug; +use tracing::debug; /// Bacially just normalizes a given path and converts it to a string. fn render_filename>(path: P, basedir: Option<&str>) -> CargoResult { diff --git a/src/cargo/core/compiler/rustdoc.rs b/src/cargo/core/compiler/rustdoc.rs index f6fdd005a3fa..aa4bd0dd4cba 100644 --- a/src/cargo/core/compiler/rustdoc.rs +++ b/src/cargo/core/compiler/rustdoc.rs @@ -112,7 +112,7 @@ pub fn add_root_urls( ) -> CargoResult<()> { let config = cx.bcx.config; if !config.cli_unstable().rustdoc_map { - log::debug!("`doc.extern-map` ignored, requires -Zrustdoc-map flag"); + tracing::debug!("`doc.extern-map` ignored, requires -Zrustdoc-map flag"); return Ok(()); } let map = config.doc_extern_map()?; @@ -125,7 +125,7 @@ pub fn add_root_urls( if let Ok(index_url) = config.get_registry_index(name) { Some((name, index_url)) } else { - log::warn!( + tracing::warn!( "`doc.extern-map.{}` specifies a registry that is not defined", name ); @@ -181,7 +181,7 @@ pub fn add_root_urls( })?; Some(url.to_string()) } else { - log::warn!( + tracing::warn!( "`doc.extern-map.std` is \"local\", but local docs don't appear to exist at {}", html_root.display() ); diff --git a/src/cargo/core/compiler/timings.rs b/src/cargo/core/compiler/timings.rs index 0e0dc03eeeda..57ded9bf84b3 100644 --- a/src/cargo/core/compiler/timings.rs +++ b/src/cargo/core/compiler/timings.rs @@ -122,7 +122,7 @@ impl<'cfg> Timings<'cfg> { match State::current() { Ok(state) => Some(state), Err(e) => { - log::info!("failed to get CPU state, CPU tracking disabled: {:?}", e); + tracing::info!("failed to get CPU state, CPU tracking disabled: {:?}", e); None } } @@ -276,7 +276,7 @@ impl<'cfg> Timings<'cfg> { let current = match State::current() { Ok(s) => s, Err(e) => { - log::info!("failed to get CPU state: {:?}", e); + tracing::info!("failed to get CPU state: {:?}", e); return; } }; diff --git a/src/cargo/core/compiler/unit_dependencies.rs b/src/cargo/core/compiler/unit_dependencies.rs index 369fd83180d6..686822356057 100644 --- a/src/cargo/core/compiler/unit_dependencies.rs +++ b/src/cargo/core/compiler/unit_dependencies.rs @@ -17,7 +17,7 @@ use std::collections::{HashMap, HashSet}; -use log::trace; +use tracing::trace; use crate::core::compiler::artifact::match_artifacts_kind_with_targets; use crate::core::compiler::unit_graph::{UnitDep, UnitGraph}; diff --git a/src/cargo/core/dependency.rs b/src/cargo/core/dependency.rs index 0b3aba8ada5b..6340ce414244 100644 --- a/src/cargo/core/dependency.rs +++ b/src/cargo/core/dependency.rs @@ -1,5 +1,5 @@ use cargo_platform::Platform; -use log::trace; +use tracing::trace; use semver::VersionReq; use serde::ser; use serde::Serialize; diff --git a/src/cargo/core/package.rs b/src/cargo/core/package.rs index 093c64d72d30..8f80f6a45cfb 100644 --- a/src/cargo/core/package.rs +++ b/src/cargo/core/package.rs @@ -13,7 +13,7 @@ use bytesize::ByteSize; use curl::easy::Easy; use curl::multi::{EasyHandle, Multi}; use lazycell::LazyCell; -use log::debug; +use tracing::debug; use semver::Version; use serde::Serialize; diff --git a/src/cargo/core/registry.rs b/src/cargo/core/registry.rs index e20531b709c2..da3d612d0474 100644 --- a/src/cargo/core/registry.rs +++ b/src/cargo/core/registry.rs @@ -8,7 +8,7 @@ use crate::util::errors::CargoResult; use crate::util::interning::InternedString; use crate::util::{CanonicalUrl, Config}; use anyhow::{bail, Context as _}; -use log::{debug, trace}; +use tracing::{debug, trace}; use url::Url; /// Source of information about a group of packages. @@ -876,7 +876,7 @@ fn summary_for_patch( // Since the locked patch did not match anything, try the unlocked one. let orig_matches = ready!(source.query_vec(orig_patch, QueryKind::Exact)).unwrap_or_else(|e| { - log::warn!( + tracing::warn!( "could not determine unlocked summaries for dep {:?}: {:?}", orig_patch, e @@ -895,7 +895,7 @@ fn summary_for_patch( let name_summaries = ready!(source.query_vec(&name_only_dep, QueryKind::Exact)).unwrap_or_else(|e| { - log::warn!( + tracing::warn!( "failed to do name-only summary query for {:?}: {:?}", name_only_dep, e diff --git a/src/cargo/core/resolver/conflict_cache.rs b/src/cargo/core/resolver/conflict_cache.rs index 10c41761d20a..fba497506d4f 100644 --- a/src/cargo/core/resolver/conflict_cache.rs +++ b/src/cargo/core/resolver/conflict_cache.rs @@ -1,6 +1,6 @@ use std::collections::{BTreeMap, HashMap, HashSet}; -use log::trace; +use tracing::trace; use super::types::ConflictMap; use crate::core::resolver::Context; diff --git a/src/cargo/core/resolver/context.rs b/src/cargo/core/resolver/context.rs index 4854dcde7e2d..5f444a157ff4 100644 --- a/src/cargo/core/resolver/context.rs +++ b/src/cargo/core/resolver/context.rs @@ -6,7 +6,7 @@ use crate::core::{Dependency, PackageId, SourceId, Summary}; use crate::util::interning::InternedString; use crate::util::Graph; use anyhow::format_err; -use log::debug; +use tracing::debug; use std::collections::HashMap; use std::num::NonZeroU64; diff --git a/src/cargo/core/resolver/dep_cache.rs b/src/cargo/core/resolver/dep_cache.rs index 54b0ce97ff27..77101d4a439b 100644 --- a/src/cargo/core/resolver/dep_cache.rs +++ b/src/cargo/core/resolver/dep_cache.rs @@ -23,7 +23,7 @@ use crate::util::errors::CargoResult; use crate::util::interning::InternedString; use anyhow::Context as _; -use log::debug; +use tracing::debug; use std::collections::{BTreeSet, HashMap, HashSet}; use std::rc::Rc; use std::task::Poll; diff --git a/src/cargo/core/resolver/encode.rs b/src/cargo/core/resolver/encode.rs index 000044d2168a..7b023cd8907e 100644 --- a/src/cargo/core/resolver/encode.rs +++ b/src/cargo/core/resolver/encode.rs @@ -117,7 +117,7 @@ use crate::util::errors::CargoResult; use crate::util::interning::InternedString; use crate::util::{internal, Graph}; use anyhow::{bail, Context as _}; -use log::debug; +use tracing::debug; use serde::de; use serde::ser; use serde::{Deserialize, Serialize}; diff --git a/src/cargo/core/resolver/features.rs b/src/cargo/core/resolver/features.rs index 3670e87112f7..4518f9fe7cf0 100644 --- a/src/cargo/core/resolver/features.rs +++ b/src/cargo/core/resolver/features.rs @@ -470,7 +470,7 @@ impl<'a, 'cfg> FeatureResolver<'a, 'cfg> { deferred_weak_dependencies: HashMap::new(), }; r.do_resolve(specs, cli_features)?; - log::debug!("features={:#?}", r.activated_features); + tracing::debug!("features={:#?}", r.activated_features); if r.opts.compare { r.compare(); } @@ -518,7 +518,7 @@ impl<'a, 'cfg> FeatureResolver<'a, 'cfg> { fk: FeaturesFor, fvs: &[FeatureValue], ) -> CargoResult<()> { - log::trace!("activate_pkg {} {}", pkg_id.name(), fk); + tracing::trace!("activate_pkg {} {}", pkg_id.name(), fk); // Add an empty entry to ensure everything is covered. This is intended for // finding bugs where the resolver missed something it should have visited. // Remove this in the future if `activated_features` uses an empty default. @@ -566,7 +566,7 @@ impl<'a, 'cfg> FeatureResolver<'a, 'cfg> { fk: FeaturesFor, fv: &FeatureValue, ) -> CargoResult<()> { - log::trace!("activate_fv {} {} {}", pkg_id.name(), fk, fv); + tracing::trace!("activate_fv {} {} {}", pkg_id.name(), fk, fv); match fv { FeatureValue::Feature(f) => { self.activate_rec(pkg_id, fk, *f)?; @@ -593,7 +593,7 @@ impl<'a, 'cfg> FeatureResolver<'a, 'cfg> { fk: FeaturesFor, feature_to_enable: InternedString, ) -> CargoResult<()> { - log::trace!( + tracing::trace!( "activate_rec {} {} feat={}", pkg_id.name(), fk, @@ -615,7 +615,7 @@ impl<'a, 'cfg> FeatureResolver<'a, 'cfg> { // TODO: this should only happen for optional dependencies. // Other cases should be validated by Summary's `build_feature_map`. // Figure out some way to validate this assumption. - log::debug!( + tracing::debug!( "pkg {:?} does not define feature {}", pkg_id, feature_to_enable @@ -654,7 +654,7 @@ impl<'a, 'cfg> FeatureResolver<'a, 'cfg> { } if let Some(to_enable) = &to_enable { for dep_feature in to_enable { - log::trace!( + tracing::trace!( "activate deferred {} {} -> {}/{}", pkg_id.name(), fk, @@ -697,7 +697,7 @@ impl<'a, 'cfg> FeatureResolver<'a, 'cfg> { { // This is weak, but not yet activated. Defer in case // something comes along later and enables it. - log::trace!( + tracing::trace!( "deferring feature {} {} -> {}/{}", pkg_id.name(), fk, diff --git a/src/cargo/core/resolver/mod.rs b/src/cargo/core/resolver/mod.rs index b9c29fb872b6..e3da6fe5ad22 100644 --- a/src/cargo/core/resolver/mod.rs +++ b/src/cargo/core/resolver/mod.rs @@ -63,7 +63,7 @@ use std::mem; use std::rc::Rc; use std::time::{Duration, Instant}; -use log::{debug, trace}; +use tracing::{debug, trace}; use crate::core::PackageIdSpec; use crate::core::{Dependency, PackageId, Registry, Summary}; diff --git a/src/cargo/core/source/source_id.rs b/src/cargo/core/source/source_id.rs index 43c141b7a247..28889a19887d 100644 --- a/src/cargo/core/source/source_id.rs +++ b/src/cargo/core/source/source_id.rs @@ -3,7 +3,7 @@ use crate::sources::registry::CRATES_IO_HTTP_INDEX; use crate::sources::{DirectorySource, CRATES_IO_DOMAIN, CRATES_IO_INDEX, CRATES_IO_REGISTRY}; use crate::sources::{GitSource, PathSource, RegistrySource}; use crate::util::{config, CanonicalUrl, CargoResult, Config, IntoUrl}; -use log::trace; +use tracing::trace; use serde::de; use serde::ser; use std::cmp::{self, Ordering}; diff --git a/src/cargo/core/workspace.rs b/src/cargo/core/workspace.rs index db9c18010734..9ee0cbe04304 100644 --- a/src/cargo/core/workspace.rs +++ b/src/cargo/core/workspace.rs @@ -7,7 +7,7 @@ use std::rc::Rc; use anyhow::{anyhow, bail, Context as _}; use glob::glob; use itertools::Itertools; -use log::debug; +use tracing::debug; use url::Url; use crate::core::compiler::Unit; diff --git a/src/cargo/lib.rs b/src/cargo/lib.rs index a03d51199787..9f6edf80d2a5 100644 --- a/src/cargo/lib.rs +++ b/src/cargo/lib.rs @@ -147,7 +147,7 @@ use crate::core::shell::Verbosity::Verbose; use crate::core::Shell; use anyhow::Error; -use log::debug; +use tracing::debug; pub use crate::util::errors::{AlreadyPrintedError, InternalError, VerboseError}; pub use crate::util::{indented_lines, CargoResult, CliError, CliResult, Config}; diff --git a/src/cargo/ops/cargo_compile/mod.rs b/src/cargo/ops/cargo_compile/mod.rs index f53a9e934262..9287fdf4fc58 100644 --- a/src/cargo/ops/cargo_compile/mod.rs +++ b/src/cargo/ops/cargo_compile/mod.rs @@ -753,7 +753,7 @@ fn remove_duplicate_doc( .into_iter() .partition(|unit| cb(unit) && !root_units.contains(unit)); for unit in to_remove { - log::debug!( + tracing::debug!( "removing duplicate doc due to {} for package {} target `{}`", reason, unit.pkg, diff --git a/src/cargo/ops/cargo_generate_lockfile.rs b/src/cargo/ops/cargo_generate_lockfile.rs index 6267b08f5882..cfee791f695d 100644 --- a/src/cargo/ops/cargo_generate_lockfile.rs +++ b/src/cargo/ops/cargo_generate_lockfile.rs @@ -6,7 +6,7 @@ use crate::ops; use crate::util::config::Config; use crate::util::CargoResult; use anyhow::Context; -use log::debug; +use tracing::debug; use std::collections::{BTreeMap, HashSet}; use termcolor::Color::{self, Cyan, Green, Red, Yellow}; diff --git a/src/cargo/ops/cargo_new.rs b/src/cargo/ops/cargo_new.rs index b113671b078e..0809cefc373a 100644 --- a/src/cargo/ops/cargo_new.rs +++ b/src/cargo/ops/cargo_new.rs @@ -879,7 +879,7 @@ mod tests { .arg(&path_of_source_file) .exec_with_output() { - log::warn!("failed to call rustfmt: {:#}", e); + tracing::warn!("failed to call rustfmt: {:#}", e); } } } diff --git a/src/cargo/ops/cargo_package.rs b/src/cargo/ops/cargo_package.rs index e904dba83f04..133cff7834d6 100644 --- a/src/cargo/ops/cargo_package.rs +++ b/src/cargo/ops/cargo_package.rs @@ -22,7 +22,7 @@ use anyhow::Context as _; use cargo_util::paths; use flate2::read::GzDecoder; use flate2::{Compression, GzBuilder}; -use log::debug; +use tracing::debug; use serde::Serialize; use tar::{Archive, Builder, EntryType, Header, HeaderMode}; use unicase::Ascii as UncasedAscii; diff --git a/src/cargo/ops/cargo_read_manifest.rs b/src/cargo/ops/cargo_read_manifest.rs index 2dfe900860fd..d9daea5da2ce 100644 --- a/src/cargo/ops/cargo_read_manifest.rs +++ b/src/cargo/ops/cargo_read_manifest.rs @@ -9,7 +9,7 @@ use crate::util::important_paths::find_project_manifest_exact; use crate::util::toml::read_manifest; use crate::util::Config; use cargo_util::paths; -use log::{info, trace}; +use tracing::{info, trace}; pub fn read_package( path: &Path, diff --git a/src/cargo/ops/fix.rs b/src/cargo/ops/fix.rs index be24967f8b91..9f5c767dd237 100644 --- a/src/cargo/ops/fix.rs +++ b/src/cargo/ops/fix.rs @@ -46,7 +46,7 @@ use std::{env, fs, str}; use anyhow::{bail, Context as _}; use cargo_util::{exit_status_to_string, is_simple_exit_code, paths, ProcessBuilder}; -use log::{debug, trace, warn}; +use tracing::{debug, trace, warn}; use rustfix::diagnostics::Diagnostic; use rustfix::{self, CodeFix}; use semver::Version; diff --git a/src/cargo/ops/resolve.rs b/src/cargo/ops/resolve.rs index ea5eded4aa2c..b7d293a9d038 100644 --- a/src/cargo/ops/resolve.rs +++ b/src/cargo/ops/resolve.rs @@ -71,7 +71,7 @@ use crate::sources::PathSource; use crate::util::errors::CargoResult; use crate::util::{profile, CanonicalUrl}; use anyhow::Context as _; -use log::{debug, trace}; +use tracing::{debug, trace}; use std::collections::{HashMap, HashSet}; /// Result for `resolve_ws_with_opts`. diff --git a/src/cargo/ops/tree/graph.rs b/src/cargo/ops/tree/graph.rs index d01d07f1a1a3..f0dad4e5d3f2 100644 --- a/src/cargo/ops/tree/graph.rs +++ b/src/cargo/ops/tree/graph.rs @@ -642,7 +642,7 @@ fn add_feature_rec( let dep_indexes = match graph.dep_name_map[&package_index].get(dep_name) { Some(indexes) => indexes.clone(), None => { - log::debug!( + tracing::debug!( "enabling feature {} on {}, found {}/{}, \ dep appears to not be enabled", feature_name, diff --git a/src/cargo/sources/config.rs b/src/cargo/sources/config.rs index 4097567bbf61..e39bd6954e81 100644 --- a/src/cargo/sources/config.rs +++ b/src/cargo/sources/config.rs @@ -10,7 +10,7 @@ use crate::util::config::{self, ConfigRelativePath, OptValue}; use crate::util::errors::CargoResult; use crate::util::{Config, IntoUrl}; use anyhow::{bail, Context as _}; -use log::debug; +use tracing::debug; use std::collections::{HashMap, HashSet}; use url::Url; diff --git a/src/cargo/sources/git/known_hosts.rs b/src/cargo/sources/git/known_hosts.rs index 41b965693a66..0b0dd3208aa6 100644 --- a/src/cargo/sources/git/known_hosts.rs +++ b/src/cargo/sources/git/known_hosts.rs @@ -342,7 +342,7 @@ fn check_ssh_known_hosts( }; match parse_known_hosts_line(&line_value.val, location) { Some(known_host) => known_hosts.push(known_host), - None => log::warn!( + None => tracing::warn!( "failed to parse known host {} from {}", line_value.val, line_value.definition diff --git a/src/cargo/sources/git/oxide.rs b/src/cargo/sources/git/oxide.rs index e86c63e8ee96..b0d66b42aa23 100644 --- a/src/cargo/sources/git/oxide.rs +++ b/src/cargo/sources/git/oxide.rs @@ -6,7 +6,7 @@ use crate::util::{human_readable_bytes, network, MetricsCounter, Progress}; use crate::{CargoResult, Config}; use cargo_util::paths; use gix::bstr::{BString, ByteSlice}; -use log::debug; +use tracing::debug; use std::cell::RefCell; use std::path::Path; use std::sync::atomic::{AtomicBool, Ordering}; diff --git a/src/cargo/sources/git/source.rs b/src/cargo/sources/git/source.rs index 7cba21693623..3a8603862cef 100644 --- a/src/cargo/sources/git/source.rs +++ b/src/cargo/sources/git/source.rs @@ -10,7 +10,7 @@ use crate::util::hex::short_hash; use crate::util::Config; use anyhow::Context; use cargo_util::paths::exclude_from_backups_and_indexing; -use log::trace; +use tracing::trace; use std::fmt::{self, Debug, Formatter}; use std::task::Poll; use url::Url; diff --git a/src/cargo/sources/git/utils.rs b/src/cargo/sources/git/utils.rs index 0c7ce8b64367..8d320994da4b 100644 --- a/src/cargo/sources/git/utils.rs +++ b/src/cargo/sources/git/utils.rs @@ -11,7 +11,7 @@ use anyhow::{anyhow, Context as _}; use cargo_util::{paths, ProcessBuilder}; use curl::easy::List; use git2::{self, ErrorClass, ObjectType, Oid}; -use log::{debug, info}; +use tracing::{debug, info}; use serde::ser; use serde::Serialize; use std::borrow::Cow; @@ -1316,7 +1316,7 @@ fn clean_repo_temp_files(repo: &git2::Repository) { let pattern = match path.to_str() { Some(p) => p, None => { - log::warn!("cannot convert {path:?} to a string"); + tracing::warn!("cannot convert {path:?} to a string"); return; } }; @@ -1327,8 +1327,8 @@ fn clean_repo_temp_files(repo: &git2::Repository) { for path in paths { if let Ok(path) = path { match paths::remove_file(&path) { - Ok(_) => log::debug!("removed stale temp git file {path:?}"), - Err(e) => log::warn!("failed to remove {path:?} while cleaning temp files: {e}"), + Ok(_) => tracing::debug!("removed stale temp git file {path:?}"), + Err(e) => tracing::warn!("failed to remove {path:?} while cleaning temp files: {e}"), } } } diff --git a/src/cargo/sources/path.rs b/src/cargo/sources/path.rs index bb40ec9b11b6..1d8ffc35c8b7 100644 --- a/src/cargo/sources/path.rs +++ b/src/cargo/sources/path.rs @@ -11,7 +11,7 @@ use anyhow::Context as _; use cargo_util::paths; use filetime::FileTime; use ignore::gitignore::GitignoreBuilder; -use log::{trace, warn}; +use tracing::{trace, warn}; use walkdir::WalkDir; /// A source represents one or multiple packages gathering from a given root @@ -203,7 +203,7 @@ impl<'cfg> PathSource<'cfg> { let repo = match git2::Repository::discover(root) { Ok(repo) => repo, Err(e) => { - log::debug!( + tracing::debug!( "could not discover git repo at or above {}: {}", root.display(), e @@ -223,7 +223,7 @@ impl<'cfg> PathSource<'cfg> { let repo_relative_path = match paths::strip_prefix_canonical(root, repo_root) { Ok(p) => p, Err(e) => { - log::warn!( + tracing::warn!( "cannot determine if path `{:?}` is in git repo `{:?}`: {:?}", root, repo_root, diff --git a/src/cargo/sources/registry/http_remote.rs b/src/cargo/sources/registry/http_remote.rs index 05920eab11e8..d7a96ccd6fe8 100644 --- a/src/cargo/sources/registry/http_remote.rs +++ b/src/cargo/sources/registry/http_remote.rs @@ -14,7 +14,7 @@ use cargo_credential::Operation; use cargo_util::paths; use curl::easy::{Easy, List}; use curl::multi::{EasyHandle, Multi}; -use log::{debug, trace}; +use tracing::{debug, trace}; use std::cell::RefCell; use std::collections::{HashMap, HashSet}; use std::fs::{self, File}; @@ -394,11 +394,11 @@ impl<'cfg> HttpRegistry<'cfg> { Ok(json) => { self.registry_config = Some(json); } - Err(e) => log::debug!("failed to decode cached config.json: {}", e), + Err(e) => tracing::debug!("failed to decode cached config.json: {}", e), }, Err(e) => { if e.kind() != ErrorKind::NotFound { - log::debug!("failed to read config.json cache: {}", e) + tracing::debug!("failed to read config.json cache: {}", e) } } } @@ -423,7 +423,7 @@ impl<'cfg> HttpRegistry<'cfg> { self.registry_config = Some(serde_json::from_slice(&raw_data)?); if paths::create_dir_all(&config_json_path.parent().unwrap()).is_ok() { if let Err(e) = fs::write(&config_json_path, &raw_data) { - log::debug!("failed to write config.json cache: {}", e); + tracing::debug!("failed to write config.json cache: {}", e); } } Poll::Ready(Ok(self.registry_config.as_ref().unwrap())) diff --git a/src/cargo/sources/registry/index.rs b/src/cargo/sources/registry/index.rs index 6d565da8f5b2..cb63ddf8093e 100644 --- a/src/cargo/sources/registry/index.rs +++ b/src/cargo/sources/registry/index.rs @@ -94,7 +94,7 @@ use crate::util::IntoUrl; use crate::util::{internal, CargoResult, Config, Filesystem, OptVersionReq, ToSemver}; use anyhow::bail; use cargo_util::{paths, registry::make_dep_path}; -use log::{debug, info}; +use tracing::{debug, info}; use semver::Version; use serde::Deserialize; use std::borrow::Cow; @@ -673,23 +673,23 @@ impl Summaries { index_version = Some(v); } Err(e) => { - log::debug!("failed to parse {:?} cache: {}", relative, e); + tracing::debug!("failed to parse {:?} cache: {}", relative, e); } }, - Err(e) => log::debug!("cache missing for {:?} error: {}", relative, e), + Err(e) => tracing::debug!("cache missing for {:?} error: {}", relative, e), } let response = ready!(load.load(root, relative, index_version.as_deref())?); match response { LoadResponse::CacheValid => { - log::debug!("fast path for registry cache of {:?}", relative); + tracing::debug!("fast path for registry cache of {:?}", relative); return Poll::Ready(Ok(cached_summaries)); } LoadResponse::NotFound => { if let Err(e) = fs::remove_file(cache_path) { if e.kind() != ErrorKind::NotFound { - log::debug!("failed to remove from cache: {}", e); + tracing::debug!("failed to remove from cache: {}", e); } } return Poll::Ready(Ok(None)); @@ -701,7 +701,7 @@ impl Summaries { // This is the fallback path where we actually talk to the registry backend to load // information. Here we parse every single line in the index (as we need // to find the versions) - log::debug!("slow path for {:?}", relative); + tracing::debug!("slow path for {:?}", relative); let mut cache = SummariesCache::default(); let mut ret = Summaries::default(); ret.raw_data = raw_data; @@ -722,7 +722,7 @@ impl Summaries { // entries in the cache preventing those newer // versions from reading them (that is, until the // cache is rebuilt). - log::info!("failed to parse {:?} registry package: {}", relative, e); + tracing::info!("failed to parse {:?} registry package: {}", relative, e); continue; } }; @@ -731,7 +731,7 @@ impl Summaries { ret.versions.insert(version, summary.into()); } if let Some(index_version) = index_version { - log::trace!("caching index_version {}", index_version); + tracing::trace!("caching index_version {}", index_version); let cache_bytes = cache.serialize(index_version.as_str()); // Once we have our `cache_bytes` which represents the `Summaries` we're // about to return, write that back out to disk so future Cargo @@ -743,7 +743,7 @@ impl Summaries { let path = Filesystem::new(cache_path.clone()); config.assert_package_cache_locked(&path); if let Err(e) = fs::write(cache_path, &cache_bytes) { - log::info!("failed to write cache: {}", e); + tracing::info!("failed to write cache: {}", e); } } @@ -906,7 +906,7 @@ impl IndexSummary { v, } = serde_json::from_slice(line)?; let v = v.unwrap_or(1); - log::trace!("json parsed registry {}/{}", name, vers); + tracing::trace!("json parsed registry {}/{}", name, vers); let pkgid = PackageId::new(name, &vers, source_id)?; let deps = deps .into_iter() diff --git a/src/cargo/sources/registry/mod.rs b/src/cargo/sources/registry/mod.rs index a0178db55e8c..dd7fa16ec7dd 100644 --- a/src/cargo/sources/registry/mod.rs +++ b/src/cargo/sources/registry/mod.rs @@ -195,7 +195,7 @@ use std::task::{ready, Poll}; use anyhow::Context as _; use cargo_util::paths::{self, exclude_from_backups_and_indexing}; use flate2::read::GzDecoder; -use log::debug; +use tracing::debug; use serde::Deserialize; use serde::Serialize; use tar::Archive; @@ -589,9 +589,9 @@ impl<'cfg> RegistrySource<'cfg> { } _ => { if ok == "ok" { - log::debug!("old `ok` content found, clearing cache"); + tracing::debug!("old `ok` content found, clearing cache"); } else { - log::warn!("unrecognized .cargo-ok content, clearing cache: {ok}"); + tracing::warn!("unrecognized .cargo-ok content, clearing cache: {ok}"); } // See comment of `unpack_package` about why removing all stuff. paths::remove_dir_all(dst.as_path_unlocked())?; diff --git a/src/cargo/sources/registry/remote.rs b/src/cargo/sources/registry/remote.rs index 4223b0303867..153c9c07b67d 100644 --- a/src/cargo/sources/registry/remote.rs +++ b/src/cargo/sources/registry/remote.rs @@ -12,7 +12,7 @@ use crate::util::{Config, Filesystem}; use anyhow::Context as _; use cargo_util::paths; use lazycell::LazyCell; -use log::{debug, trace}; +use tracing::{debug, trace}; use std::cell::{Cell, Ref, RefCell}; use std::fs::File; use std::mem; diff --git a/src/cargo/util/auth/mod.rs b/src/cargo/util/auth/mod.rs index 8a85fceb3ab4..e1e672994a16 100644 --- a/src/cargo/util/auth/mod.rs +++ b/src/cargo/util/auth/mod.rs @@ -220,7 +220,7 @@ fn registry_credential_config_raw_uncached( config: &Config, sid: &SourceId, ) -> CargoResult> { - log::trace!("loading credential config for {}", sid); + tracing::trace!("loading credential config for {}", sid); config.load_credentials()?; if !sid.is_remote_registry() { bail!( @@ -307,10 +307,10 @@ fn registry_credential_config_raw_uncached( } if let Some(name) = &name { - log::debug!("found alternative registry name `{name}` for {sid}"); + tracing::debug!("found alternative registry name `{name}` for {sid}"); config.get::>(&format!("registries.{name}")) } else { - log::debug!("no registry name found for {sid}"); + tracing::debug!("no registry name found for {sid}"); Ok(None) } } @@ -320,7 +320,7 @@ fn resolve_credential_alias(config: &Config, mut provider: PathAndArgs) -> Vec(&key) { - log::debug!("resolving credential alias '{key}' -> '{alias:?}'"); + tracing::debug!("resolving credential alias '{key}' -> '{alias:?}'"); provider = alias; } } @@ -444,7 +444,7 @@ fn credential_action( for provider in providers { let args: Vec<&str> = provider.iter().map(String::as_str).collect(); let process = args[0]; - log::debug!("attempting credential provider: {args:?}"); + tracing::debug!("attempting credential provider: {args:?}"); let provider: Box = match process { "cargo:token" => Box::new(TokenCredential::new(config)), "cargo:paseto" => Box::new(PasetoCredential::new(config)), @@ -510,7 +510,7 @@ fn auth_token_optional( operation: Operation<'_>, headers: Vec, ) -> CargoResult>> { - log::trace!("token requested for {}", sid.display_registry_name()); + tracing::trace!("token requested for {}", sid.display_registry_name()); let mut cache = config.credential_cache(); let url = sid.canonical_url(); if let Some(cached_token) = cache.get(url) { @@ -520,7 +520,7 @@ fn auth_token_optional( .unwrap_or(true) { if cached_token.operation_independent || matches!(operation, Operation::Read) { - log::trace!("using token from in-memory cache"); + tracing::trace!("using token from in-memory cache"); return Ok(Some(cached_token.token_value.clone())); } } else { @@ -548,7 +548,7 @@ fn auth_token_optional( bail!("credential provider produced unexpected response for `get` request: {credential_response:?}") }; let token = Secret::from(token); - log::trace!("found token"); + tracing::trace!("found token"); let expiration = match cache_control { CacheControl::Expires(expiration) => Some(expiration), CacheControl::Session => None, diff --git a/src/cargo/util/config/mod.rs b/src/cargo/util/config/mod.rs index 024137dd79a9..cf977d38d135 100644 --- a/src/cargo/util/config/mod.rs +++ b/src/cargo/util/config/mod.rs @@ -611,7 +611,7 @@ impl Config { key: &ConfigKey, vals: &HashMap, ) -> CargoResult> { - log::trace!("get cv {:?}", key); + tracing::trace!("get cv {:?}", key); if key.is_root() { // Returning the entire root table (for example `cargo config get` // with no key). The definition here shouldn't matter. @@ -2798,7 +2798,7 @@ fn disables_multiplexing_for_bad_curl( .iter() .any(|v| curl_version.starts_with(v)) { - log::info!("disabling multiplexing with proxy, curl version is {curl_version}"); + tracing::info!("disabling multiplexing with proxy, curl version is {curl_version}"); http.multiplexing = Some(false); } } diff --git a/src/cargo/util/config/target.rs b/src/cargo/util/config/target.rs index cdafe73dd679..b8aaf906d6fc 100644 --- a/src/cargo/util/config/target.rs +++ b/src/cargo/util/config/target.rs @@ -45,7 +45,7 @@ pub(super) fn load_target_cfgs(config: &Config) -> CargoResult = config.get("target")?; - log::debug!("Got all targets {:#?}", target); + tracing::debug!("Got all targets {:#?}", target); for (key, cfg) in target { if key.starts_with("cfg(") { // Unfortunately this is not able to display the location of the diff --git a/src/cargo/util/credential/process.rs b/src/cargo/util/credential/process.rs index 07551aee303b..89eac1af6c43 100644 --- a/src/cargo/util/credential/process.rs +++ b/src/cargo/util/credential/process.rs @@ -35,7 +35,7 @@ impl<'a> Credential for CredentialProcessCredential { cmd.stdout(Stdio::piped()); cmd.stdin(Stdio::piped()); cmd.arg("--cargo-plugin"); - log::debug!("credential-process: {cmd:?}"); + tracing::debug!("credential-process: {cmd:?}"); let mut child = cmd.spawn().context("failed to spawn credential process")?; let mut output_from_child = BufReader::new(child.stdout.take().unwrap()); let mut input_to_child = child.stdin.take().unwrap(); @@ -45,7 +45,7 @@ impl<'a> Credential for CredentialProcessCredential { .context("failed to read hello from credential provider")?; let credential_hello: CredentialHello = serde_json::from_str(&buffer).context("failed to deserialize hello")?; - log::debug!("credential-process > {credential_hello:?}"); + tracing::debug!("credential-process > {credential_hello:?}"); let req = CredentialRequest { v: cargo_credential::PROTOCOL_VERSION_1, @@ -54,7 +54,7 @@ impl<'a> Credential for CredentialProcessCredential { args: args.to_vec(), }; let request = serde_json::to_string(&req).context("failed to serialize request")?; - log::debug!("credential-process < {req:?}"); + tracing::debug!("credential-process < {req:?}"); writeln!(input_to_child, "{request}").context("failed to write to credential provider")?; buffer.clear(); @@ -63,7 +63,7 @@ impl<'a> Credential for CredentialProcessCredential { .context("failed to read response from credential provider")?; let response: Result = serde_json::from_str(&buffer).context("failed to deserialize response")?; - log::debug!("credential-process > {response:?}"); + tracing::debug!("credential-process > {response:?}"); drop(input_to_child); let status = child.wait().context("credential process never started")?; if !status.success() { @@ -74,7 +74,7 @@ impl<'a> Credential for CredentialProcessCredential { ) .into()); } - log::trace!("credential process exited successfully"); + tracing::trace!("credential process exited successfully"); response } } diff --git a/src/cargo/util/diagnostic_server.rs b/src/cargo/util/diagnostic_server.rs index 36215735be27..71e8e302c118 100644 --- a/src/cargo/util/diagnostic_server.rs +++ b/src/cargo/util/diagnostic_server.rs @@ -11,7 +11,7 @@ use std::thread::{self, JoinHandle}; use anyhow::{Context, Error}; use cargo_util::ProcessBuilder; -use log::warn; +use tracing::warn; use serde::{Deserialize, Serialize}; use crate::core::Edition; diff --git a/src/cargo/util/job.rs b/src/cargo/util/job.rs index f2bcf94a26b1..1d68fc4338d6 100644 --- a/src/cargo/util/job.rs +++ b/src/cargo/util/job.rs @@ -49,7 +49,7 @@ mod imp { use std::ptr; use std::ptr::addr_of; - use log::info; + use tracing::info; use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::Foundation::HANDLE; diff --git a/src/cargo/util/network/mod.rs b/src/cargo/util/network/mod.rs index b078fa3527d2..5db594945151 100644 --- a/src/cargo/util/network/mod.rs +++ b/src/cargo/util/network/mod.rs @@ -29,7 +29,7 @@ macro_rules! try_old_curl { let result = $e; if cfg!(target_os = "macos") { if let Err(e) = result { - ::log::warn!("ignoring libcurl {} error: {}", $msg, e); + ::tracing::warn!("ignoring libcurl {} error: {}", $msg, e); } } else { use ::anyhow::Context; diff --git a/src/cargo/util/network/sleep.rs b/src/cargo/util/network/sleep.rs index d4105065e29e..fab53263b7d7 100644 --- a/src/cargo/util/network/sleep.rs +++ b/src/cargo/util/network/sleep.rs @@ -68,7 +68,7 @@ impl SleepTracker { let now = Instant::now(); let mut result = Vec::new(); while let Some(next) = self.heap.peek() { - log::debug!("ERIC: now={now:?} next={:?}", next.wakeup); + tracing::debug!("ERIC: now={now:?} next={:?}", next.wakeup); if next.wakeup < now { result.push(self.heap.pop().unwrap().data); } else { diff --git a/src/cargo/util/rustc.rs b/src/cargo/util/rustc.rs index 3f1da64d4312..f5ccf3d9e911 100644 --- a/src/cargo/util/rustc.rs +++ b/src/cargo/util/rustc.rs @@ -6,7 +6,7 @@ use std::sync::Mutex; use anyhow::Context as _; use cargo_util::{paths, ProcessBuilder, ProcessError}; -use log::{debug, info, warn}; +use tracing::{debug, info, warn}; use serde::{Deserialize, Serialize}; use crate::util::interning::InternedString; diff --git a/src/cargo/util/toml/embedded.rs b/src/cargo/util/toml/embedded.rs index cd0c7c6ee3a8..395430c1b58d 100644 --- a/src/cargo/util/toml/embedded.rs +++ b/src/cargo/util/toml/embedded.rs @@ -18,7 +18,7 @@ pub fn expand_manifest( let comment = match extract_comment(content) { Ok(comment) => Some(comment), Err(err) => { - log::trace!("failed to extract doc comment: {err}"); + tracing::trace!("failed to extract doc comment: {err}"); None } } @@ -26,7 +26,7 @@ pub fn expand_manifest( let manifest = match extract_manifest(&comment)? { Some(manifest) => Some(manifest), None => { - log::trace!("failed to extract manifest"); + tracing::trace!("failed to extract manifest"); None } } diff --git a/src/cargo/util/toml/mod.rs b/src/cargo/util/toml/mod.rs index 284c5dd35d15..1d08f37a8f9d 100644 --- a/src/cargo/util/toml/mod.rs +++ b/src/cargo/util/toml/mod.rs @@ -11,7 +11,7 @@ use cargo_platform::Platform; use cargo_util::paths; use itertools::Itertools; use lazycell::LazyCell; -use log::{debug, trace}; +use tracing::{debug, trace}; use semver::{self, VersionReq}; use serde::de::IntoDeserializer as _; use serde::de::{self, Unexpected}; From e84cc17db6ac48620e2723f51bce0703f5590060 Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Sun, 6 Aug 2023 20:30:51 +0100 Subject: [PATCH 10/17] refactor: rustfmt for tracing --- src/cargo/core/compiler/fingerprint/mod.rs | 2 +- src/cargo/core/compiler/job_queue/mod.rs | 2 +- src/cargo/core/dependency.rs | 2 +- src/cargo/core/package.rs | 2 +- src/cargo/core/resolver/context.rs | 2 +- src/cargo/core/resolver/dep_cache.rs | 2 +- src/cargo/core/resolver/encode.rs | 2 +- src/cargo/core/source/source_id.rs | 2 +- src/cargo/ops/cargo_generate_lockfile.rs | 2 +- src/cargo/ops/cargo_package.rs | 2 +- src/cargo/ops/fix.rs | 2 +- src/cargo/ops/resolve.rs | 2 +- src/cargo/sources/config.rs | 2 +- src/cargo/sources/git/oxide.rs | 2 +- src/cargo/sources/git/source.rs | 2 +- src/cargo/sources/git/utils.rs | 6 ++++-- src/cargo/sources/registry/http_remote.rs | 2 +- src/cargo/sources/registry/index.rs | 8 ++++++-- src/cargo/sources/registry/mod.rs | 2 +- src/cargo/sources/registry/remote.rs | 2 +- src/cargo/util/diagnostic_server.rs | 2 +- src/cargo/util/rustc.rs | 2 +- src/cargo/util/toml/mod.rs | 2 +- 23 files changed, 31 insertions(+), 25 deletions(-) diff --git a/src/cargo/core/compiler/fingerprint/mod.rs b/src/cargo/core/compiler/fingerprint/mod.rs index 54fbcc9a4ae5..2e6fb7eed073 100644 --- a/src/cargo/core/compiler/fingerprint/mod.rs +++ b/src/cargo/core/compiler/fingerprint/mod.rs @@ -366,10 +366,10 @@ use std::time::SystemTime; use anyhow::{bail, format_err, Context as _}; use cargo_util::{paths, ProcessBuilder}; use filetime::FileTime; -use tracing::{debug, info}; use serde::de; use serde::ser; use serde::{Deserialize, Serialize}; +use tracing::{debug, info}; use crate::core::compiler::unit_graph::UnitDep; use crate::core::Package; diff --git a/src/cargo/core/compiler/job_queue/mod.rs b/src/cargo/core/compiler/job_queue/mod.rs index 96bf1543f1ea..26fcd4826929 100644 --- a/src/cargo/core/compiler/job_queue/mod.rs +++ b/src/cargo/core/compiler/job_queue/mod.rs @@ -125,8 +125,8 @@ use std::time::Duration; use anyhow::{format_err, Context as _}; use cargo_util::ProcessBuilder; use jobserver::{Acquired, HelperThread}; -use tracing::{debug, trace}; use semver::Version; +use tracing::{debug, trace}; pub use self::job::Freshness::{self, Dirty, Fresh}; pub use self::job::{Job, Work}; diff --git a/src/cargo/core/dependency.rs b/src/cargo/core/dependency.rs index 6340ce414244..c8fee6262ec8 100644 --- a/src/cargo/core/dependency.rs +++ b/src/cargo/core/dependency.rs @@ -1,5 +1,4 @@ use cargo_platform::Platform; -use tracing::trace; use semver::VersionReq; use serde::ser; use serde::Serialize; @@ -7,6 +6,7 @@ use std::borrow::Cow; use std::fmt; use std::path::PathBuf; use std::rc::Rc; +use tracing::trace; use crate::core::compiler::{CompileKind, CompileTarget}; use crate::core::{PackageId, SourceId, Summary}; diff --git a/src/cargo/core/package.rs b/src/cargo/core/package.rs index 8f80f6a45cfb..c84941462b46 100644 --- a/src/cargo/core/package.rs +++ b/src/cargo/core/package.rs @@ -13,9 +13,9 @@ use bytesize::ByteSize; use curl::easy::Easy; use curl::multi::{EasyHandle, Multi}; use lazycell::LazyCell; -use tracing::debug; use semver::Version; use serde::Serialize; +use tracing::debug; use crate::core::compiler::{CompileKind, RustcTargetData}; use crate::core::dependency::DepKind; diff --git a/src/cargo/core/resolver/context.rs b/src/cargo/core/resolver/context.rs index 5f444a157ff4..f19c678a6953 100644 --- a/src/cargo/core/resolver/context.rs +++ b/src/cargo/core/resolver/context.rs @@ -6,9 +6,9 @@ use crate::core::{Dependency, PackageId, SourceId, Summary}; use crate::util::interning::InternedString; use crate::util::Graph; use anyhow::format_err; -use tracing::debug; use std::collections::HashMap; use std::num::NonZeroU64; +use tracing::debug; pub use super::encode::Metadata; pub use super::encode::{EncodableDependency, EncodablePackageId, EncodableResolve}; diff --git a/src/cargo/core/resolver/dep_cache.rs b/src/cargo/core/resolver/dep_cache.rs index 77101d4a439b..9975330147b5 100644 --- a/src/cargo/core/resolver/dep_cache.rs +++ b/src/cargo/core/resolver/dep_cache.rs @@ -23,10 +23,10 @@ use crate::util::errors::CargoResult; use crate::util::interning::InternedString; use anyhow::Context as _; -use tracing::debug; use std::collections::{BTreeSet, HashMap, HashSet}; use std::rc::Rc; use std::task::Poll; +use tracing::debug; pub struct RegistryQueryer<'a> { pub registry: &'a mut (dyn Registry + 'a), diff --git a/src/cargo/core/resolver/encode.rs b/src/cargo/core/resolver/encode.rs index 7b023cd8907e..1ee0d23f40a1 100644 --- a/src/cargo/core/resolver/encode.rs +++ b/src/cargo/core/resolver/encode.rs @@ -117,13 +117,13 @@ use crate::util::errors::CargoResult; use crate::util::interning::InternedString; use crate::util::{internal, Graph}; use anyhow::{bail, Context as _}; -use tracing::debug; use serde::de; use serde::ser; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, HashMap, HashSet}; use std::fmt; use std::str::FromStr; +use tracing::debug; /// The `Cargo.lock` structure. #[derive(Serialize, Deserialize, Debug)] diff --git a/src/cargo/core/source/source_id.rs b/src/cargo/core/source/source_id.rs index 28889a19887d..6bbc07a5df3f 100644 --- a/src/cargo/core/source/source_id.rs +++ b/src/cargo/core/source/source_id.rs @@ -3,7 +3,6 @@ use crate::sources::registry::CRATES_IO_HTTP_INDEX; use crate::sources::{DirectorySource, CRATES_IO_DOMAIN, CRATES_IO_INDEX, CRATES_IO_REGISTRY}; use crate::sources::{GitSource, PathSource, RegistrySource}; use crate::util::{config, CanonicalUrl, CargoResult, Config, IntoUrl}; -use tracing::trace; use serde::de; use serde::ser; use std::cmp::{self, Ordering}; @@ -14,6 +13,7 @@ use std::path::{Path, PathBuf}; use std::ptr; use std::sync::Mutex; use std::sync::OnceLock; +use tracing::trace; use url::Url; static SOURCE_ID_CACHE: OnceLock>> = OnceLock::new(); diff --git a/src/cargo/ops/cargo_generate_lockfile.rs b/src/cargo/ops/cargo_generate_lockfile.rs index cfee791f695d..fddf83f1998a 100644 --- a/src/cargo/ops/cargo_generate_lockfile.rs +++ b/src/cargo/ops/cargo_generate_lockfile.rs @@ -6,9 +6,9 @@ use crate::ops; use crate::util::config::Config; use crate::util::CargoResult; use anyhow::Context; -use tracing::debug; use std::collections::{BTreeMap, HashSet}; use termcolor::Color::{self, Cyan, Green, Red, Yellow}; +use tracing::debug; pub struct UpdateOptions<'a> { pub config: &'a Config, diff --git a/src/cargo/ops/cargo_package.rs b/src/cargo/ops/cargo_package.rs index 133cff7834d6..93469607bc8f 100644 --- a/src/cargo/ops/cargo_package.rs +++ b/src/cargo/ops/cargo_package.rs @@ -22,9 +22,9 @@ use anyhow::Context as _; use cargo_util::paths; use flate2::read::GzDecoder; use flate2::{Compression, GzBuilder}; -use tracing::debug; use serde::Serialize; use tar::{Archive, Builder, EntryType, Header, HeaderMode}; +use tracing::debug; use unicase::Ascii as UncasedAscii; pub struct PackageOpts<'cfg> { diff --git a/src/cargo/ops/fix.rs b/src/cargo/ops/fix.rs index 9f5c767dd237..0e678d61c6be 100644 --- a/src/cargo/ops/fix.rs +++ b/src/cargo/ops/fix.rs @@ -46,10 +46,10 @@ use std::{env, fs, str}; use anyhow::{bail, Context as _}; use cargo_util::{exit_status_to_string, is_simple_exit_code, paths, ProcessBuilder}; -use tracing::{debug, trace, warn}; use rustfix::diagnostics::Diagnostic; use rustfix::{self, CodeFix}; use semver::Version; +use tracing::{debug, trace, warn}; use crate::core::compiler::RustcTargetData; use crate::core::resolver::features::{DiffMap, FeatureOpts, FeatureResolver, FeaturesFor}; diff --git a/src/cargo/ops/resolve.rs b/src/cargo/ops/resolve.rs index b7d293a9d038..6246311a5c5b 100644 --- a/src/cargo/ops/resolve.rs +++ b/src/cargo/ops/resolve.rs @@ -71,8 +71,8 @@ use crate::sources::PathSource; use crate::util::errors::CargoResult; use crate::util::{profile, CanonicalUrl}; use anyhow::Context as _; -use tracing::{debug, trace}; use std::collections::{HashMap, HashSet}; +use tracing::{debug, trace}; /// Result for `resolve_ws_with_opts`. pub struct WorkspaceResolve<'cfg> { diff --git a/src/cargo/sources/config.rs b/src/cargo/sources/config.rs index e39bd6954e81..c51c1f009689 100644 --- a/src/cargo/sources/config.rs +++ b/src/cargo/sources/config.rs @@ -10,8 +10,8 @@ use crate::util::config::{self, ConfigRelativePath, OptValue}; use crate::util::errors::CargoResult; use crate::util::{Config, IntoUrl}; use anyhow::{bail, Context as _}; -use tracing::debug; use std::collections::{HashMap, HashSet}; +use tracing::debug; use url::Url; /// Represents the entire [`[source]` replacement table][1] in Cargo configuration. diff --git a/src/cargo/sources/git/oxide.rs b/src/cargo/sources/git/oxide.rs index b0d66b42aa23..ec4fcecdd67c 100644 --- a/src/cargo/sources/git/oxide.rs +++ b/src/cargo/sources/git/oxide.rs @@ -6,12 +6,12 @@ use crate::util::{human_readable_bytes, network, MetricsCounter, Progress}; use crate::{CargoResult, Config}; use cargo_util::paths; use gix::bstr::{BString, ByteSlice}; -use tracing::debug; use std::cell::RefCell; use std::path::Path; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Weak}; use std::time::{Duration, Instant}; +use tracing::debug; /// For the time being, `repo_path` makes it easy to instantiate a gitoxide repo just for fetching. /// In future this may change to be the gitoxide repository itself. diff --git a/src/cargo/sources/git/source.rs b/src/cargo/sources/git/source.rs index 3a8603862cef..10796562df00 100644 --- a/src/cargo/sources/git/source.rs +++ b/src/cargo/sources/git/source.rs @@ -10,9 +10,9 @@ use crate::util::hex::short_hash; use crate::util::Config; use anyhow::Context; use cargo_util::paths::exclude_from_backups_and_indexing; -use tracing::trace; use std::fmt::{self, Debug, Formatter}; use std::task::Poll; +use tracing::trace; use url::Url; /// `GitSource` contains one or more packages gathering from a Git repository. diff --git a/src/cargo/sources/git/utils.rs b/src/cargo/sources/git/utils.rs index 8d320994da4b..09363109184d 100644 --- a/src/cargo/sources/git/utils.rs +++ b/src/cargo/sources/git/utils.rs @@ -11,7 +11,6 @@ use anyhow::{anyhow, Context as _}; use cargo_util::{paths, ProcessBuilder}; use curl::easy::List; use git2::{self, ErrorClass, ObjectType, Oid}; -use tracing::{debug, info}; use serde::ser; use serde::Serialize; use std::borrow::Cow; @@ -21,6 +20,7 @@ use std::process::Command; use std::str; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; +use tracing::{debug, info}; use url::Url; /// A file indicates that if present, `git reset` has been done and a repo @@ -1328,7 +1328,9 @@ fn clean_repo_temp_files(repo: &git2::Repository) { if let Ok(path) = path { match paths::remove_file(&path) { Ok(_) => tracing::debug!("removed stale temp git file {path:?}"), - Err(e) => tracing::warn!("failed to remove {path:?} while cleaning temp files: {e}"), + Err(e) => { + tracing::warn!("failed to remove {path:?} while cleaning temp files: {e}") + } } } } diff --git a/src/cargo/sources/registry/http_remote.rs b/src/cargo/sources/registry/http_remote.rs index d7a96ccd6fe8..52f6f392e9d9 100644 --- a/src/cargo/sources/registry/http_remote.rs +++ b/src/cargo/sources/registry/http_remote.rs @@ -14,7 +14,6 @@ use cargo_credential::Operation; use cargo_util::paths; use curl::easy::{Easy, List}; use curl::multi::{EasyHandle, Multi}; -use tracing::{debug, trace}; use std::cell::RefCell; use std::collections::{HashMap, HashSet}; use std::fs::{self, File}; @@ -23,6 +22,7 @@ use std::path::{Path, PathBuf}; use std::str; use std::task::{ready, Poll}; use std::time::Duration; +use tracing::{debug, trace}; use url::Url; // HTTP headers diff --git a/src/cargo/sources/registry/index.rs b/src/cargo/sources/registry/index.rs index cb63ddf8093e..d82a0d24742b 100644 --- a/src/cargo/sources/registry/index.rs +++ b/src/cargo/sources/registry/index.rs @@ -94,7 +94,6 @@ use crate::util::IntoUrl; use crate::util::{internal, CargoResult, Config, Filesystem, OptVersionReq, ToSemver}; use anyhow::bail; use cargo_util::{paths, registry::make_dep_path}; -use tracing::{debug, info}; use semver::Version; use serde::Deserialize; use std::borrow::Cow; @@ -105,6 +104,7 @@ use std::io::ErrorKind; use std::path::Path; use std::str; use std::task::{ready, Poll}; +use tracing::{debug, info}; /// The current version of [`SummariesCache`]. const CURRENT_CACHE_VERSION: u8 = 3; @@ -722,7 +722,11 @@ impl Summaries { // entries in the cache preventing those newer // versions from reading them (that is, until the // cache is rebuilt). - tracing::info!("failed to parse {:?} registry package: {}", relative, e); + tracing::info!( + "failed to parse {:?} registry package: {}", + relative, + e + ); continue; } }; diff --git a/src/cargo/sources/registry/mod.rs b/src/cargo/sources/registry/mod.rs index dd7fa16ec7dd..b53e88d58a85 100644 --- a/src/cargo/sources/registry/mod.rs +++ b/src/cargo/sources/registry/mod.rs @@ -195,10 +195,10 @@ use std::task::{ready, Poll}; use anyhow::Context as _; use cargo_util::paths::{self, exclude_from_backups_and_indexing}; use flate2::read::GzDecoder; -use tracing::debug; use serde::Deserialize; use serde::Serialize; use tar::Archive; +use tracing::debug; use crate::core::dependency::Dependency; use crate::core::source::MaybePackage; diff --git a/src/cargo/sources/registry/remote.rs b/src/cargo/sources/registry/remote.rs index 153c9c07b67d..89927181f643 100644 --- a/src/cargo/sources/registry/remote.rs +++ b/src/cargo/sources/registry/remote.rs @@ -12,13 +12,13 @@ use crate::util::{Config, Filesystem}; use anyhow::Context as _; use cargo_util::paths; use lazycell::LazyCell; -use tracing::{debug, trace}; use std::cell::{Cell, Ref, RefCell}; use std::fs::File; use std::mem; use std::path::Path; use std::str; use std::task::{ready, Poll}; +use tracing::{debug, trace}; /// A remote registry is a registry that lives at a remote URL (such as /// crates.io). The git index is cloned locally, and `.crate` files are diff --git a/src/cargo/util/diagnostic_server.rs b/src/cargo/util/diagnostic_server.rs index 71e8e302c118..f8eeabfc29dc 100644 --- a/src/cargo/util/diagnostic_server.rs +++ b/src/cargo/util/diagnostic_server.rs @@ -11,8 +11,8 @@ use std::thread::{self, JoinHandle}; use anyhow::{Context, Error}; use cargo_util::ProcessBuilder; -use tracing::warn; use serde::{Deserialize, Serialize}; +use tracing::warn; use crate::core::Edition; use crate::util::errors::CargoResult; diff --git a/src/cargo/util/rustc.rs b/src/cargo/util/rustc.rs index f5ccf3d9e911..238145af6810 100644 --- a/src/cargo/util/rustc.rs +++ b/src/cargo/util/rustc.rs @@ -6,8 +6,8 @@ use std::sync::Mutex; use anyhow::Context as _; use cargo_util::{paths, ProcessBuilder, ProcessError}; -use tracing::{debug, info, warn}; use serde::{Deserialize, Serialize}; +use tracing::{debug, info, warn}; use crate::util::interning::InternedString; use crate::util::{profile, CargoResult, Config, StableHasher}; diff --git a/src/cargo/util/toml/mod.rs b/src/cargo/util/toml/mod.rs index 1d08f37a8f9d..963c4afaa925 100644 --- a/src/cargo/util/toml/mod.rs +++ b/src/cargo/util/toml/mod.rs @@ -11,12 +11,12 @@ use cargo_platform::Platform; use cargo_util::paths; use itertools::Itertools; use lazycell::LazyCell; -use tracing::{debug, trace}; use semver::{self, VersionReq}; use serde::de::IntoDeserializer as _; use serde::de::{self, Unexpected}; use serde::ser; use serde::{Deserialize, Serialize}; +use tracing::{debug, trace}; use url::Url; use crate::core::compiler::{CompileKind, CompileTarget}; From de39bdd30a744f6b05718963a55eced4c67686a9 Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Sat, 5 Aug 2023 09:20:28 +0100 Subject: [PATCH 11/17] refactor: replace `log` with `tracing` in network debugging --- src/cargo/util/network/http.rs | 37 ++++++++++++++++++++-------------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/src/cargo/util/network/http.rs b/src/cargo/util/network/http.rs index f077ce2b6409..e5e429611f78 100644 --- a/src/cargo/util/network/http.rs +++ b/src/cargo/util/network/http.rs @@ -8,8 +8,8 @@ use curl::easy::Easy; use curl::easy::InfoType; use curl::easy::SslOpt; use curl::easy::SslVersion; -use log::log; -use log::Level; +use tracing::debug; +use tracing::trace; use crate::util::config::SslVersionConfig; use crate::util::config::SslVersionConfigRange; @@ -135,14 +135,19 @@ pub fn configure_http_handle(config: &Config, handle: &mut Easy) -> CargoResult< if let Some(true) = http.debug { handle.verbose(true)?; - log::debug!("{:#?}", curl::Version::get()); + tracing::debug!("{:#?}", curl::Version::get()); handle.debug_function(|kind, data| { + enum LogLevel { + Debug, + Trace, + } + use LogLevel::*; let (prefix, level) = match kind { - InfoType::Text => ("*", Level::Debug), - InfoType::HeaderIn => ("<", Level::Debug), - InfoType::HeaderOut => (">", Level::Debug), - InfoType::DataIn => ("{", Level::Trace), - InfoType::DataOut => ("}", Level::Trace), + InfoType::Text => ("*", Debug), + InfoType::HeaderIn => ("<", Debug), + InfoType::HeaderOut => (">", Debug), + InfoType::DataIn => ("{", Trace), + InfoType::DataOut => ("}", Trace), InfoType::SslDataIn | InfoType::SslDataOut => return, _ => return, }; @@ -159,16 +164,18 @@ pub fn configure_http_handle(config: &Config, handle: &mut Easy) -> CargoResult< } else if starts_with_ignore_case(line, "set-cookie") { line = "set-cookie: [REDACTED]"; } - log!(level, "http-debug: {} {}", prefix, line); + match level { + Debug => debug!("http-debug: {prefix} {line}"), + Trace => trace!("http-debug: {prefix} {line}"), + } } } Err(_) => { - log!( - level, - "http-debug: {} ({} bytes of data)", - prefix, - data.len() - ); + let len = data.len(); + match level { + Debug => debug!("http-debug: {prefix} ({len} bytes of data)"), + Trace => trace!("http-debug: {prefix} ({len} bytes of data)"), + } } } })?; From 23561f36a1c0d494620e869e25274ea30042767c Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Sat, 5 Aug 2023 09:51:03 +0100 Subject: [PATCH 12/17] chore: add `tracing-subscriber` crate --- Cargo.lock | 75 ++++++++++++++++++++++++++++++ Cargo.toml | 2 + crates/xtask-bump-check/Cargo.toml | 1 + 3 files changed, 78 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 972c9749940a..9306d44de830 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -325,6 +325,7 @@ dependencies = [ "toml", "toml_edit", "tracing", + "tracing-subscriber", "unicase", "unicode-width", "unicode-xid", @@ -2049,6 +2050,15 @@ version = "0.4.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b06a4cde4c0f271a446782e3eff8de789548ce57dbc8eca9292c27f4a42004b4" +[[package]] +name = "matchers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558" +dependencies = [ + "regex-automata", +] + [[package]] name = "maybe-async" version = "0.2.7" @@ -2146,6 +2156,16 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "nu-ansi-term" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84" +dependencies = [ + "overload", + "winapi", +] + [[package]] name = "num-traits" version = "0.2.15" @@ -2283,6 +2303,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "overload" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" + [[package]] name = "p384" version = "0.13.0" @@ -2683,6 +2709,9 @@ name = "regex-automata" version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" +dependencies = [ + "regex-syntax 0.6.29", +] [[package]] name = "regex-syntax" @@ -2944,6 +2973,15 @@ dependencies = [ "digest", ] +[[package]] +name = "sharded-slab" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900fba806f70c630b0a382d0d825e17a0f19fcd059a2ade1ff237bcddf446b31" +dependencies = [ + "lazy_static", +] + [[package]] name = "shell-escape" version = "0.1.5" @@ -3299,6 +3337,36 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0955b8137a1df6f1a2e9a37d8a6656291ff0297c1a97c24e0d8425fe2312f79a" dependencies = [ "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78ddad33d2d10b1ed7eb9d1f518a5674713876e97e5bb9b7345a7984fbb4f922" +dependencies = [ + "lazy_static", + "log", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30a651bc37f915e81f087d86e62a18eec5f79550c7faff886f7090b4ea757c77" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", ] [[package]] @@ -3384,6 +3452,12 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" +[[package]] +name = "valuable" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" + [[package]] name = "varisat" version = "0.2.2" @@ -3724,6 +3798,7 @@ dependencies = [ "git2", "log", "tracing", + "tracing-subscriber", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index d2ee3275ac76..b0b66e34fb08 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -95,6 +95,7 @@ time = { version = "0.3", features = ["parsing", "formatting", "serde"] } toml = "0.7.6" toml_edit = "0.19.14" tracing = "0.1.37" +tracing-subscriber = { version = "0.3.17", features = ["env-filter"] } unicase = "2.6.0" unicode-width = "0.1.10" unicode-xid = "0.2.4" @@ -180,6 +181,7 @@ time.workspace = true toml.workspace = true toml_edit.workspace = true tracing.workspace = true +tracing-subscriber.workspace = true unicase.workspace = true unicode-width.workspace = true unicode-xid.workspace = true diff --git a/crates/xtask-bump-check/Cargo.toml b/crates/xtask-bump-check/Cargo.toml index 13e100e286bb..4da854aabfa9 100644 --- a/crates/xtask-bump-check/Cargo.toml +++ b/crates/xtask-bump-check/Cargo.toml @@ -13,3 +13,4 @@ env_logger.workspace = true git2.workspace = true log.workspace = true tracing.workspace = true +tracing-subscriber.workspace = true From 7e69050c6447b5ad3d5e3e93896b5586603aaf5c Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Sun, 6 Aug 2023 20:31:33 +0100 Subject: [PATCH 13/17] refactor: setup `tracing-subscriber` --- crates/xtask-bump-check/src/main.rs | 12 ++++++++++++ src/bin/cargo/main.rs | 11 +++++++++++ 2 files changed, 23 insertions(+) diff --git a/crates/xtask-bump-check/src/main.rs b/crates/xtask-bump-check/src/main.rs index 1942a3621cfb..a0b6cfe8bb46 100644 --- a/crates/xtask-bump-check/src/main.rs +++ b/crates/xtask-bump-check/src/main.rs @@ -2,6 +2,8 @@ mod xtask; fn main() { env_logger::init_from_env("CARGO_LOG"); + setup_logger(); + let cli = xtask::cli(); let matches = cli.get_matches(); @@ -13,3 +15,13 @@ fn main() { cargo::exit_with_error(e, &mut config.shell()) } } + +// In sync with `src/bin/cargo/main.rs@setup_logger`. +fn setup_logger() { + let env = tracing_subscriber::EnvFilter::from_env("CARGO_LOG"); + + tracing_subscriber::fmt() + .with_writer(std::io::stderr) + .with_env_filter(env) + .init(); +} diff --git a/src/bin/cargo/main.rs b/src/bin/cargo/main.rs index 462332fb7ed1..ec110d361623 100644 --- a/src/bin/cargo/main.rs +++ b/src/bin/cargo/main.rs @@ -25,6 +25,8 @@ fn main() { #[cfg(not(feature = "pretty-env-logger"))] env_logger::init_from_env("CARGO_LOG"); + setup_logger(); + let mut config = cli::LazyConfig::new(); let result = if let Some(lock_addr) = cargo::ops::fix_get_proxy_lock_addr() { @@ -40,6 +42,15 @@ fn main() { } } +fn setup_logger() { + let env = tracing_subscriber::EnvFilter::from_env("CARGO_LOG"); + + tracing_subscriber::fmt() + .with_writer(std::io::stderr) + .with_env_filter(env) + .init(); +} + /// Table for defining the aliases which come builtin in `Cargo`. /// The contents are structured as: `(alias, aliased_command, description)`. const BUILTIN_ALIASES: [(&str, &str, &str); 6] = [ From 9d707e4b9a5ca4aa4494c0950765a80494d42264 Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Sat, 5 Aug 2023 09:26:41 +0100 Subject: [PATCH 14/17] chore: remove `log`, `env_logger`, and `pretty_env_logger` --- Cargo.lock | 29 ----------------------------- Cargo.toml | 7 ------- crates/cargo-util/Cargo.toml | 1 - crates/xtask-bump-check/Cargo.toml | 2 -- crates/xtask-bump-check/src/main.rs | 1 - src/bin/cargo/main.rs | 5 ----- 6 files changed, 45 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9306d44de830..b0c1047a5a74 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -274,7 +274,6 @@ dependencies = [ "crates-io", "curl", "curl-sys", - "env_logger", "filetime", "flate2", "fwdansi", @@ -296,14 +295,12 @@ dependencies = [ "lazycell", "libc", "libgit2-sys", - "log", "memchr", "opener", "openssl", "os_info", "pasetors", "pathdiff", - "pretty_env_logger", "pulldown-cmark", "rand", "rustfix", @@ -434,7 +431,6 @@ dependencies = [ "hex", "jobserver", "libc", - "log", "miow", "same-file", "sha2", @@ -830,19 +826,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "env_logger" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85cdab6a89accf66733ad5a1693a4dcced6aeff64602b634530dd73c1f3ee9f0" -dependencies = [ - "humantime", - "is-terminal", - "log", - "regex", - "termcolor", -] - [[package]] name = "equivalent" version = "1.0.1" @@ -2516,16 +2499,6 @@ dependencies = [ "yansi", ] -[[package]] -name = "pretty_env_logger" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "865724d4dbe39d9f3dd3b52b88d859d66bcb2d6a0acfd5ea68a65fb66d4bdc1c" -dependencies = [ - "env_logger", - "log", -] - [[package]] name = "primeorder" version = "0.13.2" @@ -3794,9 +3767,7 @@ dependencies = [ "cargo", "cargo-util", "clap", - "env_logger", "git2", - "log", "tracing", "tracing-subscriber", ] diff --git a/Cargo.toml b/Cargo.toml index b0b66e34fb08..96fbaea309e0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,7 +34,6 @@ crates-io = { version = "0.38.0", path = "crates/crates-io" } criterion = { version = "0.5.1", features = ["html_reports"] } curl = "0.4.44" curl-sys = "0.4.65" -env_logger = "0.10.0" filetime = "0.2.21" flate2 = { version = "1.0.26", default-features = false, features = ["zlib"] } fwdansi = "1.1.0" @@ -58,7 +57,6 @@ lazy_static = "1.4.0" lazycell = "1.3.0" libc = "0.2.147" libgit2-sys = "0.15.2" -log = "0.4.19" memchr = "2.5.0" miow = "0.6.0" opener = "0.6.1" @@ -69,7 +67,6 @@ pathdiff = "0.2" percent-encoding = "2.3" pkg-config = "0.3.27" pretty_assertions = "1.4.0" -pretty_env_logger = "0.5.0" proptest = "1.2.0" pulldown-cmark = { version = "0.9.3", default-features = false } rand = "0.8.5" @@ -134,7 +131,6 @@ clap = { workspace = true, features = ["wrap_help"] } crates-io.workspace = true curl = { workspace = true, features = ["http2"] } curl-sys.workspace = true -env_logger.workspace = true filetime.workspace = true flate2.workspace = true git2.workspace = true @@ -155,13 +151,11 @@ jobserver.workspace = true lazycell.workspace = true libc.workspace = true libgit2-sys.workspace = true -log.workspace = true memchr.workspace = true opener.workspace = true os_info.workspace = true pasetors.workspace = true pathdiff.workspace = true -pretty_env_logger = { workspace = true, optional = true } pulldown-cmark.workspace = true rand.workspace = true rustfix.workspace = true @@ -222,6 +216,5 @@ doc = false [features] vendored-openssl = ["openssl/vendored"] vendored-libgit2 = ["libgit2-sys/vendored"] -pretty-env-logger = ["pretty_env_logger"] # This is primarily used by rust-lang/rust distributing cargo the executable. all-static = ['vendored-openssl', 'curl/static-curl', 'curl/force-system-lib-on-osx'] diff --git a/crates/cargo-util/Cargo.toml b/crates/cargo-util/Cargo.toml index 4f5a50b1bf34..36ca7bc1771f 100644 --- a/crates/cargo-util/Cargo.toml +++ b/crates/cargo-util/Cargo.toml @@ -14,7 +14,6 @@ filetime.workspace = true hex.workspace = true jobserver.workspace = true libc.workspace = true -log.workspace = true same-file.workspace = true shell-escape.workspace = true tempfile.workspace = true diff --git a/crates/xtask-bump-check/Cargo.toml b/crates/xtask-bump-check/Cargo.toml index 4da854aabfa9..e965ad09e654 100644 --- a/crates/xtask-bump-check/Cargo.toml +++ b/crates/xtask-bump-check/Cargo.toml @@ -9,8 +9,6 @@ anyhow.workspace = true cargo.workspace = true cargo-util.workspace = true clap.workspace = true -env_logger.workspace = true git2.workspace = true -log.workspace = true tracing.workspace = true tracing-subscriber.workspace = true diff --git a/crates/xtask-bump-check/src/main.rs b/crates/xtask-bump-check/src/main.rs index a0b6cfe8bb46..6f9e2e94cb2c 100644 --- a/crates/xtask-bump-check/src/main.rs +++ b/crates/xtask-bump-check/src/main.rs @@ -1,7 +1,6 @@ mod xtask; fn main() { - env_logger::init_from_env("CARGO_LOG"); setup_logger(); let cli = xtask::cli(); diff --git a/src/bin/cargo/main.rs b/src/bin/cargo/main.rs index ec110d361623..e9c717b9d4e5 100644 --- a/src/bin/cargo/main.rs +++ b/src/bin/cargo/main.rs @@ -20,11 +20,6 @@ mod commands; use crate::command_prelude::*; fn main() { - #[cfg(feature = "pretty-env-logger")] - pretty_env_logger::init_custom_env("CARGO_LOG"); - #[cfg(not(feature = "pretty-env-logger"))] - env_logger::init_from_env("CARGO_LOG"); - setup_logger(); let mut config = cli::LazyConfig::new(); From 964c083ea1a862f47f20228f64918da6ce8f30cd Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Sun, 6 Aug 2023 21:02:47 +0100 Subject: [PATCH 15/17] doc(logging): update mentions of `log` to `tracing` --- src/doc/contrib/src/implementation/debugging.md | 15 ++++++++------- src/doc/src/reference/environment-variables.md | 4 ++-- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/doc/contrib/src/implementation/debugging.md b/src/doc/contrib/src/implementation/debugging.md index e148d72c36b6..03940e2ffe1a 100644 --- a/src/doc/contrib/src/implementation/debugging.md +++ b/src/doc/contrib/src/implementation/debugging.md @@ -2,11 +2,11 @@ ## Logging -Cargo uses the [`env_logger`] crate to display debug log messages. The -`CARGO_LOG` environment variable can be set to enable debug logging, with a -value such as `trace`, `debug`, or `warn`. It also supports filtering for -specific modules. Feel free to use the standard [`log`] macros to help with -diagnosing problems. +Cargo uses the [`tracing`] crate to display debug log messages. +The `CARGO_LOG` environment variable can be set to enable debug logging, with a value such as `trace`, `debug`, or `warn`. +It also supports filtering for specific modules with comma-separated [directives]. +Feel free to use [shorthand macros] to help with diagnosing problems. +We're looking forward to making Cargo logging mechanism more structural! ```sh # Outputs all logs with levels debug and higher @@ -22,5 +22,6 @@ CARGO_HTTP_DEBUG=true CARGO_LOG=cargo::ops::registry=debug cargo fetch CARGO_LOG=cargo::core::compiler::fingerprint=trace cargo build ``` -[`env_logger`]: https://docs.rs/env_logger -[`log`]: https://docs.rs/log +[`tracing`]: https://docs.rs/tracing +[directive]: https://docs.rs/tracing_subscriber/filter/struct.EnvFilter.html#directives +[shorthand macros]: https://docs.rs/tracing/index.html#shorthand-macros diff --git a/src/doc/src/reference/environment-variables.md b/src/doc/src/reference/environment-variables.md index ab0562cc1fe8..25881d1388de 100644 --- a/src/doc/src/reference/environment-variables.md +++ b/src/doc/src/reference/environment-variables.md @@ -9,7 +9,7 @@ with them: You can override these environment variables to change Cargo's behavior on your system: -* `CARGO_LOG` --- Cargo uses the [`env_logger`] crate to display debug log messages. +* `CARGO_LOG` --- Cargo uses the [`tracing`] crate to display debug log messages. The `CARGO_LOG` environment variable can be set to enable debug logging, with a value such as `trace`, `debug`, or `warn`. Usually it is only used during debugging. For more details refer to the @@ -389,7 +389,7 @@ let out_dir = env::var("OUT_DIR").unwrap(); the environment; scripts should use `CARGO_ENCODED_RUSTFLAGS` instead. * `CARGO_PKG_` --- The package information variables, with the same names and values as are [provided during crate building][variables set for crates]. -[`env_logger`]: https://docs.rs/env_logger +[`tracing`]: https://docs.rs/tracing [debug logging]: https://doc.crates.io/contrib/architecture/console.html#debug-logging [unix-like platforms]: ../../reference/conditional-compilation.html#unix-and-windows [windows-like platforms]: ../../reference/conditional-compilation.html#unix-and-windows From af95711ae57bdd12f4ed66e80b86b73594d6586e Mon Sep 17 00:00:00 2001 From: Arlo Siemsen Date: Wed, 2 Aug 2023 17:25:30 -0500 Subject: [PATCH 16/17] Add more docs and example for cargo-credential --- Cargo.lock | 14 +++ credential/cargo-credential/Cargo.toml | 3 + .../examples/file-provider.rs | 90 +++++++++++++++++++ credential/cargo-credential/src/lib.rs | 30 ++++++- credential/cargo-credential/tests/examples.rs | 28 ++++++ 5 files changed, 164 insertions(+), 1 deletion(-) create mode 100644 credential/cargo-credential/examples/file-provider.rs create mode 100644 credential/cargo-credential/tests/examples.rs diff --git a/Cargo.lock b/Cargo.lock index 0d997e2c2150..9642569fa11b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -339,6 +339,7 @@ dependencies = [ "anyhow", "serde", "serde_json", + "snapbox", "thiserror", "time", ] @@ -867,6 +868,18 @@ dependencies = [ "libc", ] +[[package]] +name = "escargot" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "768064bd3a0e2bedcba91dc87ace90beea91acc41b6a01a3ca8e9aa8827461bf" +dependencies = [ + "log", + "once_cell", + "serde", + "serde_json", +] + [[package]] name = "fastrand" version = "1.9.0" @@ -3003,6 +3016,7 @@ dependencies = [ "anstyle", "content_inspector", "dunce", + "escargot", "filetime", "normalize-line-endings", "similar", diff --git a/credential/cargo-credential/Cargo.toml b/credential/cargo-credential/Cargo.toml index 9ac9168ffe6e..b765d529e53c 100644 --- a/credential/cargo-credential/Cargo.toml +++ b/credential/cargo-credential/Cargo.toml @@ -12,3 +12,6 @@ serde = { workspace = true, features = ["derive"] } serde_json.workspace = true thiserror.workspace = true time.workspace = true + +[dev-dependencies] +snapbox = { workspace = true, features = ["examples"] } diff --git a/credential/cargo-credential/examples/file-provider.rs b/credential/cargo-credential/examples/file-provider.rs new file mode 100644 index 000000000000..d119585360da --- /dev/null +++ b/credential/cargo-credential/examples/file-provider.rs @@ -0,0 +1,90 @@ +//! Example credential provider that stores credentials in a JSON file. +//! This is not secure + +use cargo_credential::{ + Action, CacheControl, Credential, CredentialResponse, RegistryInfo, Secret, +}; +use std::{collections::HashMap, fs::File, io::ErrorKind}; +type Error = Box; + +struct FileCredential; + +impl Credential for FileCredential { + fn perform( + &self, + registry: &RegistryInfo, + action: &Action, + _args: &[&str], + ) -> Result { + if registry.index_url != "https://github.com/rust-lang/crates.io-index" { + // Restrict this provider to only work for crates.io. Cargo will skip it and attempt + // another provider for any other registry. + // + // If a provider supports any registry, then this check should be omitted. + return Err(cargo_credential::Error::UrlNotSupported); + } + + // `Error::Other` takes a boxed `std::error::Error` type that causes Cargo to show the error. + let mut creds = FileCredential::read().map_err(cargo_credential::Error::Other)?; + + match action { + Action::Get(_) => { + // Cargo requested a token, look it up. + if let Some(token) = creds.get(registry.index_url) { + Ok(CredentialResponse::Get { + token: token.clone(), + cache: CacheControl::Session, + operation_independent: true, + }) + } else { + // Credential providers should respond with `NotFound` when a credential can not be + // found, allowing Cargo to attempt another provider. + Err(cargo_credential::Error::NotFound) + } + } + Action::Login(login_options) => { + // The token for `cargo login` can come from the `login_options` parameter or i + // interactively reading from stdin. + // + // `cargo_credential::read_token` automatically handles this. + let token = cargo_credential::read_token(login_options, registry)?; + creds.insert(registry.index_url.to_string(), token); + + FileCredential::write(&creds).map_err(cargo_credential::Error::Other)?; + + // Credentials were successfully stored. + Ok(CredentialResponse::Login) + } + Action::Logout => { + if creds.remove(registry.index_url).is_none() { + // If the user attempts to log out from a registry that has no credentials + // stored, then NotFound is the appropriate error. + Err(cargo_credential::Error::NotFound) + } else { + // Credentials were successfully erased. + Ok(CredentialResponse::Logout) + } + } + // If a credential provider doesn't support a given operation, it should respond with `OperationNotSupported`. + _ => Err(cargo_credential::Error::OperationNotSupported), + } + } +} + +impl FileCredential { + fn read() -> Result>, Error> { + match File::open("cargo-credentials.json") { + Ok(f) => Ok(serde_json::from_reader(f)?), + Err(e) if e.kind() == ErrorKind::NotFound => Ok(HashMap::new()), + Err(e) => Err(e)?, + } + } + fn write(value: &HashMap>) -> Result<(), Error> { + let file = File::create("cargo-credentials.json")?; + Ok(serde_json::to_writer_pretty(file, value)?) + } +} + +fn main() { + cargo_credential::main(FileCredential); +} diff --git a/credential/cargo-credential/src/lib.rs b/credential/cargo-credential/src/lib.rs index bbd437617aa0..02564dd2a29f 100644 --- a/credential/cargo-credential/src/lib.rs +++ b/credential/cargo-credential/src/lib.rs @@ -1,4 +1,4 @@ -//! Helper library for writing Cargo credential processes. +//! Helper library for writing Cargo credential providers. //! //! A credential process should have a `struct` that implements the `Credential` trait. //! The `main` function should be called with an instance of that struct, such as: @@ -8,6 +8,34 @@ //! cargo_credential::main(MyCredential); //! } //! ``` +//! +//! While in the `perform` function, stdin and stdout will be re-attached to the +//! active console. This allows credential providers to be interactive if necessary. +//! +//! ## Error handling +//! ### [`Error::UrlNotSupported`] +//! A credential provider may only support some registry URLs. If this is the case +//! and an unsupported index URL is passed to the provider, it should respond with +//! [`Error::UrlNotSupported`]. Other credential providers may be attempted by Cargo. +//! +//! ### [`Error::NotFound`] +//! When attempting an [`Action::Get`] or [`Action::Logout`], if a credential can not +//! be found, the provider should respond with [`Error::NotFound`]. Other credential +//! providers may be attempted by Cargo. +//! +//! ### [`Error::OperationNotSupported`] +//! A credential provider might not support all operations. For example if the provider +//! only supports [`Action::Get`], [`Error::OperationNotSupported`] should be returned +//! for all other requests. +//! +//! ### [`Error::Other`] +//! All other errors go here. The error will be shown to the user in Cargo, including +//! the full error chain using [`std::error::Error::source`]. +//! +//! ## Example +//! ```rust,ignore +#![doc = include_str!("../examples/file-provider.rs")] +//! ``` use serde::{Deserialize, Serialize}; use std::{ diff --git a/credential/cargo-credential/tests/examples.rs b/credential/cargo-credential/tests/examples.rs new file mode 100644 index 000000000000..d31a50cb64e2 --- /dev/null +++ b/credential/cargo-credential/tests/examples.rs @@ -0,0 +1,28 @@ +use std::path::Path; + +use snapbox::cmd::Command; + +#[test] +fn file_provider() { + let bin = snapbox::cmd::compile_example("file-provider", []).unwrap(); + + let hello = r#"{"v":[1]}"#; + let login_request = r#"{"v": 1,"registry": {"index-url":"https://github.com/rust-lang/crates.io-index","name":"crates-io"},"kind": "login","token": "s3krit","args": []}"#; + let login_response = r#"{"Ok":{"kind":"login"}}"#; + + let get_request = r#"{"v": 1,"registry": {"index-url":"https://github.com/rust-lang/crates.io-index","name":"crates-io"},"kind": "get","operation": "read","args": []}"#; + let get_response = + r#"{"Ok":{"kind":"get","token":"s3krit","cache":"session","operation_independent":true}}"#; + + let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("cargo-credential-tests"); + std::fs::create_dir(&dir).unwrap(); + Command::new(bin) + .current_dir(&dir) + .stdin(format!("{login_request}\n{get_request}\n")) + .arg("--cargo-plugin") + .assert() + .stdout_eq(format!("{hello}\n{login_response}\n{get_response}\n")) + .stderr_eq("") + .success(); + std::fs::remove_dir_all(&dir).unwrap(); +} From 1e12538c96efe0a48c30e9b849915e904c6c407a Mon Sep 17 00:00:00 2001 From: Daniil Belov <70999565+BelovDV@users.noreply.github.com> Date: Fri, 4 Aug 2023 12:36:48 +0300 Subject: [PATCH 17/17] pass jobserver on target info acquiring --- src/cargo/core/compiler/build_context/target_info.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/cargo/core/compiler/build_context/target_info.rs b/src/cargo/core/compiler/build_context/target_info.rs index e6e41c5226fb..c0e8f395867d 100644 --- a/src/cargo/core/compiler/build_context/target_info.rs +++ b/src/cargo/core/compiler/build_context/target_info.rs @@ -185,6 +185,12 @@ impl TargetInfo { .args(&rustflags) .env_remove("RUSTC_LOG"); + // Removes `FD_CLOEXEC` set by `jobserver::Client` to pass jobserver + // as environment variables specify. + if let Some(client) = config.jobserver_from_env() { + process.inherit_jobserver(client); + } + if let CompileKind::Target(target) = kind { process.arg("--target").arg(target.rustc_target()); }