Skip to content

Commit

Permalink
Replace usage of lazy_static with once_cell
Browse files Browse the repository at this point in the history
  • Loading branch information
djc committed Nov 6, 2023
1 parent 70614e4 commit fa907bf
Show file tree
Hide file tree
Showing 11 changed files with 96 additions and 112 deletions.
3 changes: 1 addition & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 3 additions & 6 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ otel = [
]

# Exports code dependent on private interfaces for the integration test suite
test = ["dep:once_cell", "dep:walkdir"]
test = ["dep:walkdir"]

# Sorted by alphabetic order
[dependencies]
Expand All @@ -56,9 +56,8 @@ flate2 = "1"
fs_at.workspace = true
git-testament = "0.2"
home = "0.5.4"
lazy_static.workspace = true
libc = "0.2"
once_cell = { workspace = true, optional = true }
once_cell.workspace = true
opener = "0.6.0"
# Used by `curl` or `reqwest` backend although it isn't imported by rustup:
# this allows controlling the vendoring status without exposing the presence of
Expand Down Expand Up @@ -141,14 +140,13 @@ version = "0.48.0"

[dev-dependencies]
enum-map = "2.5.0"
once_cell.workspace = true
proptest.workspace = true
rustup-macros.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread", "macros"] }
trycmd = "0.14.13"

[build-dependencies]
lazy_static = "1"
once_cell.workspace = true
regex = "1"

[workspace]
Expand All @@ -159,7 +157,6 @@ anyhow = "1.0.69"
derivative = "2.2.0"
enum_dispatch = "0.3.11"
fs_at = "0.1.6"
lazy_static = "1"
once_cell = "1.18.0"
opentelemetry = { version = "0.20.0", features = ["rt-tokio"] }
opentelemetry-otlp = { version = "0.13.0" }
Expand Down
4 changes: 2 additions & 2 deletions download/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ license = "MIT OR Apache-2.0"
default = ["reqwest-backend", "reqwest-rustls-tls", "reqwest-default-tls"]

curl-backend = ["curl"]
reqwest-backend = ["reqwest", "env_proxy", "lazy_static"]
reqwest-backend = ["reqwest", "env_proxy"]
reqwest-default-tls = ["reqwest/default-tls"]
reqwest-rustls-tls = ["reqwest/rustls-tls-native-roots"]

