Skip to content

fix: replace once_cell to make cargo clippy happy #1676

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion lychee-bin/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ license = "Apache-2.0 OR MIT"
repository = "https://github.com/lycheeverse/lychee"
readme = "../README.md"
version.workspace = true
rust-version = "1.83.0"

[dependencies]
# NOTE: We need to specify the version of lychee-lib here because crates.io
Expand All @@ -31,7 +32,6 @@ humantime = "2.2.0"
humantime-serde = "1.1.1"
indicatif = "0.17.11"
log = "0.4.27"
once_cell = "1.21.3"
openssl-sys = { version = "0.9.106", optional = true }
pad = "0.1.6"
regex = "1.11.1"
Expand Down
6 changes: 3 additions & 3 deletions lychee-bin/src/archive/wayback/mod.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use std::time::Duration;

use once_cell::sync::Lazy;
use serde::de::Error as SerdeError;
use serde::{Deserialize, Deserializer};
use std::sync::LazyLock;

use http::StatusCode;
use reqwest::{Client, Error, Url};
static WAYBACK_URL: Lazy<Url> =
Lazy::new(|| Url::parse("https://archive.org/wayback/available").unwrap());
static WAYBACK_URL: LazyLock<Url> =
LazyLock::new(|| Url::parse("https://archive.org/wayback/available").unwrap());

pub(crate) async fn get_wayback_link(url: &Url, timeout: Duration) -> Result<Option<Url>, Error> {
let mut archive_url: Url = WAYBACK_URL.clone();
Expand Down
2 changes: 1 addition & 1 deletion lychee-bin/src/commands/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ where
if let Some(pb) = &bar {
pb.inc_length(1);
pb.set_message(request.to_string());
};
}
send_req
.send(Ok(request))
.await
Expand Down
23 changes: 13 additions & 10 deletions lychee-bin/src/formatters/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,23 @@

use console::Style;
use log::Level;
use once_cell::sync::Lazy;
use std::sync::LazyLock;

pub(crate) static NORMAL: Lazy<Style> = Lazy::new(Style::new);
pub(crate) static DIM: Lazy<Style> = Lazy::new(|| Style::new().dim());
pub(crate) static NORMAL: LazyLock<Style> = LazyLock::new(Style::new);
pub(crate) static DIM: LazyLock<Style> = LazyLock::new(|| Style::new().dim());

pub(crate) static GREEN: Lazy<Style> = Lazy::new(|| Style::new().color256(2).bold().bright());
pub(crate) static BOLD_GREEN: Lazy<Style> = Lazy::new(|| Style::new().color256(82).bold().bright());
pub(crate) static YELLOW: Lazy<Style> = Lazy::new(|| Style::new().yellow().bright());
pub(crate) static BOLD_YELLOW: Lazy<Style> = Lazy::new(|| Style::new().yellow().bold().bright());
pub(crate) static PINK: Lazy<Style> = Lazy::new(|| Style::new().color256(197));
pub(crate) static BOLD_PINK: Lazy<Style> = Lazy::new(|| Style::new().color256(197).bold());
pub(crate) static GREEN: LazyLock<Style> =
LazyLock::new(|| Style::new().color256(2).bold().bright());
pub(crate) static BOLD_GREEN: LazyLock<Style> =
LazyLock::new(|| Style::new().color256(82).bold().bright());
pub(crate) static YELLOW: LazyLock<Style> = LazyLock::new(|| Style::new().yellow().bright());
pub(crate) static BOLD_YELLOW: LazyLock<Style> =
LazyLock::new(|| Style::new().yellow().bold().bright());
pub(crate) static PINK: LazyLock<Style> = LazyLock::new(|| Style::new().color256(197));
pub(crate) static BOLD_PINK: LazyLock<Style> = LazyLock::new(|| Style::new().color256(197).bold());

// Used for debug log messages
pub(crate) static BLUE: Lazy<Style> = Lazy::new(|| Style::new().blue().bright());
pub(crate) static BLUE: LazyLock<Style> = LazyLock::new(|| Style::new().blue().bright());

