chore: Clippy fixes

This commit is contained in:
Gerald Pinder 2025-04-28 20:57:23 -04:00
parent 6bae48bd88
commit 5f648af104
15 changed files with 74 additions and 78 deletions

View file

@ -1,5 +1,5 @@
[hooks] [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] [logging]
verbose = true verbose = true

1
Cargo.lock generated
View file

@ -496,7 +496,6 @@ dependencies = [
"nix", "nix",
"nu-ansi-term", "nu-ansi-term",
"oci-distribution", "oci-distribution",
"once_cell",
"os_pipe", "os_pipe",
"rand 0.9.1", "rand 0.9.1",
"reqwest", "reqwest",

View file

@ -16,7 +16,6 @@ blue-build-utils = { version = "=0.9.11", path = "../utils" }
indicatif-log-bridge = "0.2" indicatif-log-bridge = "0.2"
log4rs = { version = "1", features = ["background_rotation"] } log4rs = { version = "1", features = ["background_rotation"] }
nu-ansi-term = { version = "0.50", features = ["gnu_legacy"] } nu-ansi-term = { version = "0.50", features = ["gnu_legacy"] }
once_cell = "1"
os_pipe = { version = "1", features = ["io_safety"] } os_pipe = { version = "1", features = ["io_safety"] }
rand = "0.9" rand = "0.9"
signal-hook = { version = "0.3", features = ["extended-siginfo"] } signal-hook = { version = "0.3", features = ["extended-siginfo"] }

View file

@ -22,7 +22,6 @@ use indicatif::{ProgressBar, ProgressStyle};
use log::{info, trace, warn}; use log::{info, trace, warn};
use miette::{miette, IntoDiagnostic, Result}; use miette::{miette, IntoDiagnostic, Result};
use oci_distribution::Reference; use oci_distribution::Reference;
use once_cell::sync::Lazy;
use opts::{ use opts::{
BuildOpts, BuildTagPushOpts, CheckKeyPairOpts, CreateContainerOpts, GenerateImageNameOpts, BuildOpts, BuildTagPushOpts, CheckKeyPairOpts, CreateContainerOpts, GenerateImageNameOpts,
GenerateKeyPairOpts, GenerateTagsOpts, GetMetadataOpts, PushOpts, RemoveContainerOpts, GenerateKeyPairOpts, GenerateTagsOpts, GetMetadataOpts, PushOpts, RemoveContainerOpts,
@ -59,18 +58,20 @@ mod skopeo_driver;
mod traits; mod traits;
pub mod types; pub mod types;
static INIT: Lazy<Mutex<bool>> = Lazy::new(|| Mutex::new(false)); static INIT: std::sync::LazyLock<Mutex<bool>> = std::sync::LazyLock::new(|| Mutex::new(false));
static SELECTED_BUILD_DRIVER: Lazy<RwLock<Option<BuildDriverType>>> = static SELECTED_BUILD_DRIVER: std::sync::LazyLock<RwLock<Option<BuildDriverType>>> =
Lazy::new(|| RwLock::new(None)); std::sync::LazyLock::new(|| RwLock::new(None));
static SELECTED_INSPECT_DRIVER: Lazy<RwLock<Option<InspectDriverType>>> = static SELECTED_INSPECT_DRIVER: std::sync::LazyLock<RwLock<Option<InspectDriverType>>> =
Lazy::new(|| RwLock::new(None)); std::sync::LazyLock::new(|| RwLock::new(None));
static SELECTED_RUN_DRIVER: Lazy<RwLock<Option<RunDriverType>>> = Lazy::new(|| RwLock::new(None)); static SELECTED_RUN_DRIVER: std::sync::LazyLock<RwLock<Option<RunDriverType>>> =
static SELECTED_SIGNING_DRIVER: Lazy<RwLock<Option<SigningDriverType>>> = std::sync::LazyLock::new(|| RwLock::new(None));
Lazy::new(|| RwLock::new(None)); static SELECTED_SIGNING_DRIVER: std::sync::LazyLock<RwLock<Option<SigningDriverType>>> =
static SELECTED_CI_DRIVER: Lazy<RwLock<Option<CiDriverType>>> = Lazy::new(|| RwLock::new(None)); std::sync::LazyLock::new(|| RwLock::new(None));
static SELECTED_CI_DRIVER: std::sync::LazyLock<RwLock<Option<CiDriverType>>> =
std::sync::LazyLock::new(|| RwLock::new(None));
/// UUID used to mark the current builds /// UUID used to mark the current builds
static BUILD_ID: Lazy<Uuid> = Lazy::new(Uuid::new_v4); static BUILD_ID: std::sync::LazyLock<Uuid> = std::sync::LazyLock::new(Uuid::new_v4);
/// Args for selecting the various drivers to use for runtime. /// Args for selecting the various drivers to use for runtime.
/// ///

View file

@ -17,7 +17,6 @@ use comlexr::{cmd, pipe};
use log::{debug, info, trace, warn}; use log::{debug, info, trace, warn};
use miette::{bail, Context, IntoDiagnostic, Result}; use miette::{bail, Context, IntoDiagnostic, Result};
use oci_distribution::Reference; use oci_distribution::Reference;
use once_cell::sync::Lazy;
use serde::Deserialize; use serde::Deserialize;
use tempfile::TempDir; use tempfile::TempDir;
@ -50,7 +49,8 @@ struct DockerVersionJson {
pub client: DockerVerisonJsonClient, pub client: DockerVerisonJsonClient,
} }
static DOCKER_SETUP: Lazy<Mutex<bool>> = Lazy::new(|| Mutex::new(false)); static DOCKER_SETUP: std::sync::LazyLock<Mutex<bool>> =
std::sync::LazyLock::new(|| Mutex::new(false));
#[derive(Debug)] #[derive(Debug)]
pub struct DockerDriver; pub struct DockerDriver;
@ -411,9 +411,9 @@ impl BuildDriver for DockerDriver {
if status.success() { if status.success() {
if opts.push { if opts.push {
info!("Successfully built and pushed image {}", first_image); info!("Successfully built and pushed image {first_image}");
} else { } else {
info!("Successfully built image {}", first_image); info!("Successfully built image {first_image}");
} }
} else { } else {
bail!("Failed to build image {}", first_image); bail!("Failed to build image {}", first_image);

View file

@ -31,7 +31,6 @@ use log4rs::{
Config, Logger as L4RSLogger, Config, Logger as L4RSLogger,
}; };
use nu_ansi_term::Color; use nu_ansi_term::Color;
use once_cell::sync::Lazy;
use private::Private; use private::Private;
use rand::Rng; use rand::Rng;
@ -43,8 +42,10 @@ mod private {
impl Private for Command {} impl Private for Command {}
static MULTI_PROGRESS: Lazy<MultiProgress> = Lazy::new(MultiProgress::new); static MULTI_PROGRESS: std::sync::LazyLock<MultiProgress> =
static LOG_DIR: Lazy<Mutex<PathBuf>> = Lazy::new(|| Mutex::new(PathBuf::new())); std::sync::LazyLock::new(MultiProgress::new);
static LOG_DIR: std::sync::LazyLock<Mutex<PathBuf>> =
std::sync::LazyLock::new(|| Mutex::new(PathBuf::new()));
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Logger { pub struct Logger {
@ -76,7 +77,7 @@ impl Logger {
self 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.level = filter_level;
self self
} }

View file

@ -2,17 +2,13 @@
//! by this tool. It contains drivers for running, building, inspecting, and signing //! by this tool. It contains drivers for running, building, inspecting, and signing
//! images that interface with tools like docker or podman. //! 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 drivers;
pub mod logging; pub mod logging;
pub mod signal_handler; pub mod signal_handler;
#[cfg(any(feature = "sigstore", feature = "validate"))] #[cfg(any(feature = "sigstore", feature = "validate"))]
pub static ASYNC_RUNTIME: Lazy<Runtime> = Lazy::new(|| { pub static ASYNC_RUNTIME: std::sync::LazyLock<tokio::runtime::Runtime> =
std::sync::LazyLock::new(|| {
tokio::runtime::Builder::new_multi_thread() tokio::runtime::Builder::new_multi_thread()
.enable_all() .enable_all()
.build() .build()

View file

@ -14,7 +14,6 @@ use nix::{
sys::signal::{kill, Signal}, sys::signal::{kill, Signal},
unistd::Pid, unistd::Pid,
}; };
use once_cell::sync::Lazy;
use signal_hook::{ use signal_hook::{
consts::TERM_SIGNALS, consts::TERM_SIGNALS,
flag, flag,
@ -60,9 +59,10 @@ impl ContainerSignalId {
} }
} }
static PID_LIST: Lazy<Arc<Mutex<Vec<i32>>>> = Lazy::new(|| Arc::new(Mutex::new(vec![]))); static PID_LIST: std::sync::LazyLock<Arc<Mutex<Vec<i32>>>> =
static CID_LIST: Lazy<Arc<Mutex<Vec<ContainerSignalId>>>> = std::sync::LazyLock::new(|| Arc::new(Mutex::new(vec![])));
Lazy::new(|| Arc::new(Mutex::new(vec![]))); static CID_LIST: std::sync::LazyLock<Arc<Mutex<Vec<ContainerSignalId>>>> =
std::sync::LazyLock::new(|| Arc::new(Mutex::new(vec![])));
/// Initialize Ctrl-C handler. This should be done at the start /// Initialize Ctrl-C handler. This should be done at the start
/// of a binary. /// of a binary.

View file

@ -11,7 +11,7 @@ pub struct ModuleTypeVersion<'scope> {
impl ModuleTypeVersion<'_> { impl ModuleTypeVersion<'_> {
#[must_use] #[must_use]
pub fn typ(&self) -> &str { pub fn typ(&self) -> &str {
&self.typ self.typ.as_ref()
} }
#[must_use] #[must_use]

View file

@ -146,7 +146,7 @@ fn get_config_file(title: &str, message: &str) -> Result<String> {
Ok(requestty::Answer::String(path)) => Ok(path), Ok(requestty::Answer::String(path)) => Ok(path),
Ok(_) => unreachable!(), Ok(_) => unreachable!(),
Err(e) => { Err(e) => {
trace!("Failed to get file: {}", e); trace!("Failed to get file: {e}");
Err(e).into_diagnostic() Err(e).into_diagnostic()
} }
} }

View file

@ -1,4 +1,5 @@
use std::{ use std::{
fmt::Write,
fs::OpenOptions, fs::OpenOptions,
io::{BufReader, Read}, io::{BufReader, Read},
path::{Path, PathBuf}, path::{Path, PathBuf},
@ -66,10 +67,13 @@ impl BlueBuildCommand for ValidateCommand {
ASYNC_RUNTIME.block_on(self.setup_validators())?; ASYNC_RUNTIME.block_on(self.setup_validators())?;
if let Err(errors) = self.validate_recipe() { if let Err(errors) = self.validate_recipe() {
let errors = errors.into_iter().fold(String::new(), |mut full, err| { let errors = errors.into_iter().try_fold(
full.push_str(&format!("{err:?}")); String::new(),
full |mut full, err| -> miette::Result<String> {
}); write!(&mut full, "{err:?}").into_diagnostic()?;
Ok(full)
},
)?;
let main_err = format!("Recipe {recipe_path_display} failed to validate"); let main_err = format!("Recipe {recipe_path_display} failed to validate");
if self.all_errors { if self.all_errors {

View file

@ -6,9 +6,8 @@ use std::{
use blue_build_process_management::ASYNC_RUNTIME; use blue_build_process_management::ASYNC_RUNTIME;
use blue_build_recipe::ModuleTypeVersion; use blue_build_recipe::ModuleTypeVersion;
use blue_build_utils::{ use blue_build_utils::constants::{
constants::{CUSTOM_MODULE_SCHEMA, IMPORT_MODULE_SCHEMA, JSON_SCHEMA, STAGE_SCHEMA}, CUSTOM_MODULE_SCHEMA, IMPORT_MODULE_SCHEMA, JSON_SCHEMA, STAGE_SCHEMA,
retry_async,
}; };
use bon::bon; use bon::bon;
use cached::proc_macro::cached; use cached::proc_macro::cached;
@ -337,8 +336,7 @@ async fn cache_retrieve(uri: &Uri<String>) -> miette::Result<Value> {
}; };
log::debug!("Retrieving schema from {}", uri.bold().italic()); log::debug!("Retrieving schema from {}", uri.bold().italic());
tokio::spawn( tokio::spawn(blue_build_utils::retry_async(3, 2, async move || {
retry_async(3, 2, async move || {
let response = reqwest::get(&*uri) let response = reqwest::get(&*uri)
.await .await
.into_diagnostic() .into_diagnostic()
@ -353,8 +351,7 @@ async fn cache_retrieve(uri: &Uri<String>) -> miette::Result<Value> {
) )
}) })
.inspect(|value| trace!("{}:\n{value}", uri.bold().italic())) .inspect(|value| trace!("{}:\n{value}", uri.bold().italic()))
}) }))
)
.await .await
.expect("Should join task") .expect("Should join task")
} }

View file

@ -1,3 +1,4 @@
#![allow(clippy::needless_continue)]
use std::sync::Arc; use std::sync::Arc;
use bon::bon; use bon::bon;
@ -79,7 +80,7 @@ where
P: Iterator<Item = LocationSegment<'b>>, P: Iterator<Item = LocationSegment<'b>>,
{ {
#[builder] #[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 } Self { events, path }
} }
@ -103,11 +104,9 @@ where
match event { match event {
Event::StreamStart if !stream_start && !document_start => { Event::StreamStart if !stream_start && !document_start => {
stream_start = true; stream_start = true;
continue;
} }
Event::DocumentStart if stream_start && !document_start => { Event::DocumentStart if stream_start && !document_start => {
document_start = true; document_start = true;
continue;
} }
Event::MappingStart(_, _) if stream_start && document_start => { Event::MappingStart(_, _) if stream_start && document_start => {
break self.key(key)?.into(); break self.key(key)?.into();
@ -182,8 +181,8 @@ where
Event::Scalar(value, _, _, _) => { Event::Scalar(value, _, _, _) => {
last_index = marker.index() + value.len(); last_index = marker.index() + value.len();
} }
_ => continue, _ => (),
}; }
} }
} }
@ -203,7 +202,7 @@ where
last_index = marker.index() + value.len(); last_index = marker.index() + value.len();
} }
_ => continue, _ => continue,
}; }
} }
} }