[dependencies]
anyhow.workspace = true
curl = { version = "0.4.44", optional = true }
env_proxy = { version = "0.4.1", optional = true }
lazy_static = { workspace = true, optional = true }
once_cell.workspace = true
reqwest = { version = "0.11", default-features = false, features = ["blocking", "gzip", "socks"], optional = true }
thiserror.workspace = true
url.workspace = true
Expand Down
54 changes: 23 additions & 31 deletions download/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ pub mod reqwest_be {

use anyhow::{anyhow, Context, Result};
#[cfg(any(feature = "reqwest-rustls-tls", feature = "reqwest-default-tls"))]
use lazy_static::lazy_static;
use once_cell::sync::Lazy;
use reqwest::blocking::{Client, ClientBuilder, Response};
use reqwest::{header, Proxy};
use url::Url;
Expand Down Expand Up @@ -324,40 +324,32 @@ pub mod reqwest_be {
.proxy(Proxy::custom(env_proxy))
.timeout(Duration::from_secs(30))
}

#[cfg(feature = "reqwest-rustls-tls")]
lazy_static! {
static ref CLIENT_RUSTLS_TLS: Client = {
let catcher = || {
client_generic().use_rustls_tls()
.build()
};
static CLIENT_RUSTLS_TLS: Lazy<Client> = Lazy::new(|| {
let catcher = || client_generic().use_rustls_tls().build();

// woah, an unwrap?!
// It's OK. This is the same as what is happening in curl.
//
// The curl::Easy::new() internally assert!s that the initialized
// Easy is not null. Inside reqwest, the errors here would be from
// the TLS library returning a null pointer as well.
catcher().unwrap()
});

// woah, an unwrap?!
// It's OK. This is the same as what is happening in curl.
//
// The curl::Easy::new() internally assert!s that the initialized
// Easy is not null. Inside reqwest, the errors here would be from
// the TLS library returning a null pointer as well.
catcher().unwrap()
};
}
#[cfg(feature = "reqwest-default-tls")]
lazy_static! {
static ref CLIENT_DEFAULT_TLS: Client = {
let catcher = || {
client_generic()
.build()
};
static CLIENT_DEFAULT_TLS: Lazy<Client> = Lazy::new(|| {
let catcher = || client_generic().build();

// woah, an unwrap?!
// It's OK. This is the same as what is happening in curl.
//
// The curl::Easy::new() internally assert!s that the initialized
// Easy is not null. Inside reqwest, the errors here would be from
// the TLS library returning a null pointer as well.
catcher().unwrap()
};
}
// woah, an unwrap?!
// It's OK. This is the same as what is happening in curl.
//
// The curl::Easy::new() internally assert!s that the initialized
// Easy is not null. Inside reqwest, the errors here would be from
// the TLS library returning a null pointer as well.
catcher().unwrap()
});

fn env_proxy(url: &Url) -> Option<Url> {
env_proxy::for_url(url).to_url()
Expand Down
13 changes: 6 additions & 7 deletions src/cli/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use std::{cmp, env};

use anyhow::{anyhow, Context, Result};
use git_testament::{git_testament, render_testament};
use lazy_static::lazy_static;
use once_cell::sync::Lazy;

use super::self_update;
use crate::cli::download_tracker::DownloadTracker;
Expand Down Expand Up @@ -566,15 +566,14 @@ pub(crate) fn list_overrides(cfg: &Cfg) -> Result<utils::ExitCode> {
git_testament!(TESTAMENT);

pub(crate) fn version() -> &'static str {
lazy_static! {
// Because we trust our `stable` branch given the careful release
// process, we mark it trusted here so that our version numbers look
// right when built from CI before the tag is pushed
static ref RENDERED: String = render_testament!(TESTAMENT, "stable");
}
&RENDERED
}

// Because we trust our `stable` branch given the careful release
// process, we mark it trusted here so that our version numbers look
// right when built from CI before the tag is pushed
static RENDERED: Lazy<String> = Lazy::new(|| render_testament!(TESTAMENT, "stable"));

pub(crate) fn dump_testament() -> Result<utils::ExitCode> {
use git_testament::GitModification::*;
writeln!(
Expand Down
8 changes: 3 additions & 5 deletions src/cli/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
use std::io;
use std::path::PathBuf;

use lazy_static::lazy_static;
use once_cell::sync::Lazy;
use regex::Regex;
use strsim::damerau_levenshtein;
use thiserror::Error as ThisError;
Expand All @@ -24,10 +24,6 @@ pub enum CLIError {
fn maybe_suggest_toolchain(bad_name: &str) -> String {
let bad_name = &bad_name.to_ascii_lowercase();
static VALID_CHANNELS: &[&str] = &["stable", "beta", "nightly"];
lazy_static! {
static ref NUMBERED: Regex = Regex::new(r"^\d+\.\d+$").unwrap();
}

if NUMBERED.is_match(bad_name) {
return format!(". Toolchain numbers tend to have three parts, e.g. {bad_name}.0");
}
Expand All @@ -54,3 +50,5 @@ fn maybe_suggest_toolchain(bad_name: &str) -> String {
format!(". Did you mean '{}'?", scored[0].1)
}
}

static NUMBERED: Lazy<Regex> = Lazy::new(|| Regex::new(r"^\d+\.\d+$").unwrap());
6 changes: 2 additions & 4 deletions src/cli/self_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1139,12 +1139,10 @@ fn get_new_rustup_version(path: &Path) -> Option<String> {
}

fn parse_new_rustup_version(version: String) -> String {
use lazy_static::lazy_static;
use once_cell::sync::Lazy;
use regex::Regex;

lazy_static! {
static ref RE: Regex = Regex::new(r"\d+.\d+.\d+[0-9a-zA-Z-]*").unwrap();
}
static RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"\d+.\d+.\d+[0-9a-zA-Z-]*").unwrap());

let capture = RE.captures(&version);
let matched_version = match capture {
Expand Down
23 changes: 12 additions & 11 deletions src/dist/dist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::str::FromStr;

use anyhow::{anyhow, bail, Context, Result};
use chrono::NaiveDate;
use lazy_static::lazy_static;
use once_cell::sync::Lazy;
use regex::Regex;
use thiserror::Error as ThisError;

Expand Down Expand Up @@ -182,15 +182,17 @@ static TRIPLE_MIPS64_UNKNOWN_LINUX_GNUABI64: &str = "mips64el-unknown-linux-gnua
impl FromStr for ParsedToolchainDesc {
type Err = anyhow::Error;
fn from_str(desc: &str) -> Result<Self> {
lazy_static! {
static ref TOOLCHAIN_CHANNEL_PATTERN: String = format!(
static TOOLCHAIN_CHANNEL_PATTERN: Lazy<String> = Lazy::new(|| {
format!(
r"^({})(?:-(\d{{4}}-\d{{2}}-\d{{2}}))?(?:-(.+))?$",
TOOLCHAIN_CHANNELS.join("|")
);
// Note this regex gives you a guaranteed match of the channel (1)
// and an optional match of the date (2) and target (3)
static ref TOOLCHAIN_CHANNEL_RE: Regex = Regex::new(&TOOLCHAIN_CHANNEL_PATTERN).unwrap();
}
)
});

// Note this regex gives you a guaranteed match of the channel (1)
// and an optional match of the date (2) and target (3)
static TOOLCHAIN_CHANNEL_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(&TOOLCHAIN_CHANNEL_PATTERN).unwrap());

let d = TOOLCHAIN_CHANNEL_RE.captures(desc).map(|c| {
fn fn_map(s: &str) -> Option<String> {
Expand Down Expand Up @@ -603,9 +605,8 @@ impl ToolchainDesc {
/// date field is empty.
pub(crate) fn is_tracking(&self) -> bool {
let channels = ["nightly", "beta", "stable"];
lazy_static! {
static ref TRACKING_VERSION: Regex = Regex::new(r"^\d{1}\.\d{1,3}$").unwrap();
}
static TRACKING_VERSION: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^\d{1}\.\d{1,3}$").unwrap());
(channels.iter().any(|x| *x == self.channel) || TRACKING_VERSION.is_match(&self.channel))
&& self.date.is_none()
}
Expand Down
14 changes: 8 additions & 6 deletions src/dist/triple.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use lazy_static::lazy_static;
use once_cell::sync::Lazy;
use regex::Regex;

// These lists contain the targets known to rustup, and used to build
Expand Down Expand Up @@ -68,15 +68,17 @@ impl PartialTargetTriple {
// we can count on all triple components being
// delineated by it.
let name = format!("-{name}");
lazy_static! {
static ref PATTERN: String = format!(
static PATTERN: Lazy<String> = Lazy::new(|| {
format!(
r"^(?:-({}))?(?:-({}))?(?:-({}))?$",
LIST_ARCHS.join("|"),
LIST_OSES.join("|"),
LIST_ENVS.join("|")
);
static ref RE: Regex = Regex::new(&PATTERN).unwrap();
}
)
});

static RE: Lazy<Regex> = Lazy::new(|| Regex::new(&PATTERN).unwrap());

RE.captures(&name).map(|c| {
fn fn_map(s: &str) -> Option<String> {
if s.is_empty() {
Expand Down
65 changes: 32 additions & 33 deletions src/test/mock/clitools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ use std::{
};

use enum_map::{enum_map, Enum, EnumMap};
use lazy_static::lazy_static;
use once_cell::sync::Lazy;
use url::Url;

Expand Down Expand Up @@ -1501,39 +1500,39 @@ fn build_combined_installer(components: &[&MockInstallerBuilder]) -> MockInstall
/// and then we store some associated files next to it which indicate
/// the version/version hash information.
fn mock_bin(name: &str, version: &str, version_hash: &str) -> Vec<MockFile> {
lazy_static! {
static ref MOCK_BIN: Arc<Vec<u8>> = {
// Create a temp directory to hold the source and the output
let tempdir = tempfile::Builder::new().prefix("rustup").tempdir().unwrap();
let source_path = tempdir.path().join("in.rs");
let dest_path = tempdir.path().join(format!("out{EXE_SUFFIX}"));

// Write the source
let source = include_bytes!("mock_bin_src.rs");
fs::write(&source_path, &source[..]).unwrap();

// Create the executable
let status = Command::new("rustc")
.arg(&source_path)
.arg("-C").arg("panic=abort")
.arg("-O")
.arg("-o").arg(&dest_path)
.status()
.unwrap();
assert!(status.success());
assert!(dest_path.exists());

// Remove debug info from std/core which included in every programs,
// otherwise we just ignore the return result here
if cfg!(unix) {
drop(Command::new("strip").arg(&dest_path).status());
}
static MOCK_BIN: Lazy<Arc<Vec<u8>>> = Lazy::new(|| {
// Create a temp directory to hold the source and the output
let tempdir = tempfile::Builder::new().prefix("rustup").tempdir().unwrap();
let source_path = tempdir.path().join("in.rs");
let dest_path = tempdir.path().join(format!("out{EXE_SUFFIX}"));

// Write the source
let source = include_bytes!("mock_bin_src.rs");
fs::write(&source_path, &source[..]).unwrap();

// Create the executable
let status = Command::new("rustc")
.arg(&source_path)
.arg("-C")
.arg("panic=abort")
.arg("-O")
.arg("-o")
.arg(&dest_path)
.status()
.unwrap();
assert!(status.success());
assert!(dest_path.exists());

// Now load it into memory
let buf = fs::read(dest_path).unwrap();
Arc::new(buf)
};
}
// Remove debug info from std/core which included in every programs,
// otherwise we just ignore the return result here
if cfg!(unix) {
drop(Command::new("strip").arg(&dest_path).status());
}

// Now load it into memory
let buf = fs::read(dest_path).unwrap();
Arc::new(buf)
});

let name = format!("bin/{name}{EXE_SUFFIX}");
vec![
Expand Down
Loading

0 comments on commit fa907bf

Please sign in to comment.