Skip to content

Commit

Permalink
Make clippy pedantic happy (#1277)
Browse files Browse the repository at this point in the history
Signed-off-by: Sergio Castaño Arteaga <[email protected]>
  • Loading branch information
tegioz authored Sep 26, 2023
1 parent 29ddf6a commit 38d38e7
Show file tree
Hide file tree
Showing 40 changed files with 156 additions and 78 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
[workspace]
resolver = "2"
members = [
"clomonitor-apiserver",
"clomonitor-archiver",
Expand Down
1 change: 1 addition & 0 deletions clomonitor-apiserver/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ type Count = i64;

/// Trait that defines some operations a DB implementation must support.
#[async_trait]
#[allow(clippy::ref_option_ref)]
#[cfg_attr(test, automock)]
pub(crate) trait DB {
/// Get project's data in json format.
Expand Down
21 changes: 18 additions & 3 deletions clomonitor-apiserver/src/filters.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
/// Template filter that returns the rating letter corresponding to the score
/// value provided.
#[allow(clippy::unnecessary_wraps, clippy::trivially_copy_pass_by_ref)]
pub(crate) fn rating(score: &f64) -> askama::Result<char> {
Ok(clomonitor_core::score::rating(*score))
}

/// Template filter that returns the rating letter corresponding to the score
/// value provided.
#[allow(clippy::unnecessary_wraps)]
pub(crate) fn rating_opt(score: &Option<f64>) -> askama::Result<String> {
Ok(match score {
Some(v) => clomonitor_core::score::rating(*v).to_string(),
Expand All @@ -15,11 +17,18 @@ pub(crate) fn rating_opt(score: &Option<f64>) -> askama::Result<String> {

/// Template filter that rounds the f64 value provided and returns its integer
/// part.
#[allow(
clippy::unnecessary_wraps,
clippy::trivially_copy_pass_by_ref,
clippy::cast_possible_truncation,
clippy::cast_sign_loss
)]
pub(crate) fn round(v: &f64) -> askama::Result<usize> {
Ok(v.round() as usize)
}

/// Template filter that returns the width of the section score bar.
#[allow(clippy::unnecessary_wraps)]
pub(crate) fn rs_section_score_width(score: &Option<f64>) -> askama::Result<f64> {
Ok(match score {
Some(v) => {
Expand All @@ -35,12 +44,18 @@ pub(crate) fn rs_section_score_width(score: &Option<f64>) -> askama::Result<f64>
}

/// Template filter that return the stroke-dasharray for the global score.
#[allow(clippy::unnecessary_wraps, clippy::trivially_copy_pass_by_ref)]
pub(crate) fn stroke(v: &f64) -> askama::Result<f64> {
Ok(251.42 + (251.42 * v / 100.0))
}

/// Template filter that returns the integer part of the rounded score value
/// provided as a string. "n/a" is returned when the value is none.
#[allow(
clippy::unnecessary_wraps,
clippy::cast_sign_loss,
clippy::cast_possible_truncation
)]
pub(crate) fn to_string(score: &Option<f64>) -> askama::Result<String> {
Ok(match score {
Some(v) => (v.round() as usize).to_string(),
Expand Down Expand Up @@ -76,13 +91,13 @@ mod tests {

#[test]
fn rs_section_score_width_some() {
assert_eq!(rs_section_score_width(&Some(1.0)).unwrap(), 2.0);
assert_eq!(rs_section_score_width(&Some(80.0)).unwrap(), 85.0);
assert!((rs_section_score_width(&Some(1.0)).unwrap() - 2.0).abs() < f64::EPSILON);
assert!((rs_section_score_width(&Some(80.0)).unwrap() - 85.0).abs() < f64::EPSILON);
}

#[test]
fn rs_section_score_width_none() {
assert_eq!(rs_section_score_width(&None).unwrap(), 0.0);
assert!((rs_section_score_width(&None).unwrap() - 0.0).abs() < f64::EPSILON);
}

#[test]
Expand Down
34 changes: 17 additions & 17 deletions clomonitor-apiserver/src/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,21 +74,18 @@ pub(crate) async fn badge(
// Prepare badge configuration
let message: String;
let color: &str;
match rating {
Some(rating) => {
message = rating.to_uppercase();
color = match rating.as_ref() {
"a" => "green",
"b" => "yellow",
"c" => "orange",
"d" => "red",
_ => "grey",
};
}
None => {
message = "not processed yet".to_owned();
color = "grey";
}
if let Some(rating) = rating {
message = rating.to_uppercase();
color = match rating.as_ref() {
"a" => "green",
"b" => "yellow",
"c" => "orange",
"d" => "red",
_ => "grey",
};
} else {
message = "not processed yet".to_owned();
color = "grey";
}

// Return badge configuration as json
Expand All @@ -110,6 +107,7 @@ pub(crate) async fn badge(
}

/// Handler that returns the index HTML document with some metadata embedded.
#[allow(clippy::unused_async)]
pub(crate) async fn index(
State(cfg): State<Arc<Config>>,
State(tmpl): State<Arc<Tera>>,
Expand Down Expand Up @@ -138,6 +136,7 @@ pub(crate) async fn index(

/// Handler that returns the index HTML document with some project specific
/// metadata embedded.
#[allow(clippy::unused_async)]
pub(crate) async fn index_project(
State(cfg): State<Arc<Config>>,
State(tmpl): State<Arc<Tera>>,
Expand Down Expand Up @@ -375,7 +374,7 @@ pub(crate) async fn stats(
) -> impl IntoResponse {
// Get stats from database
let stats = db
.stats(params.get("foundation").map(|p| p.as_str()))
.stats(params.get("foundation").map(String::as_str))
.await
.map_err(internal_error)?;

Expand All @@ -394,7 +393,7 @@ pub(crate) async fn stats_snapshot(
Query(params): Query<HashMap<String, String>>,
) -> impl IntoResponse {
// Get stats snapshot from database
let foundation = params.get("foundation").map(|f| f.as_str());
let foundation = params.get("foundation").map(String::as_str);
let date: Date =
Date::parse(&date, &SNAPSHOT_DATE_FORMAT).map_err(|_| StatusCode::BAD_REQUEST)?;
let stats = db
Expand Down Expand Up @@ -427,6 +426,7 @@ pub(crate) async fn track_view(
}

/// Helper for mapping any error into a `500 Internal Server Error` response.
#[allow(clippy::needless_pass_by_value)]
fn internal_error<E>(err: E) -> StatusCode
where
E: Into<Error> + Display,
Expand Down
7 changes: 5 additions & 2 deletions clomonitor-apiserver/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
#![warn(clippy::all, clippy::pedantic)]
#![allow(clippy::doc_markdown, clippy::wildcard_imports)]

use crate::{db::PgDB, views::ViewsTrackerDB};
use anyhow::{Context, Result};
use clap::Parser;
Expand Down Expand Up @@ -43,7 +46,7 @@ async fn main() -> Result<()> {

// Setup logging
if std::env::var_os("RUST_LOG").is_none() {
std::env::set_var("RUST_LOG", "clomonitor_apiserver=debug,tower_http=debug")
std::env::set_var("RUST_LOG", "clomonitor_apiserver=debug,tower_http=debug");
}
let s = tracing_subscriber::fmt().with_env_filter(EnvFilter::from_default_env());
match cfg.get_string("log.format").as_deref() {
Expand Down Expand Up @@ -76,7 +79,7 @@ async fn main() -> Result<()> {

// Setup and launch API HTTP server
debug!("setting up apiserver");
let router = router::setup(cfg.clone(), db, vt.clone())?;
let router = router::setup(&cfg, db, vt.clone())?;
let addr: SocketAddr = cfg.get_string("apiserver.addr")?.parse()?;
info!("apiserver started");
info!(%addr, "listening");
Expand Down
6 changes: 3 additions & 3 deletions clomonitor-apiserver/src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ struct RouterState {
}

/// Setup API server router.
pub(crate) fn setup(cfg: Arc<Config>, db: DynDB, vt: DynVT) -> Result<Router> {
pub(crate) fn setup(cfg: &Arc<Config>, db: DynDB, vt: DynVT) -> Result<Router> {
// Setup some paths
let static_path = cfg.get_string("apiserver.staticPath")?;
let index_path = Path::new(&static_path).join("index.html");
Expand Down Expand Up @@ -596,7 +596,7 @@ mod tests {
url: "https://github.com/artifacthub/hub".to_string(),
check_sets: vec![CheckSet::Code],
score: Some(Score {
global: 99.99999999999999,
global: 99.999_999_999_999_99,
global_weight: 95,
documentation: Some(100.0),
documentation_weight: Some(30),
Expand Down Expand Up @@ -938,7 +938,7 @@ mod tests {

fn setup_test_router(db: MockDB, vt: MockViewsTracker) -> Router {
let cfg = setup_test_config();
setup(Arc::new(cfg), Arc::new(db), Arc::new(RwLock::new(vt))).unwrap()
setup(&Arc::new(cfg), Arc::new(db), Arc::new(RwLock::new(vt))).unwrap()
}

fn setup_test_config() -> Config {
Expand Down
13 changes: 7 additions & 6 deletions clomonitor-archiver/src/archiver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ pub(crate) async fn run(db: DynDB) -> Result<()> {
info!("started");

debug!("processing projects");
for project_id in db.projects_ids().await?.iter() {
for project_id in &db.projects_ids().await? {
process_project(db.clone(), project_id).await?;
}

debug!("processing stats");
for foundation in db.foundations().await?.iter() {
for foundation in &db.foundations().await? {
process_stats(db.clone(), Some(foundation)).await?;
}
process_stats(db.clone(), None).await?; // All foundations
Expand All @@ -34,7 +34,7 @@ async fn process_project(db: DynDB, project_id: &Uuid) -> Result<()> {
.project_snapshots(project_id)
.await
.context("error getting snapshots")?;
let latest_snapshot_date = snapshots.first().map(|d| d.to_owned());
let latest_snapshot_date = snapshots.first().map(ToOwned::to_owned);

// Store new project's snapshot if needed
let today = OffsetDateTime::now_utc().date();
Expand All @@ -53,7 +53,7 @@ async fn process_project(db: DynDB, project_id: &Uuid) -> Result<()> {

// Delete snapshots no longer needed
let snapshots_to_keep = get_snapshots_to_keep(today, snapshots.as_slice());
for snapshot in snapshots.iter() {
for snapshot in &snapshots {
if !snapshots_to_keep.contains(snapshot) {
db.delete_project_snapshot(project_id, snapshot)
.await
Expand All @@ -74,7 +74,7 @@ async fn process_stats(db: DynDB, foundation: Option<&str>) -> Result<()> {
.stats_snapshots(foundation)
.await
.context("error getting snapshots")?;
let latest_snapshot_date = snapshots.first().map(|d| d.to_owned());
let latest_snapshot_date = snapshots.first().map(ToOwned::to_owned);

// Store new stats snapshot if needed
let today = OffsetDateTime::now_utc().date();
Expand All @@ -93,7 +93,7 @@ async fn process_stats(db: DynDB, foundation: Option<&str>) -> Result<()> {

// Delete snapshots no longer needed
let snapshots_to_keep = get_snapshots_to_keep(today, snapshots.as_slice());
for snapshot in snapshots.iter() {
for snapshot in &snapshots {
if !snapshots_to_keep.contains(snapshot) {
db.delete_stats_snapshot(foundation, snapshot)
.await
Expand Down Expand Up @@ -148,6 +148,7 @@ fn get_snapshots_to_keep(ref_date: Date, snapshots: &[Date]) -> Vec<Date> {
}

#[cfg(test)]
#[allow(clippy::redundant_closure_for_method_calls)]
mod tests {
use super::*;
use crate::db::MockDB;
Expand Down
1 change: 1 addition & 0 deletions clomonitor-archiver/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub(crate) type DynDB = Arc<dyn DB + Send + Sync>;

/// Trait that defines some operations a DB implementation must support.
#[async_trait]
#[allow(clippy::ref_option_ref)]
#[cfg_attr(test, automock)]
pub(crate) trait DB {
/// Delete the provided project's snapshot.
Expand Down
5 changes: 4 additions & 1 deletion clomonitor-archiver/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
#![warn(clippy::all, clippy::pedantic)]
#![allow(clippy::doc_markdown)]

use crate::db::PgDB;
use anyhow::{Context, Result};
use clap::Parser;
Expand Down Expand Up @@ -32,7 +35,7 @@ async fn main() -> Result<()> {

// Setup logging
if std::env::var_os("RUST_LOG").is_none() {
std::env::set_var("RUST_LOG", "clomonitor_archiver=debug")
std::env::set_var("RUST_LOG", "clomonitor_archiver=debug");
}
let s = tracing_subscriber::fmt().with_env_filter(EnvFilter::from_default_env());
match cfg.get_string("log.format").as_deref() {
Expand Down
10 changes: 10 additions & 0 deletions clomonitor-core/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,12 @@
#![warn(clippy::all, clippy::pedantic)]
#![allow(clippy::doc_markdown, clippy::wildcard_imports)]

#[allow(clippy::module_name_repetitions)]
pub mod linter;

#[allow(
clippy::cast_precision_loss,
clippy::cast_possible_truncation,
clippy::cast_sign_loss
)]
pub mod score;
9 changes: 9 additions & 0 deletions clomonitor-core/src/linter/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ pub struct CheckOutput<T = ()> {

impl<T> CheckOutput<T> {
/// Create a new CheckOutput instance with the passed field set to true.
#[must_use]
pub fn passed() -> Self {
Self {
passed: true,
Expand All @@ -104,6 +105,7 @@ impl<T> CheckOutput<T> {
}

/// Create a new CheckOutput instance with the passed field set to false.
#[must_use]
pub fn not_passed() -> Self {
Self {
passed: false,
Expand All @@ -112,6 +114,7 @@ impl<T> CheckOutput<T> {
}

/// Create a new CheckOutput instance with the exempt field set to true.
#[must_use]
pub fn exempt() -> Self {
Self {
exempt: true,
Expand All @@ -120,6 +123,7 @@ impl<T> CheckOutput<T> {
}

/// Create a new CheckOutput instance with the failed field set to true.
#[must_use]
pub fn failed() -> Self {
Self {
failed: true,
Expand All @@ -128,30 +132,35 @@ impl<T> CheckOutput<T> {
}

/// Url field setter.
#[must_use]
pub fn url(mut self, url: Option<String>) -> CheckOutput<T> {
self.url = url;
self
}

/// Value field setter.
#[must_use]
pub fn value(mut self, value: Option<T>) -> CheckOutput<T> {
self.value = value;
self
}

/// Details field setter.
#[must_use]
pub fn details(mut self, details: Option<String>) -> CheckOutput<T> {
self.details = details;
self
}

/// Exemption reason field setter.
#[must_use]
pub fn exemption_reason(mut self, reason: Option<String>) -> CheckOutput<T> {
self.exemption_reason = reason;
self
}

/// Fail reason field setter.
#[must_use]
pub fn fail_reason(mut self, reason: Option<String>) -> CheckOutput<T> {
self.fail_reason = reason;
self
Expand Down
6 changes: 3 additions & 3 deletions clomonitor-core/src/linter/checks/analytics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,19 +47,19 @@ pub(crate) async fn check(input: &CheckInput<'_>) -> Result<CheckOutput<Vec<Stri
// Check Google Analytics 3 (Universal Analytics) tracking ID
if GA3.is_match(&content) {
analytics_detected.push("GA3".to_string());
details.push_str("· Google Analytics 3 (Universal Analytics)\n")
details.push_str("· Google Analytics 3 (Universal Analytics)\n");
}

// Check Google Analytics 4 measurement ID
if GA4.is_match(&content) {
analytics_detected.push("GA4".to_string());
details.push_str("· Google Analytics 4\n")
details.push_str("· Google Analytics 4\n");
}

// Check HubSpot tracking code
if HUBSPOT.is_match(&content) {
analytics_detected.push("HubSpot".to_string());
details.push_str("· HubSpot\n")
details.push_str("· HubSpot\n");
}

// Return check output
Expand Down
Loading

0 comments on commit 38d38e7

Please sign in to comment.