Skip to content

Commit

Permalink
Merge pull request #182 from Gawdl3y/clean/more-lints
Browse files Browse the repository at this point in the history
Implement & correct many lints
  • Loading branch information
Gawdl3y authored Jun 10, 2024
2 parents 4cb9e54 + 78b55f3 commit 8db0dbc
Show file tree
Hide file tree
Showing 18 changed files with 522 additions and 341 deletions.
1 change: 1 addition & 0 deletions clippy.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
allowed-duplicate-crates = ["bitflags", "redb"]
19 changes: 11 additions & 8 deletions crates/resolute/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,29 @@ use std::{io::ErrorKind, path::Path};

use log::{info, warn};
use native_db::{db_type::Error as NativeDbError, Database, DatabaseBuilder};
use redb::{DatabaseError, StorageError};

use crate::{mods::ResoluteMod, Error, Result};

/// Wrapper for interacting with a Resolute database
#[allow(missing_debug_implementations)]
pub struct ResoluteDatabase<'a> {
db: Database<'a>,
}

impl<'a> ResoluteDatabase<'a> {
/// Opens a database using a provided native_db builder
/// Opens a database using a provided builder.
/// If the database doesn't already exist at the given path, it will be created.
pub fn open(builder: &'a DatabaseBuilder, db_path: impl AsRef<Path>) -> Result<Self> {
info!("Opening database at {}", db_path.as_ref().display());

// Try to open an already-existing database
let db = match builder.open(&db_path) {
// If it fails because it doesn't exist, then go ahead and create one instead
Err(NativeDbError::Io(err))
| Err(NativeDbError::RedbDatabaseError(redb::DatabaseError::Storage(redb::StorageError::Io(err))))
if err.kind() == ErrorKind::NotFound =>
{
Err(
NativeDbError::Io(err)
| NativeDbError::RedbDatabaseError(DatabaseError::Storage(StorageError::Io(err))),
) if err.kind() == ErrorKind::NotFound => {
warn!("Database doesn't exist; creating");
builder.create(&db_path)?
}
Expand All @@ -34,7 +37,7 @@ impl<'a> ResoluteDatabase<'a> {
Ok(Self { db })
}

/// Defines the database models on a native_db builder
/// Defines the database models on a builder
pub fn define_models(builder: &mut DatabaseBuilder) -> Result<()> {
builder.define::<ResoluteMod>()?;
Ok(())
Expand Down Expand Up @@ -62,7 +65,7 @@ impl<'a> ResoluteDatabase<'a> {
/// Retrieves a single mod from the database by its ID
pub fn get_mod(&self, id: impl AsRef<str>) -> Result<Option<ResoluteMod>> {
let read = self.db.r_transaction()?;
let rmod = read.get().primary(id.as_ref().to_string())?;
let rmod = read.get().primary(id.as_ref().to_owned())?;
Ok(rmod)
}

Expand Down Expand Up @@ -94,7 +97,7 @@ impl<'a> ResoluteDatabase<'a> {
/// Removes a mod from the database by its ID
pub fn remove_mod_by_id(&self, id: impl AsRef<str>) -> Result<()> {
// Find the item in the database
let id = id.as_ref().to_string();
let id = id.as_ref().to_owned();
let read = self.db.r_transaction()?;
let rmod: ResoluteMod = read.get().primary(id.clone())?.ok_or_else(|| Error::ItemNotFound(id))?;

Expand Down
71 changes: 30 additions & 41 deletions crates/resolute/src/discover.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,14 @@ use crate::{
pub const RESONITE_APP: u32 = 2_519_830;

/// Searches for a potenial Resonite game directory
pub fn discover_resonite(steam: Option<SteamDir>) -> Result<Option<PathBuf>> {
pub fn resonite(steam: Option<SteamDir>) -> Result<Option<PathBuf>> {
// Find a Steam installation if one isn't provided
let steam = match steam {
Some(steam) => steam,
None => {
let steam = SteamDir::locate()?;
debug!("Steam installation located at {}", steam.path().display());
steam
}
let steam = if let Some(steam) = steam {
steam
} else {
let steam = SteamDir::locate()?;
debug!("Steam installation located at {}", steam.path().display());
steam
};

// Check the Steam installation for Resonite
Expand All @@ -41,14 +40,14 @@ pub fn discover_resonite(steam: Option<SteamDir>) -> Result<Option<PathBuf>> {
}

/// Searches for any installed mods in a Resonite directory by checksum then filename, including unrecognized mods
pub fn discover_mods(base_path: impl AsRef<Path>, mods: ResoluteModMap) -> Result<ResoluteModMap> {
let mut discovered = discover_mods_by_checksum(&base_path, &mods)?;
discovered.extend(discover_mods_by_filename(&base_path, &mods, Some(&discovered))?);
pub fn mods(base_path: impl AsRef<Path>, mods: &ResoluteModMap) -> Result<ResoluteModMap> {
let mut discovered = mods_by_checksum(&base_path, mods)?;
discovered.extend(mods_by_filename(&base_path, mods, Some(&discovered))?);
Ok(discovered)
}

/// Searches for any installed mods in a Resonite directory using artifact checksums
pub fn discover_mods_by_checksum(base_path: impl AsRef<Path>, mods: &ResoluteModMap) -> Result<ResoluteModMap> {
pub fn mods_by_checksum(base_path: impl AsRef<Path>, mods: &ResoluteModMap) -> Result<ResoluteModMap> {
let mut discovered = ResoluteModMap::new();
let mut checksums: HashMap<PathBuf, Option<String>> = HashMap::new();
let base_path = base_path.as_ref();
Expand Down Expand Up @@ -140,7 +139,7 @@ pub fn discover_mods_by_checksum(base_path: impl AsRef<Path>, mods: &ResoluteMod
}

/// Searches for any installed mods in a Resonite directory using artifact filenames
pub fn discover_mods_by_filename(
pub fn mods_by_filename(
base_path: impl AsRef<Path>,
mods: &ResoluteModMap,
already_discovered: Option<&ResoluteModMap>,
Expand Down Expand Up @@ -239,36 +238,26 @@ pub fn discover_mods_by_filename(

// Get a str representation of the filename
let filename = artifact_file.file_name();
let filename = match filename.to_str() {
Some(filename) => filename,
None => {
error!(
"Error converting artifact file name ({:?}) to string",
artifact_file.file_name()
);
continue;
}
let Some(filename) = filename.to_str() else {
error!("Error converting artifact file name ({:?}) to string", filename);
continue;
};

// Create an unrecognized mod
let rmod = match existing_rmod {
Some(rmod) => {
let version = ModVersion::new_unrecognized(filename, dirname, sha256);
let semver = version.semver.clone();

let mut rmod = rmod.clone();
rmod.versions.insert(semver.clone(), version);
rmod.installed_version = Some(semver.clone());

debug!("Created unrecognized version {} for existing mod {}", semver, rmod);
rmod
}

None => {
let rmod = ResoluteMod::new_unrecognized(filename, dirname, sha256);
debug!("Created unrecognized mod {}", rmod);
rmod
}
// Create an unrecognized mod or version
let rmod = if let Some(rmod) = existing_rmod {
let version = ModVersion::new_unrecognized(filename, dirname, sha256);
let semver = version.semver.clone();

let mut rmod = rmod.clone();
rmod.versions.insert(semver.clone(), version);
rmod.installed_version = Some(semver.clone());

debug!("Created unrecognized version {} for existing mod {}", semver, rmod);
rmod
} else {
let rmod = ResoluteMod::new_unrecognized(filename, dirname, sha256);
debug!("Created unrecognized mod {}", rmod);
rmod
};

discovered.insert(rmod.id.clone(), rmod);
Expand Down
15 changes: 11 additions & 4 deletions crates/resolute/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
use core::result;
use std::io;

#[cfg(feature = "db")]
use native_db::db_type;
use reqwest::StatusCode;
use semver::Version;
use tokio::task;

use crate::{
manager::artifacts::{ArtifactError, ArtifactErrorVec},
Expand All @@ -8,6 +14,7 @@ use crate::{

/// Error returned from a Downloader
#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum Error {
#[error("http connection failed: {0}")]
Request(#[from] reqwest::Error),
Expand All @@ -16,10 +23,10 @@ pub enum Error {
Http(StatusCode),

#[error("io error: {0}")]
Io(#[from] std::io::Error),
Io(#[from] io::Error),

#[error("task error: {0}")]
Task(#[from] tokio::task::JoinError),
Task(#[from] task::JoinError),

#[error("unable to process path: {0}")]
Path(String),
Expand Down Expand Up @@ -60,12 +67,12 @@ pub enum Error {

#[cfg(feature = "db")]
#[error("database error: {0}")]
Database(#[from] native_db::db_type::Error),
Database(#[from] db_type::Error),

#[cfg(feature = "db")]
#[error("item not found in database: {0}")]
ItemNotFound(String),
}

/// Alias for a `Result` with the error type `resolute::Error`.
pub type Result<T> = core::result::Result<T, Error>;
pub type Result<T> = result::Result<T, Error>;
73 changes: 73 additions & 0 deletions crates/resolute/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,76 @@
#![deny(macro_use_extern_crate, meta_variable_misuse, unit_bindings)]
#![warn(
explicit_outlives_requirements,
// missing_docs,
missing_debug_implementations,
single_use_lifetimes,
trivial_casts,
trivial_numeric_casts,
unreachable_pub,
unused_crate_dependencies,
unused_import_braces,
unused_lifetimes,
unused_qualifications,
variant_size_differences,
clippy::pedantic,
clippy::absolute_paths,
clippy::arithmetic_side_effects,
clippy::clone_on_ref_ptr,
clippy::cognitive_complexity,
clippy::create_dir,
clippy::dbg_macro,
clippy::empty_enum_variants_with_brackets,
clippy::empty_structs_with_brackets,
clippy::exhaustive_enums,
clippy::exhaustive_structs,
clippy::filetype_is_file,
clippy::float_cmp_const,
clippy::missing_const_for_fn,
clippy::fn_to_numeric_cast_any,
clippy::format_push_string,
clippy::get_unwrap,
clippy::if_then_some_else_none,
clippy::infinite_loop,
clippy::integer_division,
clippy::lossy_float_literal,
clippy::map_err_ignore,
// clippy::missing_docs_in_private_items,
clippy::mixed_read_write_in_expression,
clippy::multiple_crate_versions,
clippy::multiple_inherent_impl,
clippy::mutex_atomic,
clippy::negative_feature_names,
clippy::panic_in_result_fn,
clippy::print_stderr,
clippy::print_stdout,
clippy::pub_without_shorthand,
clippy::rc_buffer,
clippy::rc_mutex,
clippy::redundant_feature_names,
clippy::redundant_type_annotations,
clippy::ref_patterns,
clippy::rest_pat_in_fully_bound_structs,
clippy::same_name_method,
clippy::self_named_module_files,
clippy::semicolon_inside_block,
clippy::str_to_string,
clippy::string_lit_chars_any,
clippy::string_to_string,
clippy::suspicious_xor_used_as_pow,
clippy::tests_outside_test_module,
clippy::try_err,
clippy::undocumented_unsafe_blocks,
clippy::unnecessary_safety_comment,
clippy::unnecessary_safety_doc,
clippy::unnecessary_self_imports,
clippy::unneeded_field_pattern,
clippy::unwrap_in_result,
clippy::unwrap_used,
clippy::verbose_file_reads,
clippy::wildcard_dependencies,
)]
#![allow(clippy::missing_errors_doc, clippy::missing_panics_doc)]

#[cfg(feature = "db")]
pub mod db;
pub mod discover;
Expand Down
Loading

0 comments on commit 8db0dbc

Please sign in to comment.