// Write output using predefined colors
macro_rules! color {
Expand Down
2 changes: 1 addition & 1 deletion lychee-bin/src/formatters/response/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub(crate) struct ColorFormatter;
impl ColorFormatter {
/// Determine the color for formatted output based on the status of the
/// response.
fn status_color(status: &Status) -> &'static once_cell::sync::Lazy<console::Style> {
fn status_color(status: &Status) -> &'static std::sync::LazyLock<console::Style> {
match status {
Status::Ok(_) | Status::Cached(CacheStatus::Ok(_)) => &GREEN,
Status::Excluded
Expand Down
4 changes: 2 additions & 2 deletions lychee-bin/src/formatters/stats/compact.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use anyhow::Result;
use console::Style;
use once_cell::sync::Lazy;
use std::sync::LazyLock;
use std::{
fmt::{self, Display},
time::Duration,
Expand Down Expand Up @@ -89,7 +89,7 @@ fn write_if_any(
value: usize,
symbol: &str,
text: &str,
style: &Lazy<Style>,
style: &LazyLock<Style>,
f: &mut fmt::Formatter<'_>,
) -> Result<(), fmt::Error> {
if value > 0 {
Expand Down
2 changes: 1 addition & 1 deletion lychee-bin/src/stats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ impl ResponseStats {
///
/// This function is used to update the counters (success, error, etc.)
/// based on the given response status.
pub(crate) fn increment_status_counters(&mut self, status: &Status) {
pub(crate) const fn increment_status_counters(&mut self, status: &Status) {
match status {
Status::Ok(_) => self.successful += 1,
Status::Error(_) => self.errors += 1,
Expand Down
2 changes: 1 addition & 1 deletion lychee-lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ license = "Apache-2.0 OR MIT"
repository = "https://github.com/lycheeverse/lychee"
readme = "../README.md"
version.workspace = true
rust-version = "1.83.0"

[dependencies]
async-stream = "0.3.6"
Expand All @@ -30,7 +31,6 @@ ip_network = "0.4.1"
linkify = "0.10.0"
log = "0.4.27"
octocrab = "0.44.0"
once_cell = "1.21.3"
openssl-sys = { version = "0.9.106", optional = true }
path-clean = "1.0.1"
percent-encoding = "2.3.1"
Expand Down
2 changes: 1 addition & 1 deletion lychee-lib/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ impl ClientBuilder {
"Found user-agent in headers: {}. Overriding it with {user_agent}.",
prev_user_agent.to_str().unwrap_or("�"),
);
};
}

headers.insert(
header::TRANSFER_ENCODING,
Expand Down
2 changes: 1 addition & 1 deletion lychee-lib/src/extract/markdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ pub(crate) fn extract_markdown_fragments(input: &str) -> HashSet<String> {
Event::Text(text) | Event::Code(text) => {
if in_heading {
heading_text.push_str(&text);
};
}
}

// An HTML node
Expand Down
21 changes: 11 additions & 10 deletions lychee-lib/src/filter/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
mod excludes;
mod includes;

use once_cell::sync::Lazy;
use regex::RegexSet;
use std::collections::HashSet;
use std::sync::LazyLock;

pub use excludes::Excludes;
pub use includes::Includes;
Expand All @@ -14,23 +14,24 @@ use crate::Uri;
/// These domains are explicitly defined by RFC 2606, section 3 Reserved Example
/// Second Level Domain Names for describing example cases and should not be
/// dereferenced as they should not have content.
static EXAMPLE_DOMAINS: Lazy<HashSet<&'static str>> =
Lazy::new(|| HashSet::from_iter(["example.com", "example.org", "example.net", "example.edu"]));
static EXAMPLE_DOMAINS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
HashSet::from_iter(["example.com", "example.org", "example.net", "example.edu"])
});

#[cfg(all(not(test), not(feature = "check_example_domains")))]
/// We also exclude the example TLDs in section 2 of the same RFC.
/// This exclusion gets subsumed by the `check_example_domains` feature.
static EXAMPLE_TLDS: Lazy<HashSet<&'static str>> =
Lazy::new(|| HashSet::from_iter([".test", ".example", ".invalid", ".localhost"]));
static EXAMPLE_TLDS: LazyLock<HashSet<&'static str>> =
LazyLock::new(|| HashSet::from_iter([".test", ".example", ".invalid", ".localhost"]));

// Allow usage of example domains in tests
#[cfg(any(test, feature = "check_example_domains"))]
static EXAMPLE_DOMAINS: Lazy<HashSet<&'static str>> = Lazy::new(HashSet::new);
static EXAMPLE_DOMAINS: LazyLock<HashSet<&'static str>> = LazyLock::new(HashSet::new);

#[cfg(any(test, feature = "check_example_domains"))]
static EXAMPLE_TLDS: Lazy<HashSet<&'static str>> = Lazy::new(HashSet::new);
static EXAMPLE_TLDS: LazyLock<HashSet<&'static str>> = LazyLock::new(HashSet::new);

static UNSUPPORTED_DOMAINS: Lazy<HashSet<&'static str>> = Lazy::new(|| {
static UNSUPPORTED_DOMAINS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
HashSet::from_iter([
// Twitter requires an account to view tweets
// https://news.ycombinator.com/item?id=36540957
Expand All @@ -50,8 +51,8 @@ const FALSE_POSITIVE_PAT: &[&str] = &[
r"^https?://(.*)/xmlrpc.php$",
];

static FALSE_POSITIVE_SET: Lazy<RegexSet> =
Lazy::new(|| regex::RegexSet::new(FALSE_POSITIVE_PAT).expect("Failed to create RegexSet"));
static FALSE_POSITIVE_SET: LazyLock<RegexSet> =
LazyLock::new(|| regex::RegexSet::new(FALSE_POSITIVE_PAT).expect("Failed to create RegexSet"));

#[inline]
#[must_use]
Expand Down
16 changes: 8 additions & 8 deletions lychee-lib/src/quirks/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,17 @@ use crate::{
use async_trait::async_trait;
use header::HeaderValue;
use http::header;
use once_cell::sync::Lazy;
use regex::Regex;
use reqwest::{Request, Url};
use std::collections::HashMap;
use std::sync::LazyLock;

static CRATES_PATTERN: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^(https?://)?(www\.)?crates.io").unwrap());
static YOUTUBE_PATTERN: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^(https?://)?(www\.)?youtube(-nocookie)?\.com").unwrap());
static YOUTUBE_SHORT_PATTERN: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^(https?://)?(www\.)?(youtu\.?be)").unwrap());
static CRATES_PATTERN: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^(https?://)?(www\.)?crates.io").unwrap());
static YOUTUBE_PATTERN: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^(https?://)?(www\.)?youtube(-nocookie)?\.com").unwrap());
static YOUTUBE_SHORT_PATTERN: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^(https?://)?(www\.)?(youtu\.?be)").unwrap());

// Retrieve a map of query params for the given request
fn query(request: &Request) -> HashMap<String, String> {
Expand All @@ -24,7 +24,7 @@ fn query(request: &Request) -> HashMap<String, String> {

#[derive(Debug, Clone)]
pub(crate) struct Quirk {
pub(crate) pattern: &'static Lazy<Regex>,
pub(crate) pattern: &'static LazyLock<Regex>,
pub(crate) rewrite: fn(Request) -> Request,
}

Expand Down
10 changes: 5 additions & 5 deletions lychee-lib/src/types/accept/range.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use std::{fmt::Display, num::ParseIntError, ops::RangeInclusive, str::FromStr};

use once_cell::sync::Lazy;
use regex::Regex;
use std::sync::LazyLock;
use thiserror::Error;

static RANGE_PATTERN: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^([0-9]{3})?\.\.((=?)([0-9]{3}))?$|^([0-9]{3})$").unwrap());
static RANGE_PATTERN: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^([0-9]{3})?\.\.((=?)([0-9]{3}))?$|^([0-9]{3})$").unwrap());

/// Indicates that the parsing process of an [`AcceptRange`] from a string
/// failed due to various underlying reasons.
Expand Down Expand Up @@ -113,7 +113,7 @@ impl AcceptRange {
self.0
}

pub(crate) fn update_start(&mut self, new_start: u16) -> Result<(), AcceptRangeError> {
pub(crate) const fn update_start(&mut self, new_start: u16) -> Result<(), AcceptRangeError> {
let end = *self.end();

if new_start > end {
Expand All @@ -124,7 +124,7 @@ impl AcceptRange {
Ok(())
}

pub(crate) fn update_end(&mut self, new_end: u16) -> Result<(), AcceptRangeError> {
pub(crate) const fn update_end(&mut self, new_end: u16) -> Result<(), AcceptRangeError> {
let start = *self.start();

if start > new_end {
Expand Down
2 changes: 1 addition & 1 deletion lychee-lib/src/types/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ impl Input {
Err(_) if skip_missing => (),
Err(e) => Err(e)?,
Ok(content) => yield content,
};
}
}
},
InputSource::Stdin => {
Expand Down
9 changes: 3 additions & 6 deletions lychee-lib/src/types/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,14 +113,14 @@ impl Status {
CacheStatus::Ok(code) => {
if matches!(s, CacheStatus::Ok(_)) || accepted.contains(&code) {
return Self::Cached(CacheStatus::Ok(code));
};
}
Self::Cached(CacheStatus::Error(Some(code)))
}
CacheStatus::Error(code) => {
if let Some(code) = code {
if accepted.contains(&code) {
return Self::Cached(CacheStatus::Ok(code));
};
}
}
Self::Cached(CacheStatus::Error(code))
}
Expand Down Expand Up @@ -225,10 +225,7 @@ impl Status {
}
}
Status::Cached(CacheStatus::Ok(code) | CacheStatus::Error(Some(code))) => {
match StatusCode::from_u16(*code) {
Ok(code) => Some(code),
Err(_) => None,
}
StatusCode::from_u16(*code).ok()
}
_ => None,
}
Expand Down
6 changes: 3 additions & 3 deletions lychee-lib/src/types/uri/github.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use std::collections::HashSet;

use once_cell::sync::Lazy;
use std::sync::LazyLock;

use crate::{ErrorKind, Result, Uri};

static GITHUB_API_EXCLUDED_ENDPOINTS: Lazy<HashSet<&'static str>> = Lazy::new(|| {
static GITHUB_API_EXCLUDED_ENDPOINTS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
HashSet::from_iter([
"about",
"collections",
Expand Down Expand Up @@ -74,7 +74,7 @@ impl GithubUri {
"github.com" | "www.github.com" | "raw.githubusercontent.com"
) {
return Err(ErrorKind::InvalidGithubUrl(uri.to_string()));
};
}

let parts: Vec<_> = match uri.path_segments() {
Some(parts) => parts.collect(),
Expand Down
4 changes: 2 additions & 2 deletions lychee-lib/src/types/uri/valid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,8 +254,8 @@ impl TryFrom<&str> for Uri {
// which will allow `Url::parse` to parse them.
if let Ok(uri) = Url::parse(&format!("mailto:{s}")) {
return Ok(uri.into());
};
};
}
}

// We do not handle relative URLs here, as we do not know the base URL.
Err(ErrorKind::ParseUrl(err, s.to_owned()))
Expand Down
2 changes: 1 addition & 1 deletion lychee-lib/src/utils/fragment_checker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ impl FragmentChecker {
};
if fragment.is_empty() || fragment.eq_ignore_ascii_case("top") {
return Ok(true);
};
}
let mut fragment_decoded = percent_decode_str(fragment).decode_utf8()?;
let url_without_frag = Self::remove_fragment(url.clone());

Expand Down
6 changes: 3 additions & 3 deletions lychee-lib/src/utils/path.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use crate::{ErrorKind, Result};
use cached::proc_macro::cached;
use once_cell::sync::Lazy;
use path_clean::PathClean;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;

static CURRENT_DIR: Lazy<PathBuf> =
Lazy::new(|| env::current_dir().expect("cannot get current dir from environment"));
static CURRENT_DIR: LazyLock<PathBuf> =
LazyLock::new(|| env::current_dir().expect("cannot get current dir from environment"));

/// Create an absolute path out of a `PathBuf`.
///
Expand Down
4 changes: 2 additions & 2 deletions lychee-lib/src/utils/url.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use linkify::LinkFinder;

use once_cell::sync::Lazy;
use std::sync::LazyLock;

static LINK_FINDER: Lazy<LinkFinder> = Lazy::new(LinkFinder::new);
static LINK_FINDER: LazyLock<LinkFinder> = LazyLock::new(LinkFinder::new);

/// Remove all GET parameters from a URL and separates out the fragment.
/// The link is not a URL but a String as it may not have a base domain.
Expand Down
Loading