From 5f648af104a5730b15bd842ee2c48f210c863c30 Mon Sep 17 00:00:00 2001 From: Gerald Pinder Date: Mon, 28 Apr 2025 20:57:23 -0400 Subject: [PATCH] chore: Clippy fixes --- .rusty-hook.toml | 2 +- Cargo.lock | 1 - process/Cargo.toml | 1 - process/drivers.rs | 23 ++++++------- process/drivers/docker_driver.rs | 8 ++--- process/logging.rs | 9 +++--- process/process.rs | 18 ++++------- process/signal_handler.rs | 8 ++--- recipe/src/module/type_ver.rs | 2 +- src/commands/bug_report.rs | 2 +- src/commands/validate.rs | 12 ++++--- src/commands/validate/schema_validator.rs | 39 +++++++++++------------ src/commands/validate/yaml_span.rs | 11 +++---- src/rpm_ostree_status.rs | 4 +-- utils/src/command_output.rs | 12 +++---- 15 files changed, 74 insertions(+), 78 deletions(-) diff --git a/.rusty-hook.toml b/.rusty-hook.toml index 29b25ec..672ae15 100644 --- a/.rusty-hook.toml +++ b/.rusty-hook.toml @@ -1,5 +1,5 @@ [hooks] -pre-push = "cargo fmt --check && cargo test --workspace && cargo test --workspace --all-features && cargo clippy -- -D warnings && cargo clippy --all-features -- -D warnings" +pre-push = "cargo fmt --check --all && cargo test --workspace && cargo test --workspace --all-features && cargo clippy -- -D warnings && cargo clippy --all-features -- -D warnings" [logging] verbose = true diff --git a/Cargo.lock b/Cargo.lock index 8bd127f..76d04eb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -496,7 +496,6 @@ dependencies = [ "nix", "nu-ansi-term", "oci-distribution", - "once_cell", "os_pipe", "rand 0.9.1", "reqwest", diff --git a/process/Cargo.toml b/process/Cargo.toml index 5651d33..44de117 100644 --- a/process/Cargo.toml +++ b/process/Cargo.toml @@ -16,7 +16,6 @@ blue-build-utils = { version = "=0.9.11", path = "../utils" } indicatif-log-bridge = "0.2" log4rs = { version = "1", features = ["background_rotation"] } nu-ansi-term = { version = "0.50", features = ["gnu_legacy"] } -once_cell = "1" os_pipe = { version = "1", features = ["io_safety"] } rand = "0.9" signal-hook = { version = "0.3", features = ["extended-siginfo"] } diff --git a/process/drivers.rs b/process/drivers.rs index 6777fca..37f5e81 100644 --- a/process/drivers.rs +++ b/process/drivers.rs @@ -22,7 +22,6 @@ use indicatif::{ProgressBar, ProgressStyle}; use log::{info, trace, warn}; use miette::{miette, IntoDiagnostic, Result}; use oci_distribution::Reference; -use once_cell::sync::Lazy; use opts::{ BuildOpts, BuildTagPushOpts, CheckKeyPairOpts, CreateContainerOpts, GenerateImageNameOpts, GenerateKeyPairOpts, GenerateTagsOpts, GetMetadataOpts, PushOpts, RemoveContainerOpts, @@ -59,18 +58,20 @@ mod skopeo_driver; mod traits; pub mod types; -static INIT: Lazy> = Lazy::new(|| Mutex::new(false)); -static SELECTED_BUILD_DRIVER: Lazy>> = - Lazy::new(|| RwLock::new(None)); -static SELECTED_INSPECT_DRIVER: Lazy>> = - Lazy::new(|| RwLock::new(None)); -static SELECTED_RUN_DRIVER: Lazy>> = Lazy::new(|| RwLock::new(None)); -static SELECTED_SIGNING_DRIVER: Lazy>> = - Lazy::new(|| RwLock::new(None)); -static SELECTED_CI_DRIVER: Lazy>> = Lazy::new(|| RwLock::new(None)); +static INIT: std::sync::LazyLock> = std::sync::LazyLock::new(|| Mutex::new(false)); +static SELECTED_BUILD_DRIVER: std::sync::LazyLock>> = + std::sync::LazyLock::new(|| RwLock::new(None)); +static SELECTED_INSPECT_DRIVER: std::sync::LazyLock>> = + std::sync::LazyLock::new(|| RwLock::new(None)); +static SELECTED_RUN_DRIVER: std::sync::LazyLock>> = + std::sync::LazyLock::new(|| RwLock::new(None)); +static SELECTED_SIGNING_DRIVER: std::sync::LazyLock>> = + std::sync::LazyLock::new(|| RwLock::new(None)); +static SELECTED_CI_DRIVER: std::sync::LazyLock>> = + std::sync::LazyLock::new(|| RwLock::new(None)); /// UUID used to mark the current builds -static BUILD_ID: Lazy = Lazy::new(Uuid::new_v4); +static BUILD_ID: std::sync::LazyLock = std::sync::LazyLock::new(Uuid::new_v4); /// Args for selecting the various drivers to use for runtime. /// diff --git a/process/drivers/docker_driver.rs b/process/drivers/docker_driver.rs index c1f4233..b742d5b 100644 --- a/process/drivers/docker_driver.rs +++ b/process/drivers/docker_driver.rs @@ -17,7 +17,6 @@ use comlexr::{cmd, pipe}; use log::{debug, info, trace, warn}; use miette::{bail, Context, IntoDiagnostic, Result}; use oci_distribution::Reference; -use once_cell::sync::Lazy; use serde::Deserialize; use tempfile::TempDir; @@ -50,7 +49,8 @@ struct DockerVersionJson { pub client: DockerVerisonJsonClient, } -static DOCKER_SETUP: Lazy> = Lazy::new(|| Mutex::new(false)); +static DOCKER_SETUP: std::sync::LazyLock> = + std::sync::LazyLock::new(|| Mutex::new(false)); #[derive(Debug)] pub struct DockerDriver; @@ -411,9 +411,9 @@ impl BuildDriver for DockerDriver { if status.success() { if opts.push { - info!("Successfully built and pushed image {}", first_image); + info!("Successfully built and pushed image {first_image}"); } else { - info!("Successfully built image {}", first_image); + info!("Successfully built image {first_image}"); } } else { bail!("Failed to build image {}", first_image); diff --git a/process/logging.rs b/process/logging.rs index 4d65f5c..547741f 100644 --- a/process/logging.rs +++ b/process/logging.rs @@ -31,7 +31,6 @@ use log4rs::{ Config, Logger as L4RSLogger, }; use nu_ansi_term::Color; -use once_cell::sync::Lazy; use private::Private; use rand::Rng; @@ -43,8 +42,10 @@ mod private { impl Private for Command {} -static MULTI_PROGRESS: Lazy = Lazy::new(MultiProgress::new); -static LOG_DIR: Lazy> = Lazy::new(|| Mutex::new(PathBuf::new())); +static MULTI_PROGRESS: std::sync::LazyLock = + std::sync::LazyLock::new(MultiProgress::new); +static LOG_DIR: std::sync::LazyLock> = + std::sync::LazyLock::new(|| Mutex::new(PathBuf::new())); #[derive(Debug, Clone)] pub struct Logger { @@ -76,7 +77,7 @@ impl Logger { self } - pub fn filter_level(&mut self, filter_level: LevelFilter) -> &mut Self { + pub const fn filter_level(&mut self, filter_level: LevelFilter) -> &mut Self { self.level = filter_level; self } diff --git a/process/process.rs b/process/process.rs index 693c1ba..fcd9f0a 100644 --- a/process/process.rs +++ b/process/process.rs @@ -2,22 +2,18 @@ //! by this tool. It contains drivers for running, building, inspecting, and signing //! images that interface with tools like docker or podman. -#[cfg(any(feature = "sigstore", feature = "validate"))] -use once_cell::sync::Lazy; -#[cfg(any(feature = "sigstore", feature = "validate"))] -use tokio::runtime::Runtime; - pub mod drivers; pub mod logging; pub mod signal_handler; #[cfg(any(feature = "sigstore", feature = "validate"))] -pub static ASYNC_RUNTIME: Lazy = Lazy::new(|| { - tokio::runtime::Builder::new_multi_thread() - .enable_all() - .build() - .unwrap() -}); +pub static ASYNC_RUNTIME: std::sync::LazyLock = + std::sync::LazyLock::new(|| { + tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .unwrap() + }); #[cfg(test)] pub(crate) mod test { diff --git a/process/signal_handler.rs b/process/signal_handler.rs index a33bbcd..02a2831 100644 --- a/process/signal_handler.rs +++ b/process/signal_handler.rs @@ -14,7 +14,6 @@ use nix::{ sys::signal::{kill, Signal}, unistd::Pid, }; -use once_cell::sync::Lazy; use signal_hook::{ consts::TERM_SIGNALS, flag, @@ -60,9 +59,10 @@ impl ContainerSignalId { } } -static PID_LIST: Lazy>>> = Lazy::new(|| Arc::new(Mutex::new(vec![]))); -static CID_LIST: Lazy>>> = - Lazy::new(|| Arc::new(Mutex::new(vec![]))); +static PID_LIST: std::sync::LazyLock>>> = + std::sync::LazyLock::new(|| Arc::new(Mutex::new(vec![]))); +static CID_LIST: std::sync::LazyLock>>> = + std::sync::LazyLock::new(|| Arc::new(Mutex::new(vec![]))); /// Initialize Ctrl-C handler. This should be done at the start /// of a binary. diff --git a/recipe/src/module/type_ver.rs b/recipe/src/module/type_ver.rs index bef11e2..bcaadbc 100644 --- a/recipe/src/module/type_ver.rs +++ b/recipe/src/module/type_ver.rs @@ -11,7 +11,7 @@ pub struct ModuleTypeVersion<'scope> { impl ModuleTypeVersion<'_> { #[must_use] pub fn typ(&self) -> &str { - &self.typ + self.typ.as_ref() } #[must_use] diff --git a/src/commands/bug_report.rs b/src/commands/bug_report.rs index dc242c4..cded0e0 100644 --- a/src/commands/bug_report.rs +++ b/src/commands/bug_report.rs @@ -146,7 +146,7 @@ fn get_config_file(title: &str, message: &str) -> Result { Ok(requestty::Answer::String(path)) => Ok(path), Ok(_) => unreachable!(), Err(e) => { - trace!("Failed to get file: {}", e); + trace!("Failed to get file: {e}"); Err(e).into_diagnostic() } } diff --git a/src/commands/validate.rs b/src/commands/validate.rs index 65b859a..8b50b14 100644 --- a/src/commands/validate.rs +++ b/src/commands/validate.rs @@ -1,4 +1,5 @@ use std::{ + fmt::Write, fs::OpenOptions, io::{BufReader, Read}, path::{Path, PathBuf}, @@ -66,10 +67,13 @@ impl BlueBuildCommand for ValidateCommand { ASYNC_RUNTIME.block_on(self.setup_validators())?; if let Err(errors) = self.validate_recipe() { - let errors = errors.into_iter().fold(String::new(), |mut full, err| { - full.push_str(&format!("{err:?}")); - full - }); + let errors = errors.into_iter().try_fold( + String::new(), + |mut full, err| -> miette::Result { + write!(&mut full, "{err:?}").into_diagnostic()?; + Ok(full) + }, + )?; let main_err = format!("Recipe {recipe_path_display} failed to validate"); if self.all_errors { diff --git a/src/commands/validate/schema_validator.rs b/src/commands/validate/schema_validator.rs index 1361a54..3db2518 100644 --- a/src/commands/validate/schema_validator.rs +++ b/src/commands/validate/schema_validator.rs @@ -6,9 +6,8 @@ use std::{ use blue_build_process_management::ASYNC_RUNTIME; use blue_build_recipe::ModuleTypeVersion; -use blue_build_utils::{ - constants::{CUSTOM_MODULE_SCHEMA, IMPORT_MODULE_SCHEMA, JSON_SCHEMA, STAGE_SCHEMA}, - retry_async, +use blue_build_utils::constants::{ + CUSTOM_MODULE_SCHEMA, IMPORT_MODULE_SCHEMA, JSON_SCHEMA, STAGE_SCHEMA, }; use bon::bon; use cached::proc_macro::cached; @@ -337,24 +336,22 @@ async fn cache_retrieve(uri: &Uri) -> miette::Result { }; log::debug!("Retrieving schema from {}", uri.bold().italic()); - tokio::spawn( - retry_async(3, 2, async move || { - let response = reqwest::get(&*uri) - .await - .into_diagnostic() - .with_context(|| format!("Failed to retrieve schema from {uri}"))?; - let raw_output = response.bytes().await.into_diagnostic()?; - serde_json::from_slice(&raw_output) - .into_diagnostic() - .with_context(|| { - format!( - "Failed to parse json from {uri}, contents:\n{}", - String::from_utf8_lossy(&raw_output) - ) - }) - .inspect(|value| trace!("{}:\n{value}", uri.bold().italic())) - }) - ) + tokio::spawn(blue_build_utils::retry_async(3, 2, async move || { + let response = reqwest::get(&*uri) + .await + .into_diagnostic() + .with_context(|| format!("Failed to retrieve schema from {uri}"))?; + let raw_output = response.bytes().await.into_diagnostic()?; + serde_json::from_slice(&raw_output) + .into_diagnostic() + .with_context(|| { + format!( + "Failed to parse json from {uri}, contents:\n{}", + String::from_utf8_lossy(&raw_output) + ) + }) + .inspect(|value| trace!("{}:\n{value}", uri.bold().italic())) + })) .await .expect("Should join task") } diff --git a/src/commands/validate/yaml_span.rs b/src/commands/validate/yaml_span.rs index fb22c3f..b374a0c 100644 --- a/src/commands/validate/yaml_span.rs +++ b/src/commands/validate/yaml_span.rs @@ -1,3 +1,4 @@ +#![allow(clippy::needless_continue)] use std::sync::Arc; use bon::bon; @@ -79,7 +80,7 @@ where P: Iterator>, { #[builder] - pub fn new(events: &'a mut I, path: &'b mut P) -> Self { + pub const fn new(events: &'a mut I, path: &'b mut P) -> Self { Self { events, path } } @@ -103,11 +104,9 @@ where match event { Event::StreamStart if !stream_start && !document_start => { stream_start = true; - continue; } Event::DocumentStart if stream_start && !document_start => { document_start = true; - continue; } Event::MappingStart(_, _) if stream_start && document_start => { break self.key(key)?.into(); @@ -182,8 +181,8 @@ where Event::Scalar(value, _, _, _) => { last_index = marker.index() + value.len(); } - _ => continue, - }; + _ => (), + } } } @@ -203,7 +202,7 @@ where last_index = marker.index() + value.len(); } _ => continue, - }; + } } } diff --git a/src/rpm_ostree_status.rs b/src/rpm_ostree_status.rs index 584177c..0413dbf 100644 --- a/src/rpm_ostree_status.rs +++ b/src/rpm_ostree_status.rs @@ -79,7 +79,7 @@ impl RpmOstreeStatus<'_> { self.booted_image().is_some_and(|deployment| { deployment .split(':') - .last() + .next_back() .is_some_and(|boot_ref| Path::new(boot_ref) == archive_path.as_ref()) }) } @@ -92,7 +92,7 @@ impl RpmOstreeStatus<'_> { self.staged_image().is_some_and(|deployment| { deployment .split(':') - .last() + .next_back() .is_some_and(|boot_ref| Path::new(boot_ref) == archive_path.as_ref()) }) } diff --git a/utils/src/command_output.rs b/utils/src/command_output.rs index cc28192..111109e 100644 --- a/utils/src/command_output.rs +++ b/utils/src/command_output.rs @@ -22,15 +22,15 @@ pub struct CommandOutput { /// fn create_command>(binary_name: T) -> Result { let binary_name = binary_name.as_ref(); - log::trace!("Creating Command for binary {:?}", binary_name); + log::trace!("Creating Command for binary {binary_name:?}"); let full_path = match which::which(binary_name) { Ok(full_path) => { - log::trace!("Using {:?} as {:?}", full_path, binary_name); + log::trace!("Using {full_path:?} as {binary_name:?}"); full_path } Err(error) => { - log::trace!("Unable to find {:?} in PATH, {:?}", binary_name, error); + log::trace!("Unable to find {binary_name:?} in PATH, {error:?}"); return Err(Error::new(ErrorKind::NotFound, error)); } }; @@ -49,7 +49,7 @@ pub fn exec_cmd + Debug, U: AsRef + Debug>( args: &[U], time_limit: Duration, ) -> Option { - log::trace!("Executing command {:?} with args {:?}", cmd, args); + log::trace!("Executing command {cmd:?} with args {args:?}"); internal_exec_cmd(cmd, args, time_limit) } @@ -82,14 +82,14 @@ fn exec_timeout(cmd: &mut Command, time_limit: Duration) -> Option stdout, Err(error) => { - log::warn!("Unable to decode stdout: {:?}", error); + log::warn!("Unable to decode stdout: {error:?}"); return None; } }; let stderr_string = match String::from_utf8(output.stderr) { Ok(stderr) => stderr, Err(error) => { - log::warn!("Unable to decode stderr: {:?}", error); + log::warn!("Unable to decode stderr: {error:?}"); return None; } };