View file

@ -79,7 +79,7 @@ impl RpmOstreeStatus<'_> {
self.booted_image().is_some_and(|deployment| { self.booted_image().is_some_and(|deployment| {
deployment deployment
.split(':') .split(':')
.last() .next_back()
.is_some_and(|boot_ref| Path::new(boot_ref) == archive_path.as_ref()) .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| { self.staged_image().is_some_and(|deployment| {
deployment deployment
.split(':') .split(':')
.last() .next_back()
.is_some_and(|boot_ref| Path::new(boot_ref) == archive_path.as_ref()) .is_some_and(|boot_ref| Path::new(boot_ref) == archive_path.as_ref())
}) })
} }

View file

@ -22,15 +22,15 @@ pub struct CommandOutput {
/// ///
fn create_command<T: AsRef<OsStr>>(binary_name: T) -> Result<Command> { fn create_command<T: AsRef<OsStr>>(binary_name: T) -> Result<Command> {
let binary_name = binary_name.as_ref(); 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) { let full_path = match which::which(binary_name) {
Ok(full_path) => { Ok(full_path) => {
log::trace!("Using {:?} as {:?}", full_path, binary_name); log::trace!("Using {full_path:?} as {binary_name:?}");
full_path full_path
} }
Err(error) => { 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)); return Err(Error::new(ErrorKind::NotFound, error));
} }
}; };
@ -49,7 +49,7 @@ pub fn exec_cmd<T: AsRef<OsStr> + Debug, U: AsRef<OsStr> + Debug>(
args: &[U], args: &[U],
time_limit: Duration, time_limit: Duration,
) -> Option<CommandOutput> { ) -> Option<CommandOutput> {
log::trace!("Executing command {:?} with args {:?}", cmd, args); log::trace!("Executing command {cmd:?} with args {args:?}");
internal_exec_cmd(cmd, args, time_limit) internal_exec_cmd(cmd, args, time_limit)
} }
@ -82,14 +82,14 @@ fn exec_timeout(cmd: &mut Command, time_limit: Duration) -> Option<CommandOutput
let stdout_string = match String::from_utf8(output.stdout) { let stdout_string = match String::from_utf8(output.stdout) {
Ok(stdout) => stdout, Ok(stdout) => stdout,
Err(error) => { Err(error) => {
log::warn!("Unable to decode stdout: {:?}", error); log::warn!("Unable to decode stdout: {error:?}");
return None; return None;
} }
}; };
let stderr_string = match String::from_utf8(output.stderr) { let stderr_string = match String::from_utf8(output.stderr) {
Ok(stderr) => stderr, Ok(stderr) => stderr,
Err(error) => { Err(error) => {
log::warn!("Unable to decode stderr: {:?}", error); log::warn!("Unable to decode stderr: {error:?}");
return None; return None;
} }
}; };