From ddbc1a8d4d3f1c88b85216ef19c02f67f2a2a040 Mon Sep 17 00:00:00 2001 From: Jose Quesada Date: Thu, 2 Nov 2023 13:18:18 -0600 Subject: [PATCH 1/4] added `rustfmt.toml` --- rustfmt.toml | 1 + 1 file changed, 1 insertion(+) create mode 100644 rustfmt.toml diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 000000000..df99c6919 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1 @@ +max_width = 80 From 06e7919035441e36786f71758272130205bbbba1 Mon Sep 17 00:00:00 2001 From: Jose Quesada Date: Thu, 2 Nov 2023 13:20:42 -0600 Subject: [PATCH 2/4] run `cargo fmt` --- crates/carbon_app/build.rs | 9 +- crates/carbon_app/src/api/account.rs | 3 +- crates/carbon_app/src/api/instance/mod.rs | 12 +- crates/carbon_app/src/api/java/managed.rs | 36 +- crates/carbon_app/src/api/java/mod.rs | 31 +- crates/carbon_app/src/api/mc.rs | 6 +- crates/carbon_app/src/api/metrics.rs | 4 +- .../api/modplatforms/curseforge/filters.rs | 47 ++- .../api/modplatforms/curseforge/responses.rs | 4 +- .../api/modplatforms/curseforge/structs.rs | 143 ++++++-- .../src/api/modplatforms/filters.rs | 154 ++++++-- crates/carbon_app/src/api/modplatforms/mod.rs | 16 +- .../src/api/modplatforms/modrinth/filters.rs | 30 +- .../api/modplatforms/modrinth/responses.rs | 12 +- .../src/api/modplatforms/modrinth/structs.rs | 60 ++- .../src/api/modplatforms/responses.rs | 20 +- crates/carbon_app/src/api/settings.rs | 7 +- crates/carbon_app/src/api/vtask.rs | 8 +- crates/carbon_app/src/cache_middleware.rs | 67 +++- crates/carbon_app/src/domain/java.rs | 50 ++- .../src/domain/minecraft/minecraft.rs | 30 +- .../modplatforms/curseforge/manifest.rs | 4 +- .../domain/modplatforms/modrinth/search.rs | 20 +- .../domain/modplatforms/modrinth/version.rs | 6 +- crates/carbon_app/src/domain/runtime_path.rs | 18 +- crates/carbon_app/src/domain/url.rs | 3 +- crates/carbon_app/src/error/json.rs | 40 +- crates/carbon_app/src/error/mod.rs | 6 +- crates/carbon_app/src/error/request.rs | 40 +- crates/carbon_app/src/error/sentry.rs | 8 +- crates/carbon_app/src/logger.rs | 12 +- crates/carbon_app/src/main.rs | 12 +- crates/carbon_app/src/managers/account/api.rs | 32 +- .../carbon_app/src/managers/account/enroll.rs | 16 +- crates/carbon_app/src/managers/account/mod.rs | 107 ++++-- .../carbon_app/src/managers/account/skin.rs | 50 ++- crates/carbon_app/src/managers/download.rs | 100 +++-- .../instance/importer/curseforge_archive.rs | 61 ++-- .../instance/importer/legacy_gdlauncher.rs | 74 ++-- .../src/managers/instance/importer/mod.rs | 65 +++- .../instance/importer/modrinth_archive.rs | 56 ++- .../src/managers/instance/installer/mod.rs | 171 ++++++--- .../carbon_app/src/managers/instance/log.rs | 5 +- .../carbon_app/src/managers/instance/mod.rs | 341 ++++++++++++------ .../carbon_app/src/managers/instance/mods.rs | 97 +++-- .../carbon_app/src/managers/instance/run.rs | 73 ++-- .../src/managers/instance/schema/mod.rs | 8 +- .../src/managers/java/discovery/finder.rs | 35 +- .../src/managers/java/java_checker.rs | 7 +- .../src/managers/java/managed/azul_zulu.rs | 34 +- .../src/managers/java/managed/mod.rs | 20 +- crates/carbon_app/src/managers/java/mod.rs | 83 +++-- crates/carbon_app/src/managers/java/parser.rs | 11 +- .../src/managers/java/scan_and_sync.rs | 99 +++-- .../src/managers/metadata/cache/curseforge.rs | 80 ++-- .../src/managers/metadata/cache/mod.rs | 237 +++++++----- .../src/managers/metadata/cache/modrinth.rs | 63 ++-- .../carbon_app/src/managers/metadata/mods.rs | 49 ++- .../src/managers/minecraft/assets.rs | 50 ++- .../src/managers/minecraft/curseforge.rs | 46 ++- .../src/managers/minecraft/fabric.rs | 6 +- .../src/managers/minecraft/forge.rs | 54 ++- .../src/managers/minecraft/minecraft.rs | 175 +++++---- .../carbon_app/src/managers/minecraft/mod.rs | 61 +++- .../src/managers/minecraft/modrinth.rs | 41 ++- .../src/managers/minecraft/quilt.rs | 6 +- crates/carbon_app/src/managers/mod.rs | 38 +- .../src/managers/modplatforms/curseforge.rs | 30 +- .../src/managers/modplatforms/mod.rs | 10 +- .../src/managers/modplatforms/modrinth.rs | 63 +++- .../carbon_app/src/managers/prisma_client.rs | 8 +- .../carbon_app/src/managers/settings/mod.rs | 46 ++- .../managers/settings/terms_and_privacy.rs | 6 +- crates/carbon_app/src/managers/vtask.rs | 33 +- .../carbon_app/src/runtime_path_override.rs | 5 +- crates/carbon_compression/src/lib.rs | 22 +- crates/carbon_macro/src/lib.rs | 5 +- crates/carbon_net/src/lib.rs | 6 +- 78 files changed, 2488 insertions(+), 1115 deletions(-) diff --git a/crates/carbon_app/build.rs b/crates/carbon_app/build.rs index 903e59779..d5ebf9d49 100644 --- a/crates/carbon_app/build.rs +++ b/crates/carbon_app/build.rs @@ -15,10 +15,13 @@ fn main() { .args(["log", "-1", "--format=%ct"]) .output() .unwrap(); - let git_commit_author_date = String::from_utf8(git_commit_author_date.stdout).unwrap(); + let git_commit_author_date = + String::from_utf8(git_commit_author_date.stdout).unwrap(); - let version_json = std::fs::read_to_string("../../packages/config/version.json").unwrap(); - let version_json: serde_json::Value = serde_json::from_str(&version_json).unwrap(); + let version_json = + std::fs::read_to_string("../../packages/config/version.json").unwrap(); + let version_json: serde_json::Value = + serde_json::from_str(&version_json).unwrap(); let version = version_json["version"].as_str().unwrap(); let channel = version_json["channel"] diff --git a/crates/carbon_app/src/api/account.rs b/crates/carbon_app/src/api/account.rs index 28b4cf4ce..d7b38a2ef 100644 --- a/crates/carbon_app/src/api/account.rs +++ b/crates/carbon_app/src/api/account.rs @@ -79,7 +79,8 @@ pub(super) fn mount_axum_router() -> axum::Router> { axum::Router::new().route( "/headImage", axum::routing::get( - |State(app): State>, Query(query): Query| async move { + |State(app): State>, + Query(query): Query| async move { app.account_manager() .skin_manager() .make_head(query.uuid) diff --git a/crates/carbon_app/src/api/instance/mod.rs b/crates/carbon_app/src/api/instance/mod.rs index 9f57ffe68..56b6803cb 100644 --- a/crates/carbon_app/src/api/instance/mod.rs +++ b/crates/carbon_app/src/api/instance/mod.rs @@ -981,8 +981,12 @@ impl From for ListInstance { impl From for ListInstanceStatus { fn from(value: manager::ListInstanceStatus) -> Self { match value { - manager::ListInstanceStatus::Valid(status) => Self::Valid(status.into()), - manager::ListInstanceStatus::Invalid(status) => Self::Invalid(status.into()), + manager::ListInstanceStatus::Valid(status) => { + Self::Valid(status.into()) + } + manager::ListInstanceStatus::Invalid(status) => { + Self::Invalid(status.into()) + } } } } @@ -1021,7 +1025,9 @@ impl From for ConfigurationParseError { } } -impl From for ConfigurationParseErrorType { +impl From + for ConfigurationParseErrorType +{ fn from(value: manager::ConfigurationParseErrorType) -> Self { use manager::ConfigurationParseErrorType as manager; diff --git a/crates/carbon_app/src/api/java/managed.rs b/crates/carbon_app/src/api/java/managed.rs index 05ef57c68..fb9693eac 100644 --- a/crates/carbon_app/src/api/java/managed.rs +++ b/crates/carbon_app/src/api/java/managed.rs @@ -98,7 +98,9 @@ pub struct FEManagedJavaVersion { java_version: String, } -impl From for FEManagedJavaVersion { +impl From + for FEManagedJavaVersion +{ fn from(v: crate::managers::java::managed::ManagedJavaVersion) -> Self { Self { id: v.id, @@ -109,7 +111,9 @@ impl From for FEManagedJavaV } } -impl TryFrom for crate::managers::java::managed::ManagedJavaVersion { +impl TryFrom + for crate::managers::java::managed::ManagedJavaVersion +{ type Error = anyhow::Error; fn try_from(v: FEManagedJavaVersion) -> Result { @@ -124,7 +128,9 @@ impl TryFrom for crate::managers::java::managed::ManagedJa #[derive(Type, Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct FEManagedJavaArchMap(pub HashMap>); +pub struct FEManagedJavaArchMap( + pub HashMap>, +); impl Deref for FEManagedJavaArchMap { type Target = HashMap>; @@ -134,11 +140,15 @@ impl Deref for FEManagedJavaArchMap { } } -impl From for FEManagedJavaArchMap { +impl From + for FEManagedJavaArchMap +{ fn from(v: crate::managers::java::managed::ManagedJavaArchMap) -> Self { Self( v.0.into_iter() - .map(|(k, v)| (k.into(), v.into_iter().map(|v| v.into()).collect())) + .map(|(k, v)| { + (k.into(), v.into_iter().map(|v| v.into()).collect()) + }) .collect(), ) } @@ -146,7 +156,9 @@ impl From for FEManagedJavaA #[derive(Type, Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct FEManagedJavaOsMap(pub HashMap); +pub struct FEManagedJavaOsMap( + pub HashMap, +); impl Deref for FEManagedJavaOsMap { type Target = HashMap; @@ -156,7 +168,9 @@ impl Deref for FEManagedJavaOsMap { } } -impl From for FEManagedJavaOsMap { +impl From + for FEManagedJavaOsMap +{ fn from(v: crate::managers::java::managed::ManagedJavaOsMap) -> Self { Self(v.0.into_iter().map(|(k, v)| (k.into(), v.into())).collect()) } @@ -186,8 +200,12 @@ impl From for FEManagedJavaSetupProgress { match v { Step::Idle => Self::Idle, - Step::Downloading(a, b) => Self::Downloading(a.to_string(), b.to_string()), - Step::Extracting(a, b) => Self::Extracting(a.to_string(), b.to_string()), + Step::Downloading(a, b) => { + Self::Downloading(a.to_string(), b.to_string()) + } + Step::Extracting(a, b) => { + Self::Extracting(a.to_string(), b.to_string()) + } Step::Done => Self::Done, } } diff --git a/crates/carbon_app/src/api/java/mod.rs b/crates/carbon_app/src/api/java/mod.rs index a60e7d5c3..ce2de46d1 100644 --- a/crates/carbon_app/src/api/java/mod.rs +++ b/crates/carbon_app/src/api/java/mod.rs @@ -1,4 +1,6 @@ -use crate::api::java::managed::{FEManagedJavaSetupArgs, FEManagedJavaSetupProgress}; +use crate::api::java::managed::{ + FEManagedJavaSetupArgs, FEManagedJavaSetupProgress, +}; use crate::api::managers::App; use crate::api::router::router; use crate::domain::java::{JavaComponentType, JavaVendor}; @@ -7,7 +9,9 @@ use rspc::{RouterBuilderLike, Type}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; -use self::managed::{FEManagedJavaArch, FEManagedJavaOs, FEManagedJavaOsMap, FEVendor}; +use self::managed::{ + FEManagedJavaArch, FEManagedJavaOs, FEManagedJavaOsMap, FEVendor, +}; mod managed; @@ -78,7 +82,10 @@ fn get_managed_os(app: App, _args: ()) -> anyhow::Result> { Ok(all_os.into_iter().map(FEManagedJavaOs::from).collect()) } -fn get_managed_arch(app: App, _args: ()) -> anyhow::Result> { +fn get_managed_arch( + app: App, + _args: (), +) -> anyhow::Result> { let all_arch = app.java_manager().managed_service.get_all_archs(); Ok(all_arch.into_iter().map(FEManagedJavaArch::from).collect()) @@ -103,7 +110,10 @@ async fn get_managed_versions_by_vendor( Ok(managed_java_map_os.into()) } -async fn setup_managed_java(app: App, args: FEManagedJavaSetupArgs) -> anyhow::Result { +async fn setup_managed_java( + app: App, + args: FEManagedJavaSetupArgs, +) -> anyhow::Result { app.java_manager() .managed_service .setup_managed( @@ -132,7 +142,10 @@ async fn get_setup_managed_java_progress( Ok(res.into()) } -async fn get_system_java_profiles(app: App, _args: ()) -> anyhow::Result> { +async fn get_system_java_profiles( + app: App, + _args: (), +) -> anyhow::Result> { let profiles = app.java_manager().get_system_java_profiles().await?; Ok(profiles @@ -224,7 +237,9 @@ pub enum FESystemJavaProfileName { MinecraftJavaExe, } -impl From for FESystemJavaProfileName { +impl From + for FESystemJavaProfileName +{ fn from(name: crate::domain::java::SystemJavaProfileName) -> Self { use crate::domain::java::SystemJavaProfileName; match name { @@ -238,7 +253,9 @@ impl From for FESystemJavaProfileNam } } -impl From for crate::domain::java::SystemJavaProfileName { +impl From + for crate::domain::java::SystemJavaProfileName +{ fn from(name: FESystemJavaProfileName) -> Self { match name { FESystemJavaProfileName::Legacy => Self::Legacy, diff --git a/crates/carbon_app/src/api/mc.rs b/crates/carbon_app/src/api/mc.rs index 512020353..dafc97eca 100644 --- a/crates/carbon_app/src/api/mc.rs +++ b/crates/carbon_app/src/api/mc.rs @@ -43,7 +43,11 @@ pub struct FEModdedManifest { impl From for FEModdedManifest { fn from(value: modded::Manifest) -> Self { FEModdedManifest { - game_versions: value.game_versions.into_iter().map(|v| v.into()).collect(), + game_versions: value + .game_versions + .into_iter() + .map(|v| v.into()) + .collect(), } } } diff --git a/crates/carbon_app/src/api/metrics.rs b/crates/carbon_app/src/api/metrics.rs index 0093af2c4..114ef269c 100644 --- a/crates/carbon_app/src/api/metrics.rs +++ b/crates/carbon_app/src/api/metrics.rs @@ -33,7 +33,9 @@ impl From for crate::domain::metrics::Event { fn from(event: FEEvent) -> Self { Self { name: match event.name { - FEEventName::AppClosed => crate::domain::metrics::EventName::AppClosed, + FEEventName::AppClosed => { + crate::domain::metrics::EventName::AppClosed + } }, properties: event.properties, } diff --git a/crates/carbon_app/src/api/modplatforms/curseforge/filters.rs b/crates/carbon_app/src/api/modplatforms/curseforge/filters.rs index 796fe262e..4bd12603a 100644 --- a/crates/carbon_app/src/api/modplatforms/curseforge/filters.rs +++ b/crates/carbon_app/src/api/modplatforms/curseforge/filters.rs @@ -2,9 +2,10 @@ use rspc::Type; use serde::{Deserialize, Serialize}; use crate::domain::modplatforms::curseforge::filters::{ - FilesParameters, FilesParametersBody, ModDescriptionParameters, ModFileChangelogParameters, - ModFileParameters, ModFilesParameters, ModFilesParametersQuery, ModParameters, - ModSearchParameters, ModSearchParametersQuery, ModSearchSortField, ModSearchSortOrder, + FilesParameters, FilesParametersBody, ModDescriptionParameters, + ModFileChangelogParameters, ModFileParameters, ModFilesParameters, + ModFilesParametersQuery, ModParameters, ModSearchParameters, + ModSearchParametersQuery, ModSearchSortField, ModSearchSortOrder, ModsParameters, ModsParametersBody, }; @@ -27,13 +28,21 @@ impl From for ModSearchSortField { fn from(field: CFFEModSearchSortField) -> Self { match field { CFFEModSearchSortField::Featured => ModSearchSortField::Featured, - CFFEModSearchSortField::Popularity => ModSearchSortField::Popularity, - CFFEModSearchSortField::LastUpdated => ModSearchSortField::LastUpdated, + CFFEModSearchSortField::Popularity => { + ModSearchSortField::Popularity + } + CFFEModSearchSortField::LastUpdated => { + ModSearchSortField::LastUpdated + } CFFEModSearchSortField::Name => ModSearchSortField::Name, CFFEModSearchSortField::Author => ModSearchSortField::Author, - CFFEModSearchSortField::TotalDownloads => ModSearchSortField::TotalDownloads, + CFFEModSearchSortField::TotalDownloads => { + ModSearchSortField::TotalDownloads + } CFFEModSearchSortField::Category => ModSearchSortField::Category, - CFFEModSearchSortField::GameVersion => ModSearchSortField::GameVersion, + CFFEModSearchSortField::GameVersion => { + ModSearchSortField::GameVersion + } } } } @@ -42,13 +51,21 @@ impl From for CFFEModSearchSortField { fn from(field: ModSearchSortField) -> Self { match field { ModSearchSortField::Featured => CFFEModSearchSortField::Featured, - ModSearchSortField::Popularity => CFFEModSearchSortField::Popularity, - ModSearchSortField::LastUpdated => CFFEModSearchSortField::LastUpdated, + ModSearchSortField::Popularity => { + CFFEModSearchSortField::Popularity + } + ModSearchSortField::LastUpdated => { + CFFEModSearchSortField::LastUpdated + } ModSearchSortField::Name => CFFEModSearchSortField::Name, ModSearchSortField::Author => CFFEModSearchSortField::Author, - ModSearchSortField::TotalDownloads => CFFEModSearchSortField::TotalDownloads, + ModSearchSortField::TotalDownloads => { + CFFEModSearchSortField::TotalDownloads + } ModSearchSortField::Category => CFFEModSearchSortField::Category, - ModSearchSortField::GameVersion => CFFEModSearchSortField::GameVersion, + ModSearchSortField::GameVersion => { + CFFEModSearchSortField::GameVersion + } } } } @@ -64,7 +81,9 @@ impl From for ModSearchSortOrder { fn from(order: CFFEModSearchSortOrder) -> Self { match order { CFFEModSearchSortOrder::Ascending => ModSearchSortOrder::Ascending, - CFFEModSearchSortOrder::Descending => ModSearchSortOrder::Descending, + CFFEModSearchSortOrder::Descending => { + ModSearchSortOrder::Descending + } } } } @@ -73,7 +92,9 @@ impl From for CFFEModSearchSortOrder { fn from(order: ModSearchSortOrder) -> Self { match order { ModSearchSortOrder::Ascending => CFFEModSearchSortOrder::Ascending, - ModSearchSortOrder::Descending => CFFEModSearchSortOrder::Descending, + ModSearchSortOrder::Descending => { + CFFEModSearchSortOrder::Descending + } } } } diff --git a/crates/carbon_app/src/api/modplatforms/curseforge/responses.rs b/crates/carbon_app/src/api/modplatforms/curseforge/responses.rs index 67db6b8dd..830aba1c0 100644 --- a/crates/carbon_app/src/api/modplatforms/curseforge/responses.rs +++ b/crates/carbon_app/src/api/modplatforms/curseforge/responses.rs @@ -1,7 +1,9 @@ use rspc::Type; use serde::{Deserialize, Serialize}; -use crate::domain::modplatforms::curseforge::{Category, CurseForgeResponse, File, Mod}; +use crate::domain::modplatforms::curseforge::{ + Category, CurseForgeResponse, File, Mod, +}; use super::structs::{CFFECategory, CFFEFile, CFFEMod, CFFEPagination}; diff --git a/crates/carbon_app/src/api/modplatforms/curseforge/structs.rs b/crates/carbon_app/src/api/modplatforms/curseforge/structs.rs index 50c97492c..193652903 100644 --- a/crates/carbon_app/src/api/modplatforms/curseforge/structs.rs +++ b/crates/carbon_app/src/api/modplatforms/curseforge/structs.rs @@ -184,11 +184,15 @@ impl From for CFFEFileStatus { fn from(file_status: mpcf::FileStatus) -> Self { match file_status { mpcf::FileStatus::Processing => CFFEFileStatus::Processing, - mpcf::FileStatus::ChangesRequired => CFFEFileStatus::ChangesRequired, + mpcf::FileStatus::ChangesRequired => { + CFFEFileStatus::ChangesRequired + } mpcf::FileStatus::UnderReview => CFFEFileStatus::UnderReview, mpcf::FileStatus::Approved => CFFEFileStatus::Approved, mpcf::FileStatus::Rejected => CFFEFileStatus::Rejected, - mpcf::FileStatus::MalwareDetected => CFFEFileStatus::MalwareDetected, + mpcf::FileStatus::MalwareDetected => { + CFFEFileStatus::MalwareDetected + } mpcf::FileStatus::Deleted => CFFEFileStatus::Deleted, mpcf::FileStatus::Archived => CFFEFileStatus::Archived, mpcf::FileStatus::Testing => CFFEFileStatus::Testing, @@ -196,8 +200,12 @@ impl From for CFFEFileStatus { mpcf::FileStatus::ReadyForReview => CFFEFileStatus::ReadyForReview, mpcf::FileStatus::Deprecated => CFFEFileStatus::Deprecated, mpcf::FileStatus::Baking => CFFEFileStatus::Baking, - mpcf::FileStatus::AwaitingPublishing => CFFEFileStatus::AwaitingPublishing, - mpcf::FileStatus::FailedPublishing => CFFEFileStatus::FailedPublishing, + mpcf::FileStatus::AwaitingPublishing => { + CFFEFileStatus::AwaitingPublishing + } + mpcf::FileStatus::FailedPublishing => { + CFFEFileStatus::FailedPublishing + } } } } @@ -216,11 +224,19 @@ pub enum CFFEFileRelationType { impl From for CFFEFileRelationType { fn from(relation_type: mpcf::FileRelationType) -> Self { match relation_type { - mpcf::FileRelationType::EmbeddedLibrary => CFFEFileRelationType::EmbeddedLibrary, - mpcf::FileRelationType::OptionalDependency => CFFEFileRelationType::OptionalDependency, - mpcf::FileRelationType::RequiredDependency => CFFEFileRelationType::RequiredDependency, + mpcf::FileRelationType::EmbeddedLibrary => { + CFFEFileRelationType::EmbeddedLibrary + } + mpcf::FileRelationType::OptionalDependency => { + CFFEFileRelationType::OptionalDependency + } + mpcf::FileRelationType::RequiredDependency => { + CFFEFileRelationType::RequiredDependency + } mpcf::FileRelationType::Tool => CFFEFileRelationType::Tool, - mpcf::FileRelationType::Incompatible => CFFEFileRelationType::Incompatible, + mpcf::FileRelationType::Incompatible => { + CFFEFileRelationType::Incompatible + } mpcf::FileRelationType::Include => CFFEFileRelationType::Include, } } @@ -292,7 +308,9 @@ pub struct CFFEFingerprintFuzzyMatchResult { pub fuzzy_matches: Vec, } -impl From for CFFEFingerprintFuzzyMatchResult { +impl From + for CFFEFingerprintFuzzyMatchResult +{ fn from(fuzzy_match_result: mpcf::FingerprintFuzzyMatchResult) -> Self { CFFEFingerprintFuzzyMatchResult { fuzzy_matches: fuzzy_match_result @@ -317,7 +335,11 @@ impl From for CFFEFingerprintMatch { CFFEFingerprintMatch { id: match_.id, file: match_.file.into(), - latest_files: match_.latest_files.into_iter().map(|f| f.into()).collect(), + latest_files: match_ + .latest_files + .into_iter() + .map(|f| f.into()) + .collect(), } } } @@ -356,7 +378,9 @@ impl From for CFFEFingerprintsMatchesResult { partial_match_fingerprints: matches_result .partial_match_fingerprints .into_iter() - .map(|(k, v)| (k, v.into_iter().map(|f| f.to_string()).collect())) + .map(|(k, v)| { + (k, v.into_iter().map(|f| f.to_string()).collect()) + }) .collect(), installed_fingerprints: matches_result .installed_fingerprints @@ -445,8 +469,12 @@ impl From for CFFEMinecraftGameVersion { approved: minecraft_game_version.approved, date_modified: minecraft_game_version.date_modified, game_version_type_id: minecraft_game_version.game_version_type_id, - game_version_status: minecraft_game_version.game_version_status.into(), - game_version_type_status: minecraft_game_version.game_version_type_status.into(), + game_version_status: minecraft_game_version + .game_version_status + .into(), + game_version_type_status: minecraft_game_version + .game_version_type_status + .into(), } } } @@ -508,14 +536,19 @@ pub struct CFFEMinecraftModLoaderVersion { } impl From for CFFEMinecraftModLoaderVersion { - fn from(minecraft_mod_loader_version: mpcf::MinecraftModLoaderVersion) -> Self { + fn from( + minecraft_mod_loader_version: mpcf::MinecraftModLoaderVersion, + ) -> Self { CFFEMinecraftModLoaderVersion { id: minecraft_mod_loader_version.id, game_version_id: minecraft_mod_loader_version.game_version_id, - minecraft_game_version_id: minecraft_mod_loader_version.minecraft_game_version_id, + minecraft_game_version_id: minecraft_mod_loader_version + .minecraft_game_version_id, forge_version: minecraft_mod_loader_version.forge_version, name: minecraft_mod_loader_version.name, - mod_loader_type: minecraft_mod_loader_version.mod_loader_type.into(), + mod_loader_type: minecraft_mod_loader_version + .mod_loader_type + .into(), download_url: minecraft_mod_loader_version.download_url, filename: minecraft_mod_loader_version.filename, install_method: minecraft_mod_loader_version.install_method.into(), @@ -523,12 +556,16 @@ impl From for CFFEMinecraftModLoaderVersion { recommended: minecraft_mod_loader_version.recommended, approved: minecraft_mod_loader_version.approved, date_modified: minecraft_mod_loader_version.date_modified, - maven_version_string: minecraft_mod_loader_version.maven_version_string, + maven_version_string: minecraft_mod_loader_version + .maven_version_string, version_json: minecraft_mod_loader_version.version_json, - libraries_install_location: minecraft_mod_loader_version.libraries_install_location, + libraries_install_location: minecraft_mod_loader_version + .libraries_install_location, minecraft_version: minecraft_mod_loader_version.minecraft_version, - additional_files_json: minecraft_mod_loader_version.additional_files_json, - mod_loader_game_version_id: minecraft_mod_loader_version.mod_loader_game_version_id, + additional_files_json: minecraft_mod_loader_version + .additional_files_json, + mod_loader_game_version_id: minecraft_mod_loader_version + .mod_loader_game_version_id, mod_loader_game_version_type_id: minecraft_mod_loader_version .mod_loader_game_version_type_id, mod_loader_game_version_status: minecraft_mod_loader_version @@ -538,12 +575,16 @@ impl From for CFFEMinecraftModLoaderVersion { .mod_loader_game_version_type_status .into(), mc_game_version_id: minecraft_mod_loader_version.mc_game_version_id, - mc_game_version_type_id: minecraft_mod_loader_version.mc_game_version_type_id, - mc_game_version_status: minecraft_mod_loader_version.mc_game_version_status.into(), + mc_game_version_type_id: minecraft_mod_loader_version + .mc_game_version_type_id, + mc_game_version_status: minecraft_mod_loader_version + .mc_game_version_status + .into(), mc_game_version_type_status: minecraft_mod_loader_version .mc_game_version_type_status .into(), - install_profile_json: minecraft_mod_loader_version.install_profile_json, + install_profile_json: minecraft_mod_loader_version + .install_profile_json, } } } @@ -755,13 +796,19 @@ pub struct CFFESortableGameVersion { } impl From for CFFESortableGameVersion { - fn from(minecraft_sortable_game_version: mpcf::SortableGameVersion) -> Self { + fn from( + minecraft_sortable_game_version: mpcf::SortableGameVersion, + ) -> Self { CFFESortableGameVersion { - game_version_name: minecraft_sortable_game_version.game_version_name, - game_version_padded: minecraft_sortable_game_version.game_version_padded, + game_version_name: minecraft_sortable_game_version + .game_version_name, + game_version_padded: minecraft_sortable_game_version + .game_version_padded, game_version: minecraft_sortable_game_version.game_version, - game_version_release_date: minecraft_sortable_game_version.game_version_release_date, - game_version_type_id: minecraft_sortable_game_version.game_version_type_id, + game_version_release_date: minecraft_sortable_game_version + .game_version_release_date, + game_version_type_id: minecraft_sortable_game_version + .game_version_type_id, } } } @@ -833,7 +880,9 @@ pub enum CFFEGameVersionStatus { impl From for CFFEGameVersionStatus { fn from(minecraft_game_version_status: mpcf::GameVersionStatus) -> Self { match minecraft_game_version_status { - mpcf::GameVersionStatus::Approved => CFFEGameVersionStatus::Approved, + mpcf::GameVersionStatus::Approved => { + CFFEGameVersionStatus::Approved + } mpcf::GameVersionStatus::Deleted => CFFEGameVersionStatus::Deleted, mpcf::GameVersionStatus::New => CFFEGameVersionStatus::New, } @@ -848,10 +897,16 @@ pub enum CFFEGameVersionTypeStatus { } impl From for CFFEGameVersionTypeStatus { - fn from(minecraft_game_version_type_status: mpcf::GameVersionTypeStatus) -> Self { + fn from( + minecraft_game_version_type_status: mpcf::GameVersionTypeStatus, + ) -> Self { match minecraft_game_version_type_status { - mpcf::GameVersionTypeStatus::Normal => CFFEGameVersionTypeStatus::Normal, - mpcf::GameVersionTypeStatus::Deleted => CFFEGameVersionTypeStatus::Deleted, + mpcf::GameVersionTypeStatus::Normal => { + CFFEGameVersionTypeStatus::Normal + } + mpcf::GameVersionTypeStatus::Deleted => { + CFFEGameVersionTypeStatus::Deleted + } } } } @@ -906,9 +961,13 @@ pub enum CFFEModLoaderInstallMethod { } use mpcf::ModLoaderInstallMethod as CFModLoaderInstallMethod; impl From for CFFEModLoaderInstallMethod { - fn from(minecraft_mod_loader_install_method: CFModLoaderInstallMethod) -> Self { + fn from( + minecraft_mod_loader_install_method: CFModLoaderInstallMethod, + ) -> Self { match minecraft_mod_loader_install_method { - CFModLoaderInstallMethod::ForgeInstaller => CFFEModLoaderInstallMethod::ForgeInstaller, + CFModLoaderInstallMethod::ForgeInstaller => { + CFFEModLoaderInstallMethod::ForgeInstaller + } CFModLoaderInstallMethod::ForgeJarInstall => { CFFEModLoaderInstallMethod::ForgeJarInstall } @@ -1086,11 +1145,19 @@ pub enum CFFEDependencyType { impl From for CFFEDependencyType { fn from(minecraft_dependency_type: mpcf::DependencyType) -> Self { match minecraft_dependency_type { - mpcf::DependencyType::EmbeddedLibrary => CFFEDependencyType::EmbeddedLibrary, - mpcf::DependencyType::OptionalDependency => CFFEDependencyType::OptionalDependency, - mpcf::DependencyType::RequiredDependency => CFFEDependencyType::RequiredDependency, + mpcf::DependencyType::EmbeddedLibrary => { + CFFEDependencyType::EmbeddedLibrary + } + mpcf::DependencyType::OptionalDependency => { + CFFEDependencyType::OptionalDependency + } + mpcf::DependencyType::RequiredDependency => { + CFFEDependencyType::RequiredDependency + } mpcf::DependencyType::Tool => CFFEDependencyType::Tool, - mpcf::DependencyType::Incompatible => CFFEDependencyType::Incompatible, + mpcf::DependencyType::Incompatible => { + CFFEDependencyType::Incompatible + } mpcf::DependencyType::Include => CFFEDependencyType::Include, } } diff --git a/crates/carbon_app/src/api/modplatforms/filters.rs b/crates/carbon_app/src/api/modplatforms/filters.rs index 0ca689c67..547d34577 100644 --- a/crates/carbon_app/src/api/modplatforms/filters.rs +++ b/crates/carbon_app/src/api/modplatforms/filters.rs @@ -153,18 +153,26 @@ pub enum FEUnifiedModLoaderType { Waterfall, } -impl TryFrom for curseforge::structs::CFFEModLoaderType { +impl TryFrom + for curseforge::structs::CFFEModLoaderType +{ type Error = anyhow::Error; fn try_from(value: FEUnifiedModLoaderType) -> Result { match value { - FEUnifiedModLoaderType::Forge => Ok(curseforge::structs::CFFEModLoaderType::Forge), + FEUnifiedModLoaderType::Forge => { + Ok(curseforge::structs::CFFEModLoaderType::Forge) + } FEUnifiedModLoaderType::NeoForge => { Ok(curseforge::structs::CFFEModLoaderType::NeoForge) } - FEUnifiedModLoaderType::Fabric => Ok(curseforge::structs::CFFEModLoaderType::Fabric), - FEUnifiedModLoaderType::Quilt => Ok(curseforge::structs::CFFEModLoaderType::Quilt), + FEUnifiedModLoaderType::Fabric => { + Ok(curseforge::structs::CFFEModLoaderType::Fabric) + } + FEUnifiedModLoaderType::Quilt => { + Ok(curseforge::structs::CFFEModLoaderType::Quilt) + } FEUnifiedModLoaderType::LiteLoader => { Ok(curseforge::structs::CFFEModLoaderType::LiteLoader) } @@ -184,29 +192,75 @@ impl TryFrom for modrinth::structs::MRFELoaderType { fn try_from(value: FEUnifiedModLoaderType) -> Result { match value { - FEUnifiedModLoaderType::Forge => Ok(modrinth::structs::MRFELoaderType::Forge), - FEUnifiedModLoaderType::NeoForge => Ok(modrinth::structs::MRFELoaderType::NeoForge), - FEUnifiedModLoaderType::Fabric => Ok(modrinth::structs::MRFELoaderType::Fabric), - FEUnifiedModLoaderType::Quilt => Ok(modrinth::structs::MRFELoaderType::Quilt), - FEUnifiedModLoaderType::LiteLoader => Ok(modrinth::structs::MRFELoaderType::Liteloader), - FEUnifiedModLoaderType::Bukkit => Ok(modrinth::structs::MRFELoaderType::Bukkit), - FEUnifiedModLoaderType::Bungeecord => Ok(modrinth::structs::MRFELoaderType::Bungeecord), - FEUnifiedModLoaderType::Canvas => Ok(modrinth::structs::MRFELoaderType::Canvas), - FEUnifiedModLoaderType::Datapack => Ok(modrinth::structs::MRFELoaderType::Datapack), - FEUnifiedModLoaderType::Folia => Ok(modrinth::structs::MRFELoaderType::Folia), - FEUnifiedModLoaderType::Iris => Ok(modrinth::structs::MRFELoaderType::Iris), - FEUnifiedModLoaderType::Minecraft => Ok(modrinth::structs::MRFELoaderType::Minecraft), - FEUnifiedModLoaderType::Modloader => Ok(modrinth::structs::MRFELoaderType::Modloader), - FEUnifiedModLoaderType::Optifine => Ok(modrinth::structs::MRFELoaderType::Optifine), - FEUnifiedModLoaderType::Paper => Ok(modrinth::structs::MRFELoaderType::Paper), - FEUnifiedModLoaderType::Purpur => Ok(modrinth::structs::MRFELoaderType::Purpur), - FEUnifiedModLoaderType::Rift => Ok(modrinth::structs::MRFELoaderType::Rift), - FEUnifiedModLoaderType::Spigot => Ok(modrinth::structs::MRFELoaderType::Spigot), - FEUnifiedModLoaderType::Sponge => Ok(modrinth::structs::MRFELoaderType::Sponge), - FEUnifiedModLoaderType::Vanilla => Ok(modrinth::structs::MRFELoaderType::Vanilla), - FEUnifiedModLoaderType::Velocity => Ok(modrinth::structs::MRFELoaderType::Velocity), - FEUnifiedModLoaderType::Waterfall => Ok(modrinth::structs::MRFELoaderType::Waterfall), - FEUnifiedModLoaderType::Unknown => Err(anyhow!("Can't use unknown modloader type")), + FEUnifiedModLoaderType::Forge => { + Ok(modrinth::structs::MRFELoaderType::Forge) + } + FEUnifiedModLoaderType::NeoForge => { + Ok(modrinth::structs::MRFELoaderType::NeoForge) + } + FEUnifiedModLoaderType::Fabric => { + Ok(modrinth::structs::MRFELoaderType::Fabric) + } + FEUnifiedModLoaderType::Quilt => { + Ok(modrinth::structs::MRFELoaderType::Quilt) + } + FEUnifiedModLoaderType::LiteLoader => { + Ok(modrinth::structs::MRFELoaderType::Liteloader) + } + FEUnifiedModLoaderType::Bukkit => { + Ok(modrinth::structs::MRFELoaderType::Bukkit) + } + FEUnifiedModLoaderType::Bungeecord => { + Ok(modrinth::structs::MRFELoaderType::Bungeecord) + } + FEUnifiedModLoaderType::Canvas => { + Ok(modrinth::structs::MRFELoaderType::Canvas) + } + FEUnifiedModLoaderType::Datapack => { + Ok(modrinth::structs::MRFELoaderType::Datapack) + } + FEUnifiedModLoaderType::Folia => { + Ok(modrinth::structs::MRFELoaderType::Folia) + } + FEUnifiedModLoaderType::Iris => { + Ok(modrinth::structs::MRFELoaderType::Iris) + } + FEUnifiedModLoaderType::Minecraft => { + Ok(modrinth::structs::MRFELoaderType::Minecraft) + } + FEUnifiedModLoaderType::Modloader => { + Ok(modrinth::structs::MRFELoaderType::Modloader) + } + FEUnifiedModLoaderType::Optifine => { + Ok(modrinth::structs::MRFELoaderType::Optifine) + } + FEUnifiedModLoaderType::Paper => { + Ok(modrinth::structs::MRFELoaderType::Paper) + } + FEUnifiedModLoaderType::Purpur => { + Ok(modrinth::structs::MRFELoaderType::Purpur) + } + FEUnifiedModLoaderType::Rift => { + Ok(modrinth::structs::MRFELoaderType::Rift) + } + FEUnifiedModLoaderType::Spigot => { + Ok(modrinth::structs::MRFELoaderType::Spigot) + } + FEUnifiedModLoaderType::Sponge => { + Ok(modrinth::structs::MRFELoaderType::Sponge) + } + FEUnifiedModLoaderType::Vanilla => { + Ok(modrinth::structs::MRFELoaderType::Vanilla) + } + FEUnifiedModLoaderType::Velocity => { + Ok(modrinth::structs::MRFELoaderType::Velocity) + } + FEUnifiedModLoaderType::Waterfall => { + Ok(modrinth::structs::MRFELoaderType::Waterfall) + } + FEUnifiedModLoaderType::Unknown => { + Err(anyhow!("Can't use unknown modloader type")) + } FEUnifiedModLoaderType::Cauldron => { Err(anyhow!("Modrinth does not support the `Cauldron` loader")) } @@ -235,7 +289,9 @@ impl From for curseforge::structs::CFFEClassId { fn from(value: FEUnifiedSearchType) -> Self { match value { FEUnifiedSearchType::Mod => curseforge::structs::CFFEClassId::Mods, - FEUnifiedSearchType::ModPack => curseforge::structs::CFFEClassId::Modpacks, + FEUnifiedSearchType::ModPack => { + curseforge::structs::CFFEClassId::Modpacks + } } } } @@ -262,13 +318,17 @@ pub struct FEUnifiedSearchParameters { pub search_api: FESearchAPI, } -impl From for curseforge::filters::CFFEModSearchParameters { +impl From + for curseforge::filters::CFFEModSearchParameters +{ fn from(value: FEUnifiedSearchParameters) -> Self { curseforge::filters::CFFEModSearchParameters { query: CFFEModSearchParametersQuery { game_id: 432, search_filter: value.search_query, - game_version: value.game_versions.and_then(|vers| vers.into_iter().next()), + game_version: value + .game_versions + .and_then(|vers| vers.into_iter().next()), category_ids: value.categories.map(|cat_groups| { cat_groups .into_iter() @@ -276,7 +336,9 @@ impl From for curseforge::filters::CFFEModSearchParam // Curseforge does't support ORs of categories, take only the first of each // group cats.into_iter().find_map(|cat| match cat { - FEUnifiedSearchCategoryID::Curseforge(id) => Some(id), + FEUnifiedSearchCategoryID::Curseforge(id) => { + Some(id) + } FEUnifiedSearchCategoryID::Modrinth(_) => None, }) }) @@ -284,7 +346,9 @@ impl From for curseforge::filters::CFFEModSearchParam }), sort_order: value.sort_order, sort_field: match value.sort_index { - Some(FEUnifiedModSortIndex::CurseForge(field)) => Some(field), + Some(FEUnifiedModSortIndex::CurseForge(field)) => { + Some(field) + } _ => None, }, class_id: value.project_type.map(Into::into), @@ -310,12 +374,15 @@ impl TryFrom type Error = anyhow::Error; fn try_from(value: FEUnifiedSearchParameters) -> Result { - let search_params: curseforge::filters::CFFEModSearchParameters = value.try_into()?; + let search_params: curseforge::filters::CFFEModSearchParameters = + value.try_into()?; Ok(search_params.into()) } } -impl From for modrinth::filters::MRFEProjectSearchParameters { +impl From + for modrinth::filters::MRFEProjectSearchParameters +{ fn from(value: FEUnifiedSearchParameters) -> Self { let mut facets = modrinth::filters::MRFESearchFacetAnd::new(); if let Some(categories) = value.categories { @@ -324,9 +391,9 @@ impl From for modrinth::filters::MRFEProjectSearchPar .into_iter() .filter_map(|cat| match cat { FEUnifiedSearchCategoryID::Curseforge(_) => None, - FEUnifiedSearchCategoryID::Modrinth(id) => { - Some(modrinth::filters::MRFESearchFacet::Category(id)) - } + FEUnifiedSearchCategoryID::Modrinth(id) => Some( + modrinth::filters::MRFESearchFacet::Category(id), + ), }) .collect(); facets.push(category_or); @@ -343,17 +410,24 @@ impl From for modrinth::filters::MRFEProjectSearchPar let modloaders_or = modloaders .into_iter() .filter_map(|loader| { - TryInto::::try_into(loader).ok() + TryInto::::try_into( + loader, + ) + .ok() }) .map(|modloader| { - modrinth::filters::MRFESearchFacet::Category(modloader.to_string()) + modrinth::filters::MRFESearchFacet::Category( + modloader.to_string(), + ) }) .collect(); facets.push(modloaders_or); } if let Some(project_type) = value.project_type { facets.push(modrinth::filters::MRFESearchFacetOr(vec![ - modrinth::filters::MRFESearchFacet::ProjectType(project_type.to_string()), + modrinth::filters::MRFESearchFacet::ProjectType( + project_type.to_string(), + ), ])); } modrinth::filters::MRFEProjectSearchParameters { diff --git a/crates/carbon_app/src/api/modplatforms/mod.rs b/crates/carbon_app/src/api/modplatforms/mod.rs index 3f9a7bc21..a9e7f3d7f 100644 --- a/crates/carbon_app/src/api/modplatforms/mod.rs +++ b/crates/carbon_app/src/api/modplatforms/mod.rs @@ -5,13 +5,15 @@ use strum::IntoEnumIterator; use crate::{ api::{ keys::modplatforms::{ - CURSEFORGE_GET_CATEGORIES, CURSEFORGE_GET_FILES, CURSEFORGE_GET_MOD, - CURSEFORGE_GET_MODLOADERS, CURSEFORGE_GET_MODS, CURSEFORGE_GET_MOD_DESCRIPTION, - CURSEFORGE_GET_MOD_FILE, CURSEFORGE_GET_MOD_FILES, CURSEFORGE_GET_MOD_FILE_CHANGELOG, - CURSEFORGE_SEARCH, MODRINTH_GET_CATEGORIES, MODRINTH_GET_LOADERS, MODRINTH_GET_PROJECT, - MODRINTH_GET_PROJECTS, MODRINTH_GET_PROJECT_TEAM, MODRINTH_GET_PROJECT_VERSIONS, - MODRINTH_GET_TEAM, MODRINTH_GET_VERSION, MODRINTH_GET_VERSIONS, MODRINTH_SEARCH, - UNIFIED_SEARCH, + CURSEFORGE_GET_CATEGORIES, CURSEFORGE_GET_FILES, + CURSEFORGE_GET_MOD, CURSEFORGE_GET_MODLOADERS, CURSEFORGE_GET_MODS, + CURSEFORGE_GET_MOD_DESCRIPTION, CURSEFORGE_GET_MOD_FILE, + CURSEFORGE_GET_MOD_FILES, CURSEFORGE_GET_MOD_FILE_CHANGELOG, + CURSEFORGE_SEARCH, MODRINTH_GET_CATEGORIES, MODRINTH_GET_LOADERS, + MODRINTH_GET_PROJECT, MODRINTH_GET_PROJECTS, + MODRINTH_GET_PROJECT_TEAM, MODRINTH_GET_PROJECT_VERSIONS, + MODRINTH_GET_TEAM, MODRINTH_GET_VERSION, MODRINTH_GET_VERSIONS, + MODRINTH_SEARCH, UNIFIED_SEARCH, }, router::router, }, diff --git a/crates/carbon_app/src/api/modplatforms/modrinth/filters.rs b/crates/carbon_app/src/api/modplatforms/modrinth/filters.rs index 92cc6fe19..45bea8fe0 100644 --- a/crates/carbon_app/src/api/modplatforms/modrinth/filters.rs +++ b/crates/carbon_app/src/api/modplatforms/modrinth/filters.rs @@ -10,8 +10,9 @@ use serde::{Deserialize, Serialize}; use crate::domain::modplatforms::modrinth::{ project::ProjectVersionsFilters, search::{ - ProjectID, ProjectIDs, ProjectSearchParameters, SearchFacet, SearchFacetAnd, SearchFacetOr, - SearchIndex, TeamID, VersionID, VersionIDs, + ProjectID, ProjectIDs, ProjectSearchParameters, SearchFacet, + SearchFacetAnd, SearchFacetOr, SearchIndex, TeamID, VersionID, + VersionIDs, }, }; use anyhow::anyhow; @@ -63,7 +64,10 @@ impl FromStr for MRFESearchFacet { fn from_str(facet: &str) -> Result { let Some((facet_type, value)) = facet.trim().split_once(':') else { - return Err(anyhow!("Improperly formatted search facet `{}`", facet)); + return Err(anyhow!( + "Improperly formatted search facet `{}`", + facet + )); }; match facet_type { "categories" => Ok(MRFESearchFacet::Category(value.to_string())), @@ -85,7 +89,9 @@ impl TryFrom<&str> for MRFESearchFacet { impl Display for MRFESearchFacet { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let out = match self { - MRFESearchFacet::Category(category) => format!("categories:{}", category), + MRFESearchFacet::Category(category) => { + format!("categories:{}", category) + } MRFESearchFacet::Version(version) => format!("version:{}", version), MRFESearchFacet::License(license) => format!("license:{}", license), MRFESearchFacet::ProjectType(project_type) => { @@ -119,10 +125,14 @@ impl<'de> Deserialize<'de> for MRFESearchFacet { impl From for MRFESearchFacet { fn from(facet: SearchFacet) -> Self { match facet { - SearchFacet::Category(category) => MRFESearchFacet::Category(category), + SearchFacet::Category(category) => { + MRFESearchFacet::Category(category) + } SearchFacet::Version(version) => MRFESearchFacet::Version(version), SearchFacet::License(license) => MRFESearchFacet::License(license), - SearchFacet::ProjectType(project_type) => MRFESearchFacet::ProjectType(project_type), + SearchFacet::ProjectType(project_type) => { + MRFESearchFacet::ProjectType(project_type) + } } } } @@ -130,10 +140,14 @@ impl From for MRFESearchFacet { impl From for SearchFacet { fn from(facet: MRFESearchFacet) -> Self { match facet { - MRFESearchFacet::Category(category) => SearchFacet::Category(category), + MRFESearchFacet::Category(category) => { + SearchFacet::Category(category) + } MRFESearchFacet::Version(version) => SearchFacet::Version(version), MRFESearchFacet::License(license) => SearchFacet::License(license), - MRFESearchFacet::ProjectType(project_type) => SearchFacet::ProjectType(project_type), + MRFESearchFacet::ProjectType(project_type) => { + SearchFacet::ProjectType(project_type) + } } } } diff --git a/crates/carbon_app/src/api/modplatforms/modrinth/responses.rs b/crates/carbon_app/src/api/modplatforms/modrinth/responses.rs index bc80e2bfe..6f2b89cec 100644 --- a/crates/carbon_app/src/api/modplatforms/modrinth/responses.rs +++ b/crates/carbon_app/src/api/modplatforms/modrinth/responses.rs @@ -9,8 +9,8 @@ use serde::{Deserialize, Serialize}; use crate::domain::modplatforms::modrinth::{ responses::{ - CategoriesResponse, LoadersResponse, ProjectsResponse, TeamResponse, VersionHashesResponse, - VersionsResponse, + CategoriesResponse, LoadersResponse, ProjectsResponse, TeamResponse, + VersionHashesResponse, VersionsResponse, }, search::ProjectSearchResponse, }; @@ -47,7 +47,9 @@ impl From for MRFEProjectSearchResponse { impl TryFrom for ProjectSearchResponse { type Error = anyhow::Error; - fn try_from(results: MRFEProjectSearchResponse) -> Result { + fn try_from( + results: MRFEProjectSearchResponse, + ) -> Result { Ok(ProjectSearchResponse { hits: results .hits @@ -257,7 +259,9 @@ impl IntoIterator for MRFEVersionHashesResponse { } impl FromIterator<(String, MRFEVersion)> for MRFEVersionHashesResponse { - fn from_iter>(iter: I) -> Self { + fn from_iter>( + iter: I, + ) -> Self { let iter = iter.into_iter(); let (size_lower, _) = iter.size_hint(); let mut c = HashMap::with_capacity(size_lower); diff --git a/crates/carbon_app/src/api/modplatforms/modrinth/structs.rs b/crates/carbon_app/src/api/modplatforms/modrinth/structs.rs index 7790eed20..16c2249b8 100644 --- a/crates/carbon_app/src/api/modplatforms/modrinth/structs.rs +++ b/crates/carbon_app/src/api/modplatforms/modrinth/structs.rs @@ -5,8 +5,8 @@ use serde::{Deserialize, Serialize}; use crate::domain::modplatforms::modrinth::{ project::{ - DonationLink, GalleryItem, License, ModeratorMessage, Project, ProjectStatus, - ProjectSupportRange, ProjectType, + DonationLink, GalleryItem, License, ModeratorMessage, Project, + ProjectStatus, ProjectSupportRange, ProjectType, }, search::ProjectSearchResult, tag::{Category, Loader, LoaderType}, @@ -35,7 +35,9 @@ impl From for MRFEProjectSupportRange { fn from(value: ProjectSupportRange) -> Self { match value { ProjectSupportRange::Required => MRFEProjectSupportRange::Required, - ProjectSupportRange::Unsupported => MRFEProjectSupportRange::Unsupported, + ProjectSupportRange::Unsupported => { + MRFEProjectSupportRange::Unsupported + } ProjectSupportRange::Optional => MRFEProjectSupportRange::Optional, ProjectSupportRange::Unknown => MRFEProjectSupportRange::Unknown, } @@ -46,7 +48,9 @@ impl From for ProjectSupportRange { fn from(value: MRFEProjectSupportRange) -> Self { match value { MRFEProjectSupportRange::Required => ProjectSupportRange::Required, - MRFEProjectSupportRange::Unsupported => ProjectSupportRange::Unsupported, + MRFEProjectSupportRange::Unsupported => { + ProjectSupportRange::Unsupported + } MRFEProjectSupportRange::Optional => ProjectSupportRange::Optional, MRFEProjectSupportRange::Unknown => ProjectSupportRange::Unknown, } @@ -389,7 +393,11 @@ impl From for MRFEVersion { name: value.name, version_number: value.version_number, changelog: value.changelog, - dependencies: value.dependencies.into_iter().map(Into::into).collect(), + dependencies: value + .dependencies + .into_iter() + .map(Into::into) + .collect(), game_versions: value.game_versions, version_type: value.version_type.into(), loaders: value.loaders, @@ -415,7 +423,11 @@ impl TryFrom for Version { name: value.name, version_number: value.version_number, changelog: value.changelog, - dependencies: value.dependencies.into_iter().map(Into::into).collect(), + dependencies: value + .dependencies + .into_iter() + .map(Into::into) + .collect(), game_versions: value.game_versions, version_type: value.version_type.into(), loaders: value.loaders, @@ -671,10 +683,16 @@ pub enum MRFERequestedVersionStatus { impl From for MRFERequestedVersionStatus { fn from(value: RequestedVersionStatus) -> Self { match value { - RequestedVersionStatus::Listed => MRFERequestedVersionStatus::Listed, - RequestedVersionStatus::Archived => MRFERequestedVersionStatus::Archived, + RequestedVersionStatus::Listed => { + MRFERequestedVersionStatus::Listed + } + RequestedVersionStatus::Archived => { + MRFERequestedVersionStatus::Archived + } RequestedVersionStatus::Draft => MRFERequestedVersionStatus::Draft, - RequestedVersionStatus::Unlisted => MRFERequestedVersionStatus::Unlisted, + RequestedVersionStatus::Unlisted => { + MRFERequestedVersionStatus::Unlisted + } } } } @@ -682,10 +700,16 @@ impl From for MRFERequestedVersionStatus { impl From for RequestedVersionStatus { fn from(value: MRFERequestedVersionStatus) -> Self { match value { - MRFERequestedVersionStatus::Listed => RequestedVersionStatus::Listed, - MRFERequestedVersionStatus::Archived => RequestedVersionStatus::Archived, + MRFERequestedVersionStatus::Listed => { + RequestedVersionStatus::Listed + } + MRFERequestedVersionStatus::Archived => { + RequestedVersionStatus::Archived + } MRFERequestedVersionStatus::Draft => RequestedVersionStatus::Draft, - MRFERequestedVersionStatus::Unlisted => RequestedVersionStatus::Unlisted, + MRFERequestedVersionStatus::Unlisted => { + RequestedVersionStatus::Unlisted + } } } } @@ -790,7 +814,11 @@ impl From for MRFEProject { source_url: value.source_url, wiki_url: value.wiki_url, discord_url: value.discord_url, - donation_urls: value.donation_urls.into_iter().map(Into::into).collect(), + donation_urls: value + .donation_urls + .into_iter() + .map(Into::into) + .collect(), project_type: value.project_type.into(), downloads: value.downloads, icon_url: value.icon_url, @@ -829,7 +857,11 @@ impl TryFrom for Project { source_url: value.source_url, wiki_url: value.wiki_url, discord_url: value.discord_url, - donation_urls: value.donation_urls.into_iter().map(Into::into).collect(), + donation_urls: value + .donation_urls + .into_iter() + .map(Into::into) + .collect(), project_type: value.project_type.into(), downloads: value.downloads, icon_url: value.icon_url, diff --git a/crates/carbon_app/src/api/modplatforms/responses.rs b/crates/carbon_app/src/api/modplatforms/responses.rs index 07bd075c8..977a2a685 100644 --- a/crates/carbon_app/src/api/modplatforms/responses.rs +++ b/crates/carbon_app/src/api/modplatforms/responses.rs @@ -31,7 +31,9 @@ pub struct FEUnifiedSearchResponse { pub pagination: Option, } -impl From for FEUnifiedSearchResponse { +impl From + for FEUnifiedSearchResponse +{ fn from(value: curseforge::responses::FEModSearchResponse) -> Self { FEUnifiedSearchResponse { search_api: FESearchAPI::Curseforge, @@ -40,17 +42,21 @@ impl From for FEUnifiedSearchRespons .into_iter() .map(FEUnifiedSearchResult::Curseforge) .collect(), - pagination: value.pagination.map(|pagination| FEUnifiedPagination { - index: pagination.index as u32, - page_size: pagination.page_size as u32, - result_count: pagination.result_count as u32, - total_count: pagination.total_count as u32, + pagination: value.pagination.map(|pagination| { + FEUnifiedPagination { + index: pagination.index as u32, + page_size: pagination.page_size as u32, + result_count: pagination.result_count as u32, + total_count: pagination.total_count as u32, + } }), } } } -impl From for FEUnifiedSearchResponse { +impl From + for FEUnifiedSearchResponse +{ fn from(value: modrinth::responses::MRFEProjectSearchResponse) -> Self { let result_count = value.hits.len(); FEUnifiedSearchResponse { diff --git a/crates/carbon_app/src/api/settings.rs b/crates/carbon_app/src/api/settings.rs index c6d8e7d34..b3a71aed9 100644 --- a/crates/carbon_app/src/api/settings.rs +++ b/crates/carbon_app/src/api/settings.rs @@ -1,7 +1,8 @@ use crate::{ api::{ keys::settings::{ - GET_PRIVACY_STATEMENT_BODY, GET_SETTINGS, GET_TERMS_OF_SERVICE_BODY, SET_SETTINGS, + GET_PRIVACY_STATEMENT_BODY, GET_SETTINGS, + GET_TERMS_OF_SERVICE_BODY, SET_SETTINGS, }, router::router, }, @@ -141,7 +142,9 @@ impl Default for ModChannel { impl TryFrom for FESettings { type Error = anyhow::Error; - fn try_from(data: crate::db::app_configuration::Data) -> Result { + fn try_from( + data: crate::db::app_configuration::Data, + ) -> Result { Ok(Self { theme: data.theme, language: data.language, diff --git a/crates/carbon_app/src/api/vtask.rs b/crates/carbon_app/src/api/vtask.rs index af2bb5a1c..bbfa6e48e 100644 --- a/crates/carbon_app/src/api/vtask.rs +++ b/crates/carbon_app/src/api/vtask.rs @@ -98,7 +98,9 @@ impl From for Progress { match value { domain::Progress::Indeterminate => Self::Indeterminate, domain::Progress::Known(x) => Self::Known(x), - domain::Progress::Failed(err) => Self::Failed(FeError::from_anyhow(&*err)), + domain::Progress::Failed(err) => { + Self::Failed(FeError::from_anyhow(&*err)) + } } } } @@ -118,7 +120,9 @@ impl From for FESubtaskProgress { domain::SubtaskProgress::Download { downloaded, total } => { Self::Download { downloaded, total } } - domain::SubtaskProgress::Item { current, total } => Self::Item { current, total }, + domain::SubtaskProgress::Item { current, total } => { + Self::Item { current, total } + } domain::SubtaskProgress::Opaque => Self::Opaque, } } diff --git a/crates/carbon_app/src/cache_middleware.rs b/crates/carbon_app/src/cache_middleware.rs index 29da5d5d8..837818c27 100644 --- a/crates/carbon_app/src/cache_middleware.rs +++ b/crates/carbon_app/src/cache_middleware.rs @@ -1,7 +1,9 @@ use anyhow::anyhow; use chrono::{DateTime, Duration, Utc}; use reqwest::{Method, Request, Response, StatusCode}; -use reqwest_middleware::{ClientBuilder, ClientWithMiddleware, Middleware, Next, Result}; +use reqwest_middleware::{ + ClientBuilder, ClientWithMiddleware, Middleware, Next, Result, +}; use task_local_extensions::Extensions; use crate::{ @@ -12,7 +14,10 @@ use crate::{ managers::UnsafeAppRef, }; -pub fn new_client(app: UnsafeAppRef, client_builder: ClientBuilder) -> ClientWithMiddleware { +pub fn new_client( + app: UnsafeAppRef, + client_builder: ClientBuilder, +) -> ClientWithMiddleware { client_builder.with(CacheMiddleware { app }).build() } @@ -41,8 +46,10 @@ impl Middleware for CacheMiddleware { body: Vec, cached: bool, ) -> std::result::Result { - let mut response = hyper::Response::builder() - .status(StatusCode::from_u16(status.try_into().map_err(|_| ())?).map_err(|_| ())?); + let mut response = hyper::Response::builder().status( + StatusCode::from_u16(status.try_into().map_err(|_| ())?) + .map_err(|_| ())?, + ); if cached { response = response.header("Cached", "true"); @@ -63,14 +70,19 @@ impl Middleware for CacheMiddleware { ))]) .exec() .await - .map_err(|e| reqwest_middleware::Error::Middleware(anyhow!(e)))? + .map_err(|e| { + reqwest_middleware::Error::Middleware(anyhow!(e)) + })? }; // return the cached value if fresh if let Some(expires) = cached.as_ref().and_then(|c| c.expires_at) { if expires > Utc::now() { - let cached = cached.take().expect("cached was just asserted to be Some"); - if let Ok(response) = build_cached(cached.status_code, cached.data, true) { + let cached = + cached.take().expect("cached was just asserted to be Some"); + if let Ok(response) = + build_cached(cached.status_code, cached.data, true) + { return Ok(response); } } @@ -84,9 +96,15 @@ impl Middleware for CacheMiddleware { 'use_cache: { if let Some(cached) = cached { - if let (Some(cached_etag), Some(etag)) = (cached.etag, headers.get("etag")) { + if let (Some(cached_etag), Some(etag)) = + (cached.etag, headers.get("etag")) + { if Some(&cached_etag as &str) == etag.to_str().ok() { - match build_cached(cached.status_code, cached.data, true) { + match build_cached( + cached.status_code, + cached.data, + true, + ) { Ok(response) => return Ok(response), Err(_) => break 'use_cache, } @@ -96,8 +114,14 @@ impl Middleware for CacheMiddleware { if let (Some(cached_last_modified), Some(last_modified)) = (cached.last_modified, headers.get("last-modified")) { - if Some(&cached_last_modified as &str) == last_modified.to_str().ok() { - match build_cached(cached.status_code, cached.data, true) { + if Some(&cached_last_modified as &str) + == last_modified.to_str().ok() + { + match build_cached( + cached.status_code, + cached.data, + true, + ) { Ok(response) => return Ok(response), Err(_) => break 'use_cache, } @@ -136,7 +160,9 @@ impl Middleware for CacheMiddleware { } if !no_store { - expires = max_age.map(|offset| Utc::now() + Duration::seconds(offset as i64)); + expires = max_age.map(|offset| { + Utc::now() + Duration::seconds(offset as i64) + }); } } @@ -171,7 +197,9 @@ impl Middleware for CacheMiddleware { app.prisma_client .http_cache() // will not fail when not found - .delete_many(vec![WhereParam::Url(StringFilter::Equals(url.clone()))]), + .delete_many(vec![WhereParam::Url( + StringFilter::Equals(url.clone()), + )]), app.prisma_client.http_cache().create( url, status, @@ -188,9 +216,9 @@ impl Middleware for CacheMiddleware { match build_cached(status, body.to_vec(), false) { Ok(response) => return Ok(response), Err(_) => { - return Err(reqwest_middleware::Error::Middleware(anyhow!( - "could not return cached response" - ))) + return Err(reqwest_middleware::Error::Middleware( + anyhow!("could not return cached response"), + )) } } } @@ -248,7 +276,9 @@ mod test { let port = launch_server![( header::EXPIRES, - httpdate::fmt_http_date(SystemTime::from(Utc::now() + Duration::seconds(2))) + httpdate::fmt_http_date(SystemTime::from( + Utc::now() + Duration::seconds(2) + )) )]; assert!(!request_cached(&app, port).await); @@ -293,7 +323,8 @@ mod test { async fn test_last_modified() { let app = crate::setup_managers_for_test().await; - let port = launch_server![(header::LAST_MODIFIED, "test_last_modified")]; + let port = + launch_server![(header::LAST_MODIFIED, "test_last_modified")]; assert!(!request_cached(&app, port).await); assert!(request_cached(&app, port).await); diff --git a/crates/carbon_app/src/domain/java.rs b/crates/carbon_app/src/domain/java.rs index 00fb305e9..9e620ac64 100644 --- a/crates/carbon_app/src/domain/java.rs +++ b/crates/carbon_app/src/domain/java.rs @@ -87,7 +87,9 @@ impl ToString for JavaComponentType { } } -#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Hash, Copy, Clone, EnumIter)] +#[derive( + Serialize, Deserialize, PartialEq, Eq, Debug, Hash, Copy, Clone, EnumIter, +)] pub enum JavaArch { X86_64, X86_32, @@ -132,7 +134,9 @@ impl<'a> TryFrom<&'a str> for JavaArch { } } -#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash, EnumIter, Copy, Clone)] +#[derive( + Serialize, Deserialize, Debug, PartialEq, Eq, Hash, EnumIter, Copy, Clone, +)] pub enum JavaOs { Windows, Linux, @@ -242,22 +246,32 @@ impl TryFrom<&str> for JavaVersion { } } "update_number" => { - if let Some(update_number) = captures.name("update_number") { - version.update_number = Some(update_number.as_str().parse()?); + if let Some(update_number) = + captures.name("update_number") + { + version.update_number = + Some(update_number.as_str().parse()?); } } "prerelease" => { if let Some(prerelease) = captures.name("prerelease") { - version.prerelease = Some(prerelease.as_str().to_string()); + version.prerelease = + Some(prerelease.as_str().to_string()); } } "build_metadata" => { - if let Some(build_metadata) = captures.name("build_metadata") { - version.build_metadata = Some(build_metadata.as_str().to_string()); + if let Some(build_metadata) = + captures.name("build_metadata") + { + version.build_metadata = + Some(build_metadata.as_str().to_string()); } } _ => { - unreachable!("Regex capture group not handled: {}", name) + unreachable!( + "Regex capture group not handled: {}", + name + ) } } } @@ -266,7 +280,8 @@ impl TryFrom<&str> for JavaVersion { if version.major == 1 { version.major = version.minor; version.minor = version.patch.parse()?; - version.patch = version.update_number.unwrap_or("0".to_string()); + version.patch = + version.update_number.unwrap_or("0".to_string()); version.update_number = None; } @@ -312,7 +327,9 @@ impl JavaVersion { } } -#[derive(Serialize, Deserialize, Debug, Copy, Clone, EnumIter, Eq, PartialEq)] +#[derive( + Serialize, Deserialize, Debug, Copy, Clone, EnumIter, Eq, PartialEq, +)] pub enum SystemJavaProfileName { Legacy, Alpha, @@ -323,7 +340,10 @@ pub enum SystemJavaProfileName { } impl SystemJavaProfileName { - pub fn is_java_version_compatible(&self, java_version: &JavaVersion) -> bool { + pub fn is_java_version_compatible( + &self, + java_version: &JavaVersion, + ) -> bool { match self { Self::Legacy => java_version.major == 8, Self::Alpha => java_version.major == 16, @@ -342,7 +362,9 @@ impl From for SystemJavaProfileName { MinecraftJavaProfile::JavaRuntimeAlpha => Self::Alpha, MinecraftJavaProfile::JavaRuntimeBeta => Self::Beta, MinecraftJavaProfile::JavaRuntimeGamma => Self::Gamma, - MinecraftJavaProfile::JavaRuntimeGammaSnapshot => Self::GammaSnapshot, + MinecraftJavaProfile::JavaRuntimeGammaSnapshot => { + Self::GammaSnapshot + } MinecraftJavaProfile::MinecraftJavaExe => Self::MinecraftJavaExe, } } @@ -386,7 +408,9 @@ pub struct SystemJavaProfile { impl TryFrom for SystemJavaProfile { type Error = anyhow::Error; - fn try_from(data: crate::db::java_system_profile::Data) -> Result { + fn try_from( + data: crate::db::java_system_profile::Data, + ) -> Result { Ok(Self { name: data.name.as_str().try_into()?, java_id: data.java_id, diff --git a/crates/carbon_app/src/domain/minecraft/minecraft.rs b/crates/carbon_app/src/domain/minecraft/minecraft.rs index d22ea5ad9..654593f54 100644 --- a/crates/carbon_app/src/domain/minecraft/minecraft.rs +++ b/crates/carbon_app/src/domain/minecraft/minecraft.rs @@ -1,5 +1,6 @@ use daedalus::minecraft::{ - Argument, ArgumentValue, AssetsIndex, Download, Library, Os, OsRule, Rule, RuleAction, + Argument, ArgumentValue, AssetsIndex, Download, Library, Os, OsRule, Rule, + RuleAction, }; use std::path::PathBuf; use sysinfo::SystemExt; @@ -21,13 +22,17 @@ pub fn libraries_into_vec_downloadable( continue; } - if let Some(downloadable) = library_into_lib_downloadable(library.clone(), base_path) { + if let Some(downloadable) = + library_into_lib_downloadable(library.clone(), base_path) + { files.push(downloadable); } - if let Some(downloadable) = - library_into_natives_downloadable(library.clone(), base_path, java_arch) - { + if let Some(downloadable) = library_into_natives_downloadable( + library.clone(), + base_path, + java_arch, + ) { files.push(downloadable); } @@ -126,7 +131,8 @@ pub fn library_into_natives_downloadable( base_path: &std::path::Path, java_arch: &JavaArch, ) -> Option { - let Some(classifiers) = library.downloads.and_then(|v| v.classifiers) else { + let Some(classifiers) = library.downloads.and_then(|v| v.classifiers) + else { return None; }; @@ -138,7 +144,9 @@ pub fn library_into_natives_downloadable( return None; }; - let Some(mapping_class) = classifiers.get(&natives_name.replace("${arch}", ARCH_WIDTH)) else { + let Some(mapping_class) = + classifiers.get(&natives_name.replace("${arch}", ARCH_WIDTH)) + else { return None; }; @@ -185,7 +193,9 @@ pub fn chain_lwjgl_libs_with_base_libs( if let Some(downloads) = library.downloads.as_ref() { if let Some(artifact) = downloads.artifact.as_ref() { artifact.path.clone() - } else if let Some(classifiers) = downloads.classifiers.as_ref() { + } else if let Some(classifiers) = + downloads.classifiers.as_ref() + { let Some(native_name) = library .natives .as_ref() @@ -239,7 +249,9 @@ pub fn assets_index_into_vec_downloadable( ), asset_path, ) - .with_checksum(Some(carbon_net::Checksum::Sha1(object.hash.clone()))) + .with_checksum(Some(carbon_net::Checksum::Sha1( + object.hash.clone(), + ))) .with_size(object.size as u64), ); } diff --git a/crates/carbon_app/src/domain/modplatforms/curseforge/manifest.rs b/crates/carbon_app/src/domain/modplatforms/curseforge/manifest.rs index 115636e9f..f4a5be457 100644 --- a/crates/carbon_app/src/domain/modplatforms/curseforge/manifest.rs +++ b/crates/carbon_app/src/domain/modplatforms/curseforge/manifest.rs @@ -1,7 +1,9 @@ use anyhow::bail; use serde::{Deserialize, Serialize}; -use crate::domain::instance::info::{ModLoader, ModLoaderType, StandardVersion}; +use crate::domain::instance::info::{ + ModLoader, ModLoaderType, StandardVersion, +}; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] diff --git a/crates/carbon_app/src/domain/modplatforms/modrinth/search.rs b/crates/carbon_app/src/domain/modplatforms/modrinth/search.rs index 25503c270..a3ecce1d4 100644 --- a/crates/carbon_app/src/domain/modplatforms/modrinth/search.rs +++ b/crates/carbon_app/src/domain/modplatforms/modrinth/search.rs @@ -16,7 +16,9 @@ use crate::domain::modplatforms::modrinth::{ }; use anyhow::anyhow; use carbon_macro::into_query_parameters; -use serde::{de::DeserializeOwned, Deserialize, Deserializer, Serialize, Serializer}; +use serde::{ + de::DeserializeOwned, Deserialize, Deserializer, Serialize, Serializer, +}; use super::version::HashAlgorithm; @@ -91,7 +93,10 @@ impl FromStr for SearchFacet { fn from_str(facet: &str) -> Result { let Some((facet_type, value)) = facet.trim().split_once(':') else { - return Err(anyhow!("Improperly formatted search facet `{}`", facet)); + return Err(anyhow!( + "Improperly formatted search facet `{}`", + facet + )); }; match facet_type { "categories" => Ok(SearchFacet::Category(value.to_string())), @@ -113,10 +118,14 @@ impl TryFrom<&str> for SearchFacet { impl Display for SearchFacet { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let out = match self { - SearchFacet::Category(category) => format!("categories:{}", category), + SearchFacet::Category(category) => { + format!("categories:{}", category) + } SearchFacet::Version(version) => format!("versions:{}", version), SearchFacet::License(license) => format!("license:{}", license), - SearchFacet::ProjectType(project_type) => format!("project_type:{}", project_type), + SearchFacet::ProjectType(project_type) => { + format!("project_type:{}", project_type) + } }; write!(f, "{}", out) } @@ -147,7 +156,8 @@ where S: Serializer, T: Serialize, { - let json = serde_json::to_string(&value).map_err(serde::ser::Error::custom)?; + let json = + serde_json::to_string(&value).map_err(serde::ser::Error::custom)?; s.serialize_str(&json) } diff --git a/crates/carbon_app/src/domain/modplatforms/modrinth/version.rs b/crates/carbon_app/src/domain/modplatforms/modrinth/version.rs index a3e5c4370..1c0a596d7 100644 --- a/crates/carbon_app/src/domain/modplatforms/modrinth/version.rs +++ b/crates/carbon_app/src/domain/modplatforms/modrinth/version.rs @@ -70,9 +70,9 @@ impl TryFrom for StandardVersion { type Error = anyhow::Error; fn try_from(value: ModrinthPackDependencies) -> Result { - let minecraft_version = value - .minecraft - .ok_or_else(|| anyhow!("Modpack does not have a Minecraft version listed"))?; + let minecraft_version = value.minecraft.ok_or_else(|| { + anyhow!("Modpack does not have a Minecraft version listed") + })?; let mut modloaders = HashSet::new(); if let Some(forge_version) = value.forge { modloaders.insert(ModLoader { diff --git a/crates/carbon_app/src/domain/runtime_path.rs b/crates/carbon_app/src/domain/runtime_path.rs index be6345b5c..e234fe7c3 100644 --- a/crates/carbon_app/src/domain/runtime_path.rs +++ b/crates/carbon_app/src/domain/runtime_path.rs @@ -166,7 +166,9 @@ impl TempPath { self.0.clone() } - pub async fn maketmp(&self) -> anyhow::Result> { + pub async fn maketmp( + &self, + ) -> anyhow::Result> { let time = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .expect("time is somehow pre-epoch") @@ -196,11 +198,15 @@ impl TempPath { Err(anyhow!("Could not create tmpdir")) } - pub async fn maketmpdir(&self) -> anyhow::Result> { + pub async fn maketmpdir( + &self, + ) -> anyhow::Result> { self.maketmp().await } - pub async fn maketmpfile(&self) -> anyhow::Result> { + pub async fn maketmpfile( + &self, + ) -> anyhow::Result> { self.maketmp().await } @@ -343,7 +349,11 @@ impl Deref for RuntimePath { /// Recursivley copy from `from` to `to` except when excluded by `filter`. /// Overwrites existing files. May fail if a parent directory is filtered but children are not. -pub async fn copy_dir_filter(from: &Path, to: &Path, filter: F) -> anyhow::Result<()> +pub async fn copy_dir_filter( + from: &Path, + to: &Path, + filter: F, +) -> anyhow::Result<()> where F: for<'a> Fn(&'a Path) -> bool, { diff --git a/crates/carbon_app/src/domain/url.rs b/crates/carbon_app/src/domain/url.rs index ef77ebce5..b4672c97d 100644 --- a/crates/carbon_app/src/domain/url.rs +++ b/crates/carbon_app/src/domain/url.rs @@ -5,6 +5,7 @@ where S: Serializer, T: Serialize, { - let json = serde_json::to_string(&value).map_err(serde::ser::Error::custom)?; + let json = + serde_json::to_string(&value).map_err(serde::ser::Error::custom)?; s.serialize_str(&json) } diff --git a/crates/carbon_app/src/error/json.rs b/crates/carbon_app/src/error/json.rs index f045dc93c..39d377724 100644 --- a/crates/carbon_app/src/error/json.rs +++ b/crates/carbon_app/src/error/json.rs @@ -2,7 +2,11 @@ /// to provided context to a deserialization error. The context is only assured /// to be useful if the error was caused by a data mismatch not a syntax error or EOF. -pub fn read_json_context_back(ctx: &str, max_len: usize, string_can_end: bool) -> String { +pub fn read_json_context_back( + ctx: &str, + max_len: usize, + string_can_end: bool, +) -> String { let mut ctx: String = ctx.to_owned(); let mut token_contexts: Vec = vec![]; @@ -14,7 +18,11 @@ pub fn read_json_context_back(ctx: &str, max_len: usize, string_can_end: bool) - let mut count_string_opens = 0; let mut count_objects_found = 0; for (i, c) in ctx.char_indices().rev() { - if c == ':' && in_str && count_string_opens == 1 && last_non_whitespace_char == Some('"') { + if c == ':' + && in_str + && count_string_opens == 1 + && last_non_whitespace_char == Some('"') + { in_str = false; token_contexts.pop(); } @@ -80,7 +88,11 @@ pub fn read_json_context_back(ctx: &str, max_len: usize, string_can_end: bool) - ctx } -pub fn read_json_context_forward(ctx: &str, max_len: usize, string_can_end: bool) -> String { +pub fn read_json_context_forward( + ctx: &str, + max_len: usize, + string_can_end: bool, +) -> String { let mut ctx: String = ctx.to_owned(); let mut token_contexts: Vec = vec![]; @@ -92,7 +104,11 @@ pub fn read_json_context_forward(ctx: &str, max_len: usize, string_can_end: bool let mut count_string_opens = 0; let mut count_objects_found = 0; for (i, c) in ctx.char_indices() { - if c == ':' && in_str && count_string_opens == 1 && last_non_whitespace_char == Some('"') { + if c == ':' + && in_str + && count_string_opens == 1 + && last_non_whitespace_char == Some('"') + { in_str = false; token_contexts.pop(); } @@ -158,12 +174,18 @@ pub fn read_json_context_forward(ctx: &str, max_len: usize, string_can_end: bool ctx } -pub fn get_json_context(err: &serde_json::Error, body: &str, max_len: usize) -> String { +pub fn get_json_context( + err: &serde_json::Error, + body: &str, + max_len: usize, +) -> String { if body.is_empty() { return body.to_owned(); } - let string_can_end = body.chars().next().map(|char| char == '[' || char == '{') != Some(true); + let string_can_end = + body.chars().next().map(|char| char == '[' || char == '{') + != Some(true); let line_offset = body .char_indices() @@ -181,8 +203,10 @@ pub fn get_json_context(err: &serde_json::Error, body: &str, max_len: usize) -> let ctx_before = pre_line.to_owned() + ctx_split.0; let ctx_after = ctx_split.1.to_owned(); - let obj_before = read_json_context_back(&ctx_before, max_len, string_can_end); - let obj_after = read_json_context_forward(&ctx_after, max_len, string_can_end); + let obj_before = + read_json_context_back(&ctx_before, max_len, string_can_end); + let obj_after = + read_json_context_forward(&ctx_after, max_len, string_can_end); obj_before + "<~~ " + obj_after.as_str() } diff --git a/crates/carbon_app/src/error/mod.rs b/crates/carbon_app/src/error/mod.rs index cc60940b1..a76485abb 100644 --- a/crates/carbon_app/src/error/mod.rs +++ b/crates/carbon_app/src/error/mod.rs @@ -42,14 +42,16 @@ impl FeError { pub fn make_rspc(&self) -> rspc::Error { rspc::Error::new( rspc::ErrorCode::InternalServerError, - serde_json::to_string_pretty(self).expect("could not convert FeError to json"), + serde_json::to_string_pretty(self) + .expect("could not convert FeError to json"), ) } pub fn make_axum(&self) -> AxumError { ( axum::http::StatusCode::INTERNAL_SERVER_ERROR, - serde_json::to_string_pretty(self).expect("could not convert FeError to json"), + serde_json::to_string_pretty(self) + .expect("could not convert FeError to json"), ) } } diff --git a/crates/carbon_app/src/error/request.rs b/crates/carbon_app/src/error/request.rs index a787cde86..b9ea732ae 100644 --- a/crates/carbon_app/src/error/request.rs +++ b/crates/carbon_app/src/error/request.rs @@ -142,7 +142,10 @@ impl RequestErrorDetails { Self::from_error(error.without_url()) } - pub fn from_json_decode_error(error: serde_json::Error, body: &str) -> Self { + pub fn from_json_decode_error( + error: serde_json::Error, + body: &str, + ) -> Self { Self::MalformedResponse { details: MalformedResponseDetails::JsonDecodeError { ctx: get_json_context(&error, body, 400), @@ -169,7 +172,11 @@ impl RequestError { } } - pub fn from_json_decode_error(error: serde_json::Error, body: &str, url: &Url) -> Self { + pub fn from_json_decode_error( + error: serde_json::Error, + body: &str, + url: &Url, + ) -> Self { Self { context: RequestContext::from_url(url), error: RequestErrorDetails::from_json_decode_error(error, body), @@ -194,7 +201,9 @@ impl RequestError { #[async_trait::async_trait] pub trait GoodJsonRequestError { - async fn json_with_context(self) -> Result; + async fn json_with_context( + self, + ) -> Result; async fn json_with_context_reporting( self, ty: &'static str, @@ -203,7 +212,9 @@ pub trait GoodJsonRequestError { #[async_trait::async_trait] impl GoodJsonRequestError for reqwest::Response { - async fn json_with_context(self) -> Result { + async fn json_with_context( + self, + ) -> Result { let url = self.url().clone(); let body = self .error_for_status() @@ -211,8 +222,9 @@ impl GoodJsonRequestError for reqwest::Response { .text() .await .map_err(RequestError::from_error)?; - Ok(serde_json::from_str::(&body) - .map_err(|err| RequestError::from_json_decode_error(err, &body, &url))?) + Ok(serde_json::from_str::(&body).map_err(|err| { + RequestError::from_json_decode_error(err, &body, &url) + })?) } async fn json_with_context_reporting( @@ -258,13 +270,17 @@ impl From for FERequestError { } } RequestErrorDetails::Timeout => FERequestErrorType::Timeout, - RequestErrorDetails::ConnectionFailed => FERequestErrorType::ConnectionFailed, + RequestErrorDetails::ConnectionFailed => { + FERequestErrorType::ConnectionFailed + } RequestErrorDetails::MalformedResponse { details } => { FERequestErrorType::MalformedResponse { details: details.into(), } } - RequestErrorDetails::Unknown(x) => FERequestErrorType::Unknown(x), + RequestErrorDetails::Unknown(x) => { + FERequestErrorType::Unknown(x) + } }, } } @@ -295,12 +311,16 @@ impl From for FEMalformedResponseDetails { column, source, }, - MalformedResponseDetails::UnknownDecodeError => Self::UnknownDecodeError, + MalformedResponseDetails::UnknownDecodeError => { + Self::UnknownDecodeError + } } } } -pub fn censor_error(error: reqwest_middleware::Error) -> reqwest_middleware::Error { +pub fn censor_error( + error: reqwest_middleware::Error, +) -> reqwest_middleware::Error { match error { reqwest_middleware::Error::Reqwest(e) => { reqwest_middleware::Error::Reqwest(e.without_url()) diff --git a/crates/carbon_app/src/error/sentry.rs b/crates/carbon_app/src/error/sentry.rs index 9387f1f4b..c29007e30 100644 --- a/crates/carbon_app/src/error/sentry.rs +++ b/crates/carbon_app/src/error/sentry.rs @@ -6,8 +6,12 @@ use std::{ /// Capture an error and send it to sentry. /// Will not send an erorr of the same type more than 3 times a day. -pub fn report_volatile_error(ty: &'static str, error: anyhow::Error) -> anyhow::Error { - static TRACKER: Mutex>> = Mutex::new(None); +pub fn report_volatile_error( + ty: &'static str, + error: anyhow::Error, +) -> anyhow::Error { + static TRACKER: Mutex>> = + Mutex::new(None); let error = error.context(format!("Caught volatile error: '{ty}'")); diff --git a/crates/carbon_app/src/logger.rs b/crates/carbon_app/src/logger.rs index e7b44628a..4ad38b8e6 100644 --- a/crates/carbon_app/src/logger.rs +++ b/crates/carbon_app/src/logger.rs @@ -2,7 +2,8 @@ use std::path::Path; use tracing_appender::non_blocking::WorkerGuard; use tracing_subscriber::{ - prelude::__tracing_subscriber_SubscriberExt, util::SubscriberInitExt, EnvFilter, + prelude::__tracing_subscriber_SubscriberExt, util::SubscriberInitExt, + EnvFilter, }; fn generate_logs_filters() -> String { @@ -67,10 +68,13 @@ pub async fn setup_logger(runtime_path: &Path) -> Option { #[cfg(not(debug_assertions))] { let file_name = chrono::Local::now().format("%Y-%m-%d_%H-%M-%S"); - let file_appender = - tracing_appender::rolling::never(logs_path, format!("{}.log", file_name)); + let file_appender = tracing_appender::rolling::never( + logs_path, + format!("{}.log", file_name), + ); - let (non_blocking, guard) = tracing_appender::non_blocking(file_appender); + let (non_blocking, guard) = + tracing_appender::non_blocking(file_appender); let printer = tracing_subscriber::fmt::layer() .with_target(true) diff --git a/crates/carbon_app/src/main.rs b/crates/carbon_app/src/main.rs index 409600ff7..0afe143cb 100644 --- a/crates/carbon_app/src/main.rs +++ b/crates/carbon_app/src/main.rs @@ -109,7 +109,8 @@ async fn start_router(runtime_path: PathBuf, listener: TcpListener) { info!("Starting router"); let (invalidation_sender, _) = tokio::sync::broadcast::channel(200); - let router: Arc> = crate::api::build_rspc_router().expose().build().arced(); + let router: Arc> = + crate::api::build_rspc_router().expose().build().arced(); // We disable CORS because this is just an example. DON'T DO THIS IN PRODUCTION! let cors = CorsLayer::new() @@ -138,7 +139,8 @@ async fn start_router(runtime_path: PathBuf, listener: TcpListener) { // As soon as the server is ready, notify via stdout tokio::spawn(async move { let mut counter = 0; - let mut interval = tokio::time::interval(tokio::time::Duration::from_millis(200)); + let mut interval = + tokio::time::interval(tokio::time::Duration::from_millis(200)); let reqwest_client = reqwest::Client::new(); loop { counter += 1; @@ -180,7 +182,8 @@ struct TestEnv { impl TestEnv { async fn restart_in_place(&mut self) { let (invalidation_sender, _) = tokio::sync::broadcast::channel(200); - self.app = AppInner::new(invalidation_sender, self.tmpdir.clone()).await; + self.app = + AppInner::new(invalidation_sender, self.tmpdir.clone()).await; } } @@ -205,7 +208,8 @@ async fn setup_managers_for_test() -> TestEnv { let temp_dir = tempdir::TempDir::new("carbon_app_test").unwrap(); let temp_path = dunce::canonicalize(temp_dir.into_path()).unwrap(); info!("Test RTP: {}", temp_path.to_str().unwrap()); - let (invalidation_sender, invalidation_recv) = tokio::sync::broadcast::channel(200); + let (invalidation_sender, invalidation_recv) = + tokio::sync::broadcast::channel(200); TestEnv { tmpdir: temp_path.clone(), diff --git a/crates/carbon_app/src/managers/account/api.rs b/crates/carbon_app/src/managers/account/api.rs index 632caa797..95cebf784 100644 --- a/crates/carbon_app/src/managers/account/api.rs +++ b/crates/carbon_app/src/managers/account/api.rs @@ -12,7 +12,8 @@ use thiserror::Error; use tracing::info; use crate::error::request::{ - censor_error, MalformedResponseDetails, RequestContext, RequestError, RequestErrorDetails, + censor_error, MalformedResponseDetails, RequestContext, RequestError, + RequestErrorDetails, }; #[derive(Debug, Clone)] @@ -25,7 +26,9 @@ pub struct DeviceCode { } impl DeviceCode { - pub async fn request_code(client: &ClientWithMiddleware) -> anyhow::Result { + pub async fn request_code( + client: &ClientWithMiddleware, + ) -> anyhow::Result { #[derive(Deserialize)] struct DeviceCodeResponse { user_code: String, @@ -61,7 +64,8 @@ impl DeviceCode { verification_uri: response.verification_uri, // polling_interval: Duration::from_secs(response.interval.into()), polling_interval: Duration::from_secs(1), - expires_at: Utc::now() + chrono::Duration::seconds(response.expires_in), + expires_at: Utc::now() + + chrono::Duration::seconds(response.expires_in), }) } @@ -101,7 +105,9 @@ impl DeviceCode { match &error as &str { "authorization_pending" => continue, - "expired_token" => return Ok(Err(DeviceCodeExpiredError)), + "expired_token" => { + return Ok(Err(DeviceCodeExpiredError)) + } _ => bail!(RequestError { context: RequestContext::none(), error: RequestErrorDetails::UnexpectedStatus { @@ -129,7 +135,8 @@ impl DeviceCode { access_token: response.access_token, //id_token: response.id_token, refresh_token: response.refresh_token, - expires_at: Utc::now() + chrono::Duration::seconds(response.expires_in), + expires_at: Utc::now() + + chrono::Duration::seconds(response.expires_in), })); } _ => bail!(RequestError::from_status(&response,)), @@ -185,7 +192,8 @@ impl MsAuth { Ok(Self { access_token: response.access_token, refresh_token: response.refresh_token, - expires_at: Utc::now() + chrono::Duration::seconds(response.expires_in), + expires_at: Utc::now() + + chrono::Duration::seconds(response.expires_in), }) } } @@ -371,7 +379,8 @@ impl McAuth { Ok(Self { access_token: response.access_token, - expires_at: Utc::now() + chrono::Duration::seconds(response.expires_in), + expires_at: Utc::now() + + chrono::Duration::seconds(response.expires_in), }) } @@ -416,10 +425,12 @@ impl McAuth { Ok(jwt) => jwt.claims, Err(e) => { let error = match e.kind() { - ErrorKind::InvalidSignature | ErrorKind::ImmatureSignature => { + ErrorKind::InvalidSignature + | ErrorKind::ImmatureSignature => { McEntitlementError::InvalidSignature } - ErrorKind::InvalidToken | ErrorKind::MissingRequiredClaim(_) => { + ErrorKind::InvalidToken + | ErrorKind::MissingRequiredClaim(_) => { McEntitlementError::InvalidData } ErrorKind::MissingAlgorithm => McEntitlementError::Outdated, @@ -506,7 +517,8 @@ pub enum McEntitlement { impl McEntitlement { fn mojang_jwt_key() -> DecodingKey { // The test at the bottom of this file makes sure this unwrap is fine. - DecodingKey::from_rsa_pem(include_bytes!("mojang_jwt_signature.pem")).unwrap() + DecodingKey::from_rsa_pem(include_bytes!("mojang_jwt_signature.pem")) + .unwrap() } } diff --git a/crates/carbon_app/src/managers/account/enroll.rs b/crates/carbon_app/src/managers/account/enroll.rs index 7ef7a9224..dbbad2026 100644 --- a/crates/carbon_app/src/managers/account/enroll.rs +++ b/crates/carbon_app/src/managers/account/enroll.rs @@ -1,8 +1,9 @@ use std::sync::Arc; use super::api::{ - get_profile, DeviceCode, DeviceCodeExpiredError, FullAccount, GetProfileError, McAccount, - McAuth, McEntitlementMissingError, MsAuth, XboxAuth, XboxError, + get_profile, DeviceCode, DeviceCodeExpiredError, FullAccount, + GetProfileError, McAccount, McAuth, McEntitlementMissingError, MsAuth, + XboxAuth, XboxError, }; use anyhow::anyhow; use async_trait::async_trait; @@ -47,7 +48,10 @@ impl EnrollmentTask { let device_code = DeviceCode::request_code(&client).await?; // poll ms auth - update_status(EnrollmentStatus::PollingCode(device_code.clone())).await; + update_status(EnrollmentStatus::PollingCode( + device_code.clone(), + )) + .await; let ms_auth = device_code.poll_ms_auth(&client).await??; update_status(EnrollmentStatus::McLogin).await; @@ -61,7 +65,8 @@ impl EnrollmentTask { update_status(EnrollmentStatus::PopulateAccount).await; let account = McAccount { entitlement: mc_auth.get_entitlement(&client).await??, - profile: get_profile(&client, &mc_auth.access_token).await??, + profile: get_profile(&client, &mc_auth.access_token) + .await??, auth: mc_auth, }; @@ -123,7 +128,8 @@ impl EnrollmentTask { update_status(EnrollmentStatus::PopulateAccount).await; let account = McAccount { entitlement: mc_auth.get_entitlement(&client).await??, - profile: get_profile(&client, &mc_auth.access_token).await??, + profile: get_profile(&client, &mc_auth.access_token) + .await??, auth: mc_auth, }; diff --git a/crates/carbon_app/src/managers/account/mod.rs b/crates/carbon_app/src/managers/account/mod.rs index c29c92be1..69ef4fd00 100644 --- a/crates/carbon_app/src/managers/account/mod.rs +++ b/crates/carbon_app/src/managers/account/mod.rs @@ -8,7 +8,8 @@ use anyhow::ensure; use async_trait::async_trait; use chrono::{FixedOffset, Utc}; use prisma_client_rust::{ - chrono::DateTime, prisma_errors::query_engine::RecordNotFound, Direction, QueryError, + chrono::DateTime, prisma_errors::query_engine::RecordNotFound, Direction, + QueryError, }; use std::{ collections::HashMap, @@ -60,7 +61,10 @@ impl<'s> ManagerRef<'s, AccountManager> { .active_account_uuid) } - pub async fn set_active_uuid(self, uuid: Option) -> anyhow::Result<()> { + pub async fn set_active_uuid( + self, + uuid: Option, + ) -> anyhow::Result<()> { use db::account::WhereParam::Uuid; use db::app_configuration::SetParam::SetActiveAccountUuid; @@ -92,7 +96,9 @@ impl<'s> ManagerRef<'s, AccountManager> { /// Get the active account's details. /// /// Not exposed to the frontend on purpose. Will NOT be invalidated. - pub async fn get_active_account(&self) -> anyhow::Result> { + pub async fn get_active_account( + &self, + ) -> anyhow::Result> { use db::account::WhereParam::Uuid; let Some(uuid) = self.get_active_uuid().await? else { @@ -106,12 +112,18 @@ impl<'s> ManagerRef<'s, AccountManager> { .find_first(vec![Uuid(StringFilter::Equals(uuid))]) .exec() .await? - .ok_or_else(|| anyhow!("currenly active account could not be read from database"))?; + .ok_or_else(|| { + anyhow!( + "currenly active account could not be read from database" + ) + })?; Ok(Some(account.try_into()?)) } - async fn get_account_entries(self) -> anyhow::Result> { + async fn get_account_entries( + self, + ) -> anyhow::Result> { use db::account::OrderByParam; Ok(self @@ -146,7 +158,10 @@ impl<'s> ManagerRef<'s, AccountManager> { .collect()) } - async fn get_account(self, uuid: String) -> anyhow::Result> { + async fn get_account( + self, + uuid: String, + ) -> anyhow::Result> { use db::account::UniqueWhereParam; let account = self @@ -166,7 +181,10 @@ impl<'s> ManagerRef<'s, AccountManager> { Ok(Some(account)) } - pub async fn get_account_status(self, uuid: String) -> anyhow::Result> { + pub async fn get_account_status( + self, + uuid: String, + ) -> anyhow::Result> { let Some(mut account) = self.get_account(uuid).await? else { return Ok(None); }; @@ -299,7 +317,8 @@ impl<'s> ManagerRef<'s, AccountManager> { async fn invalidate(&self) { let app = self.app.upgrade(); let account_manager = app.account_manager(); - let mut refreshing = account_manager.currently_refreshing.write().await; + let mut refreshing = + account_manager.currently_refreshing.write().await; // this should never happen let enrollment = refreshing.get(&self.account.uuid).expect("account refresh invalidator recieved an invalidation without an active enrollemt"); let status = enrollment.status.read().await; @@ -323,7 +342,9 @@ impl<'s> ManagerRef<'s, AccountManager> { .. } = &self.account.type_ else { - panic!("account type was not microsoft during refresh"); + panic!( + "account type was not microsoft during refresh" + ); }; account_manager.add_account(FullAccount { @@ -428,8 +449,10 @@ impl<'s> ManagerRef<'s, AccountManager> { } } - let active_enrollment = - EnrollmentTask::begin(client, Invalidator(AppRef(Arc::downgrade(self.app)))); + let active_enrollment = EnrollmentTask::begin( + client, + Invalidator(AppRef(Arc::downgrade(self.app))), + ); *enrollment = Some(active_enrollment); self.app.invalidate(ENROLL_GET_STATUS, None); @@ -502,10 +525,10 @@ impl<'s> ManagerRef<'s, AccountManager> { false => None, }; - let account = self - .get_account(uuid.clone()) - .await? - .ok_or_else(|| ValidateAccountError::AccountMissing(uuid.clone()))?; + let account = + self.get_account(uuid.clone()).await?.ok_or_else(|| { + ValidateAccountError::AccountMissing(uuid.clone()) + })?; let AccountStatus::Ok { access_token: Some(access_token), @@ -513,7 +536,8 @@ impl<'s> ManagerRef<'s, AccountManager> { else { return Ok(()); }; - let profile = api::get_profile(&self.app.reqwest_client, &access_token).await; + let profile = + api::get_profile(&self.app.reqwest_client, &access_token).await; if let Some(refresh_lock) = &mut refresh_lock { **refresh_lock = Some(Instant::now() + Duration::from_secs(30)); @@ -530,7 +554,9 @@ impl<'s> ManagerRef<'s, AccountManager> { .account() .update( UniqueWhereParam::UuidEquals(uuid.clone()), - vec![SetParam::SetTokenExpires(Some(Utc::now().into()))], + vec![SetParam::SetTokenExpires(Some( + Utc::now().into(), + ))], ) .exec() .await?; @@ -589,7 +615,8 @@ impl AccountRefreshService { // wait for all additional refreshing delays to complete to avoid rate limiting loop { - let mut sleep_until = account_manager.refreshloop_sleep.lock().await; + let mut sleep_until = + account_manager.refreshloop_sleep.lock().await; match &mut *sleep_until { Some(time) => { @@ -605,7 +632,9 @@ impl AccountRefreshService { } // TODO: there's not really a way to handle an error in here - if let Ok(accounts) = account_manager.get_account_entries().await { + if let Ok(accounts) = + account_manager.get_account_entries().await + { // discard deleted accounts last_check_times = last_check_times .into_iter() @@ -624,7 +653,8 @@ impl AccountRefreshService { if !last_check_times.contains_key(&account.uuid) && account.access_token.is_some() { - last_check_times.insert(account.uuid, Instant::now()); + last_check_times + .insert(account.uuid, Instant::now()); } } @@ -651,19 +681,28 @@ impl AccountRefreshService { let account_manager = app.account_manager(); // TODO: there's not really a way to handle an error in here - if let Ok(accounts) = account_manager.get_account_entries().await { + if let Ok(accounts) = + account_manager.get_account_entries().await + { for account in accounts { // ignore badly formed account entries since we can't handle them let Ok(account) = FullAccount::try_from(account) else { continue; }; - let FullAccountType::Microsoft { token_expires, .. } = account.type_ else { + let FullAccountType::Microsoft { + token_expires, .. + } = account.type_ + else { continue; }; - if token_expires < Utc::now() - chrono::Duration::hours(1) { + if token_expires + < Utc::now() - chrono::Duration::hours(1) + { // still can't handle errors - let _ = account_manager.refresh_account(account.uuid).await; + let _ = account_manager + .refresh_account(account.uuid) + .await; break; } } @@ -733,7 +772,9 @@ pub enum FinalizeEnrollmentError { #[derive(Error, Debug)] pub enum DeleteAccountError { - #[error("attempted to delete account that is not in the account list: {0}")] + #[error( + "attempted to delete account that is not in the account list: {0}" + )] AccountDoesNotExist(String), } @@ -802,7 +843,9 @@ impl TryFrom for FullAccount { access_token, refresh_token: value.ms_refresh_token, token_expires: value.token_expires.ok_or_else(|| { - FullAccountLoadError::MissingExpiration(value.uuid.clone()) + FullAccountLoadError::MissingExpiration( + value.uuid.clone(), + ) })?, skin_id: value.skin_id, }, @@ -827,7 +870,9 @@ impl From for AccountWithStatus { FullAccountType::Offline => AccountType::Offline, }, skin_id: match &value.type_ { - FullAccountType::Microsoft { skin_id, .. } => skin_id.clone(), + FullAccountType::Microsoft { skin_id, .. } => { + skin_id.clone() + } _ => None, }, }, @@ -847,7 +892,9 @@ impl From for AccountWithStatus { access_token: Some(access_token), }, }, - FullAccountType::Offline => AccountStatus::Ok { access_token: None }, + FullAccountType::Offline => { + AccountStatus::Ok { access_token: None } + } }, } } @@ -861,7 +908,9 @@ impl From for FullAccount { type_: FullAccountType::Microsoft { access_token: value.mc.auth.access_token, refresh_token: Some(value.ms.refresh_token), - token_expires: DateTime::::from(value.mc.auth.expires_at), + token_expires: DateTime::::from( + value.mc.auth.expires_at, + ), skin_id: value.mc.profile.skin.map(|skin| skin.id), }, last_used: Utc::now().into(), diff --git a/crates/carbon_app/src/managers/account/skin.rs b/crates/carbon_app/src/managers/account/skin.rs index bb5ee36de..573e78704 100644 --- a/crates/carbon_app/src/managers/account/skin.rs +++ b/crates/carbon_app/src/managers/account/skin.rs @@ -22,7 +22,9 @@ impl ManagerRef<'_, SkinManager> { .app .prisma_client .account() - .find_unique(db::account::UniqueWhereParam::UuidEquals(uuid.clone())) + .find_unique(db::account::UniqueWhereParam::UuidEquals( + uuid.clone(), + )) .exec() .await? .ok_or_else(|| GetSkinError::AccountDoesNotExist(uuid.clone()))?; @@ -46,16 +48,23 @@ impl ManagerRef<'_, SkinManager> { }, None => { let skin = match account.access_token.as_ref() { - Some(token) => super::api::get_profile(&self.app.reqwest_client, token) - .await - .ok() - .map(Result::ok) - .flatten() - .map(|profile| profile.skin) - // use the default if there is no skin or an error occured. - .flatten() - .unwrap_or_else(|| DefaultSkin::from_uuid(uuid.clone()).make_api_skin()), - None => DefaultSkin::from_uuid(uuid.clone()).make_api_skin(), + Some(token) => { + super::api::get_profile(&self.app.reqwest_client, token) + .await + .ok() + .map(Result::ok) + .flatten() + .map(|profile| profile.skin) + // use the default if there is no skin or an error occured. + .flatten() + .unwrap_or_else(|| { + DefaultSkin::from_uuid(uuid.clone()) + .make_api_skin() + }) + } + None => { + DefaultSkin::from_uuid(uuid.clone()).make_api_skin() + } }; let skin_data = self @@ -71,12 +80,11 @@ impl ManagerRef<'_, SkinManager> { .prisma_client ._batch(( // won't error on 0 deleted - self.app - .prisma_client - .skin() - .delete_many(vec![WhereParam::Id(StringFilter::Equals( + self.app.prisma_client.skin().delete_many(vec![ + WhereParam::Id(StringFilter::Equals( skin.id.clone(), - ))]), + )), + ]), self.app.prisma_client.skin().create( skin.id.clone(), skin_data.to_vec(), @@ -84,7 +92,9 @@ impl ManagerRef<'_, SkinManager> { ), self.app.prisma_client.account().update( db::account::UniqueWhereParam::UuidEquals(uuid), - vec![db::account::SetParam::SetSkinId(Some(skin.id.clone()))], + vec![db::account::SetParam::SetSkinId(Some( + skin.id.clone(), + ))], ), )) .await?; @@ -98,7 +108,8 @@ impl ManagerRef<'_, SkinManager> { pub async fn make_head(self, uuid: String) -> anyhow::Result> { let skin = self.get_skin(uuid).await?.data; - let head = tokio::task::spawn_blocking(move || stitch_head(&skin)).await??; + let head = + tokio::task::spawn_blocking(move || stitch_head(&skin)).await??; Ok(head) } } @@ -177,7 +188,8 @@ impl DefaultSkin { _ => unreachable!("all cases that don't match have been specifically excluded in the if statement above"), }; - let alex = (is_even(7) != is_even(23)) != (is_even(15) != is_even(31)); + let alex = + (is_even(7) != is_even(23)) != (is_even(15) != is_even(31)); match alex { true => Self::Alex, diff --git a/crates/carbon_app/src/managers/download.rs b/crates/carbon_app/src/managers/download.rs index adb07b994..53c21d639 100644 --- a/crates/carbon_app/src/managers/download.rs +++ b/crates/carbon_app/src/managers/download.rs @@ -20,7 +20,10 @@ use uuid::Uuid; use crate::{ db::read_filters::StringFilter, - error::request::{MalformedResponseDetails, RequestContext, RequestError, RequestErrorDetails}, + error::request::{ + MalformedResponseDetails, RequestContext, RequestError, + RequestErrorDetails, + }, once_send::OnceSend, }; @@ -67,7 +70,10 @@ impl ManagerRef<'_, DownloadManager> { /// Cancel a download, deleting the file. /// /// If the download has already finished the files will be deleted anyway. - pub async fn cancel_download(self, handle: DownloadHandle) -> Result<(), DownloadCancelError> { + pub async fn cancel_download( + self, + handle: DownloadHandle, + ) -> Result<(), DownloadCancelError> { use crate::db::active_downloads::UniqueWhereParam; // stop the handle's drop() from being called @@ -135,7 +141,10 @@ impl ManagerRef<'_, DownloadManager> { Ok(()) } - pub async fn start_download(self, url: String) -> Result { + pub async fn start_download( + self, + url: String, + ) -> Result { use crate::db::active_downloads::WhereParam; // Lock active_downloads. Any future downloads will have to wait here. @@ -152,7 +161,9 @@ impl ManagerRef<'_, DownloadManager> { .app .prisma_client .active_downloads() - .find_first(vec![WhereParam::Url(StringFilter::Equals(url.clone()))]) + .find_first(vec![WhereParam::Url(StringFilter::Equals( + url.clone(), + ))]) .exec() .await?; @@ -180,9 +191,11 @@ impl ManagerRef<'_, DownloadManager> { .to_pathbuf() .join(&id); - let (status_send, status_recv) = watch::channel::>(None); + let (status_send, status_recv) = + watch::channel::>(None); let (cancel_send, mut cancel_recv) = mpsc::channel::<()>(1); - let (cancel_complete_send, cancel_complete_recv) = mpsc::channel::<()>(1); + let (cancel_complete_send, cancel_complete_recv) = + mpsc::channel::<()>(1); let (complete_send, complete_recv) = mpsc::channel::<()>(1); active_downloads.insert(url.clone()); @@ -200,7 +213,8 @@ impl ManagerRef<'_, DownloadManager> { let app = &app; async move { tokio::fs::create_dir_all( - path.parent().ok_or(ActiveDownloadError::MalformedPath)?, + path.parent() + .ok_or(ActiveDownloadError::MalformedPath)?, ) .await?; @@ -218,10 +232,12 @@ impl ManagerRef<'_, DownloadManager> { url: &str, start_loc: u64, ) -> anyhow::Result { - let mut builder = client.get(url).header("avoid-caching", ""); + let mut builder = + client.get(url).header("avoid-caching", ""); if start_loc != 0 { - builder = builder.header("Range", format!("bytes={start_loc}-")); + builder = builder + .header("Range", format!("bytes={start_loc}-")); } let response = builder.send().await?; @@ -233,22 +249,30 @@ impl ManagerRef<'_, DownloadManager> { Ok(response) } - let mut response = init_request(&app.reqwest_client, &url, start_loc).await?; + let mut response = + init_request(&app.reqwest_client, &url, start_loc) + .await?; match response.headers().get("content-range") { Some(range_header) => { let parse_start = || { - let mut header_str = range_header.to_str().map_err(|_| ())?; + let mut header_str = + range_header.to_str().map_err(|_| ())?; match header_str.get(0..6) { - Some("bytes ") => header_str = &header_str[6..], + Some("bytes ") => { + header_str = &header_str[6..] + } _ => return Err(()), } - let Some((range, _)) = header_str.split_once('/') else { + let Some((range, _)) = + header_str.split_once('/') + else { return Err(()); }; - let Some((start, _)) = range.split_once('-') else { + let Some((start, _)) = range.split_once('-') + else { return Err(()); }; let Ok(start) = u64::from_str(start) else { @@ -265,8 +289,12 @@ impl ManagerRef<'_, DownloadManager> { // again if we re-request with our starting point, so start from 0. start_loc = 0; file.set_len(0).await?; - response = - init_request(&app.reqwest_client, &url, 0).await?; + response = init_request( + &app.reqwest_client, + &url, + 0, + ) + .await?; } else if start < start_loc { // server gave a resume point earlier than we have, truncate the file to the // server's position. @@ -292,7 +320,8 @@ impl ManagerRef<'_, DownloadManager> { let mut writebuf = BufWriter::new(file); - let length = response.content_length().map(|x| x as u64 + start_loc); + let length = + response.content_length().map(|x| x as u64 + start_loc); let mut downloaded = start_loc; @@ -301,8 +330,10 @@ impl ManagerRef<'_, DownloadManager> { total: length, })); - while let Some(chunk) = - response.chunk().await.map_err(RequestError::from_error)? + while let Some(chunk) = response + .chunk() + .await + .map_err(RequestError::from_error)? { if let Ok(()) = cancel_recv.try_recv() { *canceled_ref = true; @@ -312,10 +343,11 @@ impl ManagerRef<'_, DownloadManager> { writebuf.write_all(&chunk).await?; downloaded += chunk.len() as u64; - let _ = status_send.send(Some(DownloadStatus::Status { - downloaded, - total: length, - })); + let _ = + status_send.send(Some(DownloadStatus::Status { + downloaded, + total: length, + })); } // will NOT be flushed on drop, so it is done manually @@ -325,7 +357,8 @@ impl ManagerRef<'_, DownloadManager> { if !*canceled_ref { // the complete flag is set first to avoid a possible race condition let _ = complete_send.send(()).await; - let _ = status_send.send(Some(DownloadStatus::Complete)); + let _ = + status_send.send(Some(DownloadStatus::Complete)); } Ok(()) @@ -350,7 +383,8 @@ impl ManagerRef<'_, DownloadManager> { match r { Ok(()) => {} Err(e) => { - let _ = status_send.send(Some(DownloadStatus::Failed(OnceSend::new(e)))); + let _ = status_send + .send(Some(DownloadStatus::Failed(OnceSend::new(e)))); } } }; @@ -516,7 +550,8 @@ mod test { async fn attempt_download() -> Result<(), DownloadError> { let app = crate::setup_managers_for_test().await; - let tmpfolder = app.settings_manager().runtime_path.get_temp().to_path(); + let tmpfolder = + app.settings_manager().runtime_path.get_temp().to_path(); tokio::fs::create_dir_all(tmpfolder).await.unwrap(); @@ -528,7 +563,9 @@ mod test { .get_temp() .to_path() .join("gdl.html"), - &mut |downloaded, total| error!("Downloaded {downloaded}/{total:?}"), + &mut |downloaded, total| { + error!("Downloaded {downloaded}/{total:?}") + }, ) .await } @@ -538,7 +575,8 @@ mod test { async fn attempt_download_twice() { let app = crate::setup_managers_for_test().await; - let tmpfolder = app.settings_manager().runtime_path.get_temp().to_path(); + let tmpfolder = + app.settings_manager().runtime_path.get_temp().to_path(); tokio::fs::create_dir_all(tmpfolder).await.unwrap(); @@ -559,7 +597,8 @@ mod test { async fn attempt_download_after_cancel() -> Result<(), DownloadStartError> { let app = crate::setup_managers_for_test().await; - let tmpfolder = app.settings_manager().runtime_path.get_temp().to_path(); + let tmpfolder = + app.settings_manager().runtime_path.get_temp().to_path(); tokio::fs::create_dir_all(tmpfolder).await.unwrap(); @@ -577,7 +616,8 @@ mod test { async fn attempt_cancel_download() { let app = crate::setup_managers_for_test().await; - let tmpfolder = app.settings_manager().runtime_path.get_temp().to_path(); + let tmpfolder = + app.settings_manager().runtime_path.get_temp().to_path(); tokio::fs::create_dir_all(tmpfolder).await.unwrap(); diff --git a/crates/carbon_app/src/managers/instance/importer/curseforge_archive.rs b/crates/carbon_app/src/managers/instance/importer/curseforge_archive.rs index 632864d97..2b3ff6d28 100644 --- a/crates/carbon_app/src/managers/instance/importer/curseforge_archive.rs +++ b/crates/carbon_app/src/managers/instance/importer/curseforge_archive.rs @@ -18,8 +18,8 @@ use crate::{ }; use super::{ - ImportScanStatus, ImportableInstance, ImporterState, InstanceImporter, InternalImportEntry, - InvalidImportEntry, + ImportScanStatus, ImportableInstance, ImporterState, InstanceImporter, + InternalImportEntry, InvalidImportEntry, }; #[derive(Debug, Clone)] @@ -85,12 +85,14 @@ impl CurseforgeArchiveImporter { .map_err(|_| Translation::InstanceImportCfZipMissingManifest)?; let mut data = Vec::new(); - manifest - .read_to_end(&mut data) - .map_err(|_| Translation::InstanceImportCfZipMalformedManifest)?; + manifest.read_to_end(&mut data).map_err(|_| { + Translation::InstanceImportCfZipMalformedManifest + })?; - let manifest = serde_json::from_slice::(&data) - .map_err(|_| Translation::InstanceImportCfZipMalformedManifest)?; + let manifest = + serde_json::from_slice::(&data).map_err(|_| { + Translation::InstanceImportCfZipMalformedManifest + })?; let murmur2 = murmurhash32::murmurhash2({ // drop whitespace @@ -105,18 +107,19 @@ impl CurseforgeArchiveImporter { let (manifest, _murmur2) = match r { Ok(t) => t, Err(reason) => { - return Ok(Some(InternalImportEntry::Invalid(InvalidImportEntry { - name, - reason, - }))) + return Ok(Some(InternalImportEntry::Invalid( + InvalidImportEntry { name, reason }, + ))) } }; if manifest.manifest_type != "minecraftModpack" { - return Ok(Some(InternalImportEntry::Invalid(InvalidImportEntry { - name, - reason: Translation::InstanceImportCfZipNotMinecraftModpack, - }))); + return Ok(Some(InternalImportEntry::Invalid( + InvalidImportEntry { + name, + reason: Translation::InstanceImportCfZipNotMinecraftModpack, + }, + ))); } // does not seem to works with packs directly downloaded from curseforge. As that's already and edge case we ignore it for now @@ -177,7 +180,11 @@ impl CurseforgeArchiveImporter { #[async_trait::async_trait] impl InstanceImporter for CurseforgeArchiveImporter { - async fn scan(&self, app: &Arc, scan_path: PathBuf) -> anyhow::Result<()> { + async fn scan( + &self, + app: &Arc, + scan_path: PathBuf, + ) -> anyhow::Result<()> { if scan_path.is_file() { if let Ok(Some(entry)) = self.scan_archive(app, scan_path).await { self.state.write().await.set_single(entry).await; @@ -192,7 +199,9 @@ impl InstanceImporter for CurseforgeArchiveImporter { while let Some(entry) = dir.next_entry().await? { if entry.metadata().await?.is_file() { futures.push(async move { - if let Ok(Some(entry)) = self.scan_archive(app, entry.path()).await { + if let Ok(Some(entry)) = + self.scan_archive(app, entry.path()).await + { self.state.write().await.push_multi(entry).await; } }) @@ -203,7 +212,10 @@ impl InstanceImporter for CurseforgeArchiveImporter { Ok(()) } - async fn get_default_scan_path(&self, _app: &Arc) -> anyhow::Result> { + async fn get_default_scan_path( + &self, + _app: &Arc, + ) -> anyhow::Result> { Ok(None) } @@ -211,7 +223,11 @@ impl InstanceImporter for CurseforgeArchiveImporter { self.state.read().await.clone().into() } - async fn begin_import(&self, app: &Arc, index: u32) -> anyhow::Result { + async fn begin_import( + &self, + app: &Arc, + index: u32, + ) -> anyhow::Result { let instance = self .state .read() @@ -221,7 +237,9 @@ impl InstanceImporter for CurseforgeArchiveImporter { .cloned() .ok_or_else(|| anyhow!("invalid importable instance index"))?; - let version = GameVersion::Standard(instance.manifest.minecraft.clone().try_into()?); + let version = GameVersion::Standard( + instance.manifest.minecraft.clone().try_into()?, + ); let instance_version_source = match &instance.meta { Some(meta) => InstanceVersionSource::ModpackWithKnownVersion( @@ -253,7 +271,8 @@ impl InstanceImporter for CurseforgeArchiveImporter { async move { let setupdir = instance_path.join(".setup"); tokio::fs::create_dir_all(&setupdir).await?; - tokio::fs::copy(&instance.path, setupdir.join("curseforge")).await?; + tokio::fs::copy(&instance.path, setupdir.join("curseforge")) + .await?; Ok(()) } diff --git a/crates/carbon_app/src/managers/instance/importer/legacy_gdlauncher.rs b/crates/carbon_app/src/managers/instance/importer/legacy_gdlauncher.rs index 4a3545cbf..d6b8ca8ba 100644 --- a/crates/carbon_app/src/managers/instance/importer/legacy_gdlauncher.rs +++ b/crates/carbon_app/src/managers/instance/importer/legacy_gdlauncher.rs @@ -7,7 +7,8 @@ use crate::{ api::translation::Translation, domain::{ instance::info::{ - CurseforgeModpack, GameVersion, ModLoader, ModLoaderType, Modpack, StandardVersion, + CurseforgeModpack, GameVersion, ModLoader, ModLoaderType, Modpack, + StandardVersion, }, vtask::VisualTaskId, }, @@ -15,8 +16,8 @@ use crate::{ }; use super::{ - ImportScanStatus, ImportableInstance, ImporterState, InstanceImporter, InternalImportEntry, - InvalidImportEntry, + ImportScanStatus, ImportableInstance, ImporterState, InstanceImporter, + InternalImportEntry, InvalidImportEntry, }; #[derive(Debug, Clone)] @@ -70,17 +71,23 @@ impl LegacyGDLauncherImporter { path, config, }))), - Err(_) => Ok(Some(InternalImportEntry::Invalid(InvalidImportEntry { - name: filename, - reason: Translation::InstanceImportLegacyBadConfigFile, - }))), + Err(_) => { + Ok(Some(InternalImportEntry::Invalid(InvalidImportEntry { + name: filename, + reason: Translation::InstanceImportLegacyBadConfigFile, + }))) + } } } } #[async_trait::async_trait] impl InstanceImporter for LegacyGDLauncherImporter { - async fn scan(&self, _app: &Arc, mut scan_path: PathBuf) -> anyhow::Result<()> { + async fn scan( + &self, + _app: &Arc, + mut scan_path: PathBuf, + ) -> anyhow::Result<()> { if !scan_path.is_dir() { return Ok(()); } @@ -108,7 +115,9 @@ impl InstanceImporter for LegacyGDLauncherImporter { while let Some(path) = dir.next_entry().await? { if path.metadata().await?.is_dir() { - if let Ok(Some(entry)) = self.scan_instance(path.path()).await { + if let Ok(Some(entry)) = + self.scan_instance(path.path()).await + { self.state.write().await.push_multi(entry).await; } } @@ -122,8 +131,12 @@ impl InstanceImporter for LegacyGDLauncherImporter { Ok(()) // TODO: invalidate on iter } - async fn get_default_scan_path(&self, _app: &Arc) -> anyhow::Result> { - let basedirs = directories::BaseDirs::new().ok_or(anyhow!("Cannot build basedirs"))?; + async fn get_default_scan_path( + &self, + _app: &Arc, + ) -> anyhow::Result> { + let basedirs = directories::BaseDirs::new() + .ok_or(anyhow!("Cannot build basedirs"))?; // old gdl did not respect the xdg basedirs spec on linux #[cfg(target_os = "linux")] @@ -138,7 +151,11 @@ impl InstanceImporter for LegacyGDLauncherImporter { self.state.read().await.clone().into() } - async fn begin_import(&self, app: &Arc, index: u32) -> anyhow::Result { + async fn begin_import( + &self, + app: &Arc, + index: u32, + ) -> anyhow::Result { let instance = self .state .read() @@ -155,7 +172,9 @@ impl InstanceImporter for LegacyGDLauncherImporter { _ => None, } .and_then(|loader_type| { - let Some(ref loader_version) = instance.config.loader.loader_version else { + let Some(ref loader_version) = + instance.config.loader.loader_version + else { return None; }; @@ -209,24 +228,33 @@ impl InstanceImporter for LegacyGDLauncherImporter { async move { let path = instance_path.join("instance"); - tokio::fs::create_dir_all(instance_path.join(".setup").join("modpack-complete")) - .await?; + tokio::fs::create_dir_all( + instance_path.join(".setup").join("modpack-complete"), + ) + .await?; // create copy-filter function in file utils for all importers - crate::domain::runtime_path::copy_dir_filter(&instance.path, &path, |path| { - match path.to_str() { - Some("config.json" | "manifest.json" | "installing.lock" | "natives") => { - false - } + crate::domain::runtime_path::copy_dir_filter( + &instance.path, + &path, + |path| match path.to_str() { + Some( + "config.json" | "manifest.json" | "installing.lock" + | "natives", + ) => false, Some(p) if Some(p) - == instance.config.background.as_ref().map(|x| x.as_str()) => + == instance + .config + .background + .as_ref() + .map(|x| x.as_str()) => { false } _ => true, - } - }) + }, + ) .await?; Ok(()) diff --git a/crates/carbon_app/src/managers/instance/importer/mod.rs b/crates/carbon_app/src/managers/instance/importer/mod.rs index 1e4cb26e3..f6c9592e9 100644 --- a/crates/carbon_app/src/managers/instance/importer/mod.rs +++ b/crates/carbon_app/src/managers/instance/importer/mod.rs @@ -13,7 +13,8 @@ use crate::{ }; use self::{ - curseforge_archive::CurseforgeArchiveImporter, legacy_gdlauncher::LegacyGDLauncherImporter, + curseforge_archive::CurseforgeArchiveImporter, + legacy_gdlauncher::LegacyGDLauncherImporter, modrinth_archive::ModrinthArchiveImporter, }; @@ -39,7 +40,10 @@ impl InstanceImportManager { } impl ManagerRef<'_, InstanceImportManager> { - pub fn set_scan_target(self, path: Option<(Entity, PathBuf)>) -> anyhow::Result<()> { + pub fn set_scan_target( + self, + path: Option<(Entity, PathBuf)>, + ) -> anyhow::Result<()> { self.scan_path .send(path) .map_err(|_| anyhow!("import scanning background task has died"))?; @@ -84,7 +88,8 @@ impl ManagerRef<'_, InstanceImportManager> { let target_changed = async { while rx.changed().await.is_ok() { - if matches!(&*rx.borrow(), Some((e, p)) if e == &entity && p == &path) { + if matches!(&*rx.borrow(), Some((e, p)) if e == &entity && p == &path) + { break; } } @@ -109,16 +114,23 @@ impl ManagerRef<'_, InstanceImportManager> { } } - pub async fn begin_import(self, index: u32) -> anyhow::Result { + pub async fn begin_import( + self, + index: u32, + ) -> anyhow::Result { match self.scanner.read().await.as_ref() { - Some((_, scanner)) => Ok(scanner.begin_import(self.app, index).await?), + Some((_, scanner)) => { + Ok(scanner.begin_import(self.app, index).await?) + } None => Err(anyhow!("scan target is not set")), } } pub async fn get_scan_path(self) -> anyhow::Result> { match self.scanner.read().await.as_ref() { - Some((_, scanner)) => Ok(scanner.get_default_scan_path(self.app).await?), + Some((_, scanner)) => { + Ok(scanner.get_default_scan_path(self.app).await?) + } None => Err(anyhow!("scan target is not set")), } } @@ -133,7 +145,9 @@ impl<'a> ManagerRef<'a, InstanceManager> { } } -#[derive(Debug, Clone, Copy, Serialize, Deserialize, EnumIter, Eq, PartialEq)] +#[derive( + Debug, Clone, Copy, Serialize, Deserialize, EnumIter, Eq, PartialEq, +)] pub enum Entity { LegacyGDLauncher, MRPack, @@ -194,10 +208,21 @@ pub struct FullImportScanStatus { #[async_trait::async_trait] pub trait InstanceImporter: std::fmt::Debug + Send + Sync { - async fn scan(&self, app: &Arc, scan_path: PathBuf) -> anyhow::Result<()>; - async fn get_default_scan_path(&self, app: &Arc) -> anyhow::Result>; + async fn scan( + &self, + app: &Arc, + scan_path: PathBuf, + ) -> anyhow::Result<()>; + async fn get_default_scan_path( + &self, + app: &Arc, + ) -> anyhow::Result>; async fn get_status(&self) -> ImportScanStatus; - async fn begin_import(&self, app: &Arc, index: u32) -> anyhow::Result; + async fn begin_import( + &self, + app: &Arc, + index: u32, + ) -> anyhow::Result; } #[derive(Debug, Clone)] @@ -231,7 +256,9 @@ impl> ImporterState { async fn get(&self, index: u32) -> Option<&T> { match self { - Self::SingleResult(InternalImportEntry::Valid(entry)) => Some(entry), + Self::SingleResult(InternalImportEntry::Valid(entry)) => { + Some(entry) + } Self::MultiResult(entries) => entries .get(index as usize) .map(|r| match r { @@ -244,19 +271,25 @@ impl> ImporterState { } } -impl> From> for ImportScanStatus { +impl> From> + for ImportScanStatus +{ fn from(value: ImporterState) -> Self { match value { ImporterState::NoResults => ImportScanStatus::NoResults, - ImporterState::SingleResult(r) => ImportScanStatus::SingleResult(r.into()), - ImporterState::MultiResult(r) => { - ImportScanStatus::MultiResult(r.into_iter().map(Into::into).collect()) + ImporterState::SingleResult(r) => { + ImportScanStatus::SingleResult(r.into()) } + ImporterState::MultiResult(r) => ImportScanStatus::MultiResult( + r.into_iter().map(Into::into).collect(), + ), } } } -impl> From> for ImportEntry { +impl> From> + for ImportEntry +{ fn from(value: InternalImportEntry) -> Self { match value { InternalImportEntry::Valid(t) => ImportEntry::Valid(t.into()), diff --git a/crates/carbon_app/src/managers/instance/importer/modrinth_archive.rs b/crates/carbon_app/src/managers/instance/importer/modrinth_archive.rs index 1debd2eb0..140673289 100644 --- a/crates/carbon_app/src/managers/instance/importer/modrinth_archive.rs +++ b/crates/carbon_app/src/managers/instance/importer/modrinth_archive.rs @@ -22,8 +22,8 @@ use crate::{ }; use super::{ - ImportScanStatus, ImportableInstance, ImporterState, InstanceImporter, InternalImportEntry, - InvalidImportEntry, + ImportScanStatus, ImportableInstance, ImporterState, InstanceImporter, + InternalImportEntry, InvalidImportEntry, }; #[derive(Debug, Clone)] @@ -84,17 +84,20 @@ impl ModrinthArchiveImporter { let mut zip = zip::ZipArchive::new(Cursor::new(&content)) .map_err(|_| Translation::InstanceImportMrpackMalformed)?; - let mut manifest = zip - .by_name("modrinth.index.json") - .map_err(|_| Translation::InstanceImportMrpackMissingManifest)?; + let mut manifest = + zip.by_name("modrinth.index.json").map_err(|_| { + Translation::InstanceImportMrpackMissingManifest + })?; let mut data = Vec::new(); - manifest - .read_to_end(&mut data) - .map_err(|_| Translation::InstanceImportMrpackMalformedManifest)?; + manifest.read_to_end(&mut data).map_err(|_| { + Translation::InstanceImportMrpackMalformedManifest + })?; let manifest = serde_json::from_slice::(&data) - .map_err(|_| Translation::InstanceImportMrpackMalformedManifest)?; + .map_err(|_| { + Translation::InstanceImportMrpackMalformedManifest + })?; let sha512 = hex::encode(<[u8; 64] as From<_>>::from( Sha512::new_with_prefix(&content).finalize(), @@ -107,10 +110,9 @@ impl ModrinthArchiveImporter { let (index, sha512) = match r { Ok(t) => t, Err(reason) => { - return Ok(Some(InternalImportEntry::Invalid(InvalidImportEntry { - name, - reason, - }))) + return Ok(Some(InternalImportEntry::Invalid( + InvalidImportEntry { name, reason }, + ))) } }; @@ -153,7 +155,11 @@ impl ModrinthArchiveImporter { #[async_trait::async_trait] impl InstanceImporter for ModrinthArchiveImporter { - async fn scan(&self, app: &Arc, scan_path: PathBuf) -> anyhow::Result<()> { + async fn scan( + &self, + app: &Arc, + scan_path: PathBuf, + ) -> anyhow::Result<()> { if scan_path.is_file() { if let Ok(Some(entry)) = self.scan_archive(app, scan_path).await { self.state.write().await.set_single(entry).await; @@ -168,7 +174,9 @@ impl InstanceImporter for ModrinthArchiveImporter { while let Some(entry) = dir.next_entry().await? { if entry.metadata().await?.is_file() { futures.push(async move { - if let Ok(Some(entry)) = self.scan_archive(app, entry.path()).await { + if let Ok(Some(entry)) = + self.scan_archive(app, entry.path()).await + { self.state.write().await.push_multi(entry).await; } }) @@ -179,7 +187,10 @@ impl InstanceImporter for ModrinthArchiveImporter { Ok(()) } - async fn get_default_scan_path(&self, _app: &Arc) -> anyhow::Result> { + async fn get_default_scan_path( + &self, + _app: &Arc, + ) -> anyhow::Result> { Ok(None) } @@ -187,7 +198,11 @@ impl InstanceImporter for ModrinthArchiveImporter { self.state.read().await.clone().into() } - async fn begin_import(&self, app: &Arc, index: u32) -> anyhow::Result { + async fn begin_import( + &self, + app: &Arc, + index: u32, + ) -> anyhow::Result { let instance = self .state .read() @@ -197,7 +212,9 @@ impl InstanceImporter for ModrinthArchiveImporter { .cloned() .ok_or_else(|| anyhow!("invalid importable instance index"))?; - let version = GameVersion::Standard(instance.index.dependencies.clone().try_into()?); + let version = GameVersion::Standard( + instance.index.dependencies.clone().try_into()?, + ); let instance_version_source = match &instance.meta { Some(meta) => InstanceVersionSource::ModpackWithKnownVersion( @@ -229,7 +246,8 @@ impl InstanceImporter for ModrinthArchiveImporter { async move { let setupdir = instance_path.join(".setup"); tokio::fs::create_dir_all(&setupdir).await?; - tokio::fs::copy(&instance.path, setupdir.join("modrinth")).await?; + tokio::fs::copy(&instance.path, setupdir.join("modrinth")) + .await?; Ok(()) } diff --git a/crates/carbon_app/src/managers/instance/installer/mod.rs b/crates/carbon_app/src/managers/instance/installer/mod.rs index 0b0e5d80d..8f0fcb794 100644 --- a/crates/carbon_app/src/managers/instance/installer/mod.rs +++ b/crates/carbon_app/src/managers/instance/installer/mod.rs @@ -11,7 +11,10 @@ use crate::{ modplatforms::{ curseforge::{ self, - filters::{ModFileParameters, ModFilesParameters, ModFilesParametersQuery}, + filters::{ + ModFileParameters, ModFilesParameters, + ModFilesParametersQuery, + }, }, modrinth::{ self, @@ -32,8 +35,12 @@ use futures::future::Future; type BoxedResourceInstaller = Box; type ResourceInstallerGetter = Box< - dyn FnOnce() -> Pin> + Send>> - + Send, + dyn FnOnce() -> Pin< + Box< + dyn Future> + + Send, + >, + > + Send, >; pub struct DependencyIterator<'iter> { @@ -71,7 +78,10 @@ pub enum ResourceFingerprint { pub trait ResourceInstaller: Sync { /// a unique ID to identify dependency loops fn id(&self) -> String; - async fn downloadable(&self, instance_path: &InstancePath) -> Option; + async fn downloadable( + &self, + instance_path: &InstancePath, + ) -> Option; fn dependencies( &self, app: &Arc, @@ -90,7 +100,10 @@ pub trait ResourceInstaller: Sync { instance_id: InstanceId, downloadable: Option, ) -> anyhow::Result<()>; - async fn rollback(&self, instance_data: &mut InstanceData) -> anyhow::Result<()>; + async fn rollback( + &self, + instance_data: &mut InstanceData, + ) -> anyhow::Result<()>; } #[async_trait::async_trait] @@ -101,7 +114,10 @@ impl ResourceInstaller for Box { } #[inline] - async fn downloadable(&self, instance_path: &InstancePath) -> Option { + async fn downloadable( + &self, + instance_path: &InstancePath, + ) -> Option { (**self).downloadable(instance_path).await } @@ -141,7 +157,10 @@ impl ResourceInstaller for Box { } #[inline] - async fn rollback(&self, instance_data: &mut InstanceData) -> anyhow::Result<()> { + async fn rollback( + &self, + instance_data: &mut InstanceData, + ) -> anyhow::Result<()> { (**self).rollback(instance_data).await } } @@ -162,13 +181,13 @@ impl InstallerRollbackContext { pub async fn rollback(&self, inciting_error: Option<&anyhow::Error>) { let instance_manager = self.app.instance_manager(); let mut instances = instance_manager.instances.write().await; - let instance = instances - .get_mut(&self.instance_id) - .expect("rollback should be called only when operating on a valid instance"); + let instance = instances.get_mut(&self.instance_id).expect( + "rollback should be called only when operating on a valid instance", + ); - let data = instance - .data_mut() - .expect("rollback should be called only when operating on a valid instance"); + let data = instance.data_mut().expect( + "rollback should be called only when operating on a valid instance", + ); let parent_name = { let lock = self.inner.lock().await; @@ -281,10 +300,11 @@ impl Installer { bail!("resource is already installed"); } - let task = VisualTask::new(Translation::InstanceTaskInstallMod { - mod_name: lock.display_name(), - instance_name: data.config.name.clone(), - }); + let task = + VisualTask::new(Translation::InstanceTaskInstallMod { + mod_name: lock.display_name(), + instance_name: data.config.name.clone(), + }); Ok::(task) }?; @@ -301,8 +321,14 @@ impl Installer { .await?; let visited_ids = Arc::new(Mutex::new(Vec::new())); let task = Arc::new(Mutex::new(task)); - self.install_inner(app, instance_id, &instance_path, &task, &visited_ids) - .await?; + self.install_inner( + app, + instance_id, + &instance_path, + &task, + &visited_ids, + ) + .await?; Ok(task_id) } @@ -337,7 +363,8 @@ impl Installer { let instance = instances .get(&instance_id) .expect("instance should still be valid"); - let instance_data = instance.data().expect("instance should still be valid"); + let instance_data = + instance.data().expect("instance should still be valid"); lock.dependencies(app, instance_data, ModChannel::Stable) }; @@ -433,13 +460,17 @@ impl Installer { if let Some(downloadable) = &downloadable { let (progress_watch_tx, mut progress_watch_rx) = - tokio::sync::watch::channel(carbon_net::Progress::new()); + tokio::sync::watch::channel( + carbon_net::Progress::new(), + ); // dropped when the sender is dropped tokio::spawn(async move { - while progress_watch_rx.changed().await.is_ok() { + while progress_watch_rx.changed().await.is_ok() + { { - let progress = progress_watch_rx.borrow(); + let progress = + progress_watch_rx.borrow(); t_download_file.update_download( progress.current_size as u32, progress.total_size as u32, @@ -447,31 +478,48 @@ impl Installer { ); } - tokio::time::sleep(Duration::from_millis(200)).await; + tokio::time::sleep(Duration::from_millis( + 200, + )) + .await; } t_download_file.complete_download(); }); - carbon_net::download_file(downloadable, Some(progress_watch_tx)).await? + carbon_net::download_file( + downloadable, + Some(progress_watch_tx), + ) + .await? } { // context to drop instance lock after install attempt let instance_manager = app_clone.instance_manager(); - let mut instances = instance_manager.instances.write().await; + let mut instances = + instance_manager.instances.write().await; let instance = instances .get_mut(&instance_id) .expect("instance should still be valid"); - let _ = instance.data_mut().expect("instance should still be valid"); + let _ = instance + .data_mut() + .expect("instance should still be valid"); let lock = inner.lock().await; - lock.finalize_install(&app_clone, instance_id, downloadable) - .await + lock.finalize_install( + &app_clone, + instance_id, + downloadable, + ) + .await }?; - app_clone.invalidate(INSTANCE_DETAILS, Some(instance_id.0.into())); + app_clone.invalidate( + INSTANCE_DETAILS, + Some(instance_id.0.into()), + ); Ok::<_, anyhow::Error>(()) })() .await; @@ -482,7 +530,9 @@ impl Installer { let rollback_lock = rollback_context.lock().await; rollback_lock .as_ref() - .expect("valid rollback context in spawned task") + .expect( + "valid rollback context in spawned task", + ) .rollback(Some(&e)) .await; @@ -523,7 +573,9 @@ impl CurseforgeModInstaller { .data; let download_url = file.download_url.clone().ok_or_else(|| { - anyhow::anyhow!("mod cannot be downloaded without privileged api key") + anyhow::anyhow!( + "mod cannot be downloaded without privileged api key" + ) })?; Ok(Self { @@ -533,9 +585,13 @@ impl CurseforgeModInstaller { }) } - pub fn from_file(file: crate::domain::modplatforms::curseforge::File) -> anyhow::Result { + pub fn from_file( + file: crate::domain::modplatforms::curseforge::File, + ) -> anyhow::Result { let download_url = file.download_url.clone().ok_or_else(|| { - anyhow::anyhow!("mod cannot be downloaded without privileged api key") + anyhow::anyhow!( + "mod cannot be downloaded without privileged api key" + ) })?; Ok(Self { @@ -552,8 +608,12 @@ impl ResourceInstaller for CurseforgeModInstaller { format!("curseforge:{}:{}", &self.file.mod_id, &self.file.id) } - async fn downloadable(&self, instance_path: &InstancePath) -> Option { - let install_path = instance_path.get_mods_path().join(&self.file.file_name); + async fn downloadable( + &self, + instance_path: &InstancePath, + ) -> Option { + let install_path = + instance_path.get_mods_path().join(&self.file.file_name); let checksums = &self .file @@ -599,7 +659,9 @@ impl ResourceInstaller for CurseforgeModInstaller { let mod_id = dep.mod_id; let game_version = game_version.clone(); - if let curseforge::FileRelationType::RequiredDependency = dep.relation_type { + if let curseforge::FileRelationType::RequiredDependency = + dep.relation_type + { installers.push(Box::new(move || { Box::pin(async move { app_clone @@ -729,7 +791,10 @@ impl ResourceInstaller for CurseforgeModInstaller { Ok(()) } - async fn rollback(&self, _instance_data: &mut InstanceData) -> anyhow::Result<()> { + async fn rollback( + &self, + _instance_data: &mut InstanceData, + ) -> anyhow::Result<()> { let mut lock = self.applied_data.lock().await; if let Some((_, downloadable)) = &*lock { match tokio::fs::try_exists(&downloadable.path).await { @@ -835,12 +900,19 @@ impl ResourceInstaller for ModrinthModInstaller { format!("modrinth:{}:{}", &self.version.project_id, &self.version.id) } - async fn downloadable(&self, instance_path: &InstancePath) -> Option { - let install_path = instance_path.get_mods_path().join(&self.file.filename); + async fn downloadable( + &self, + instance_path: &InstancePath, + ) -> Option { + let install_path = + instance_path.get_mods_path().join(&self.file.filename); let checksum = Checksum::Sha1(self.file.hashes.sha1.clone()); - Some(Downloadable::new(&self.download_url, install_path).with_checksum(Some(checksum))) + Some( + Downloadable::new(&self.download_url, install_path) + .with_checksum(Some(checksum)), + ) } fn dependencies( @@ -868,7 +940,9 @@ impl ResourceInstaller for ModrinthModInstaller { let project_id = dep.project_id.clone(); let game_version = game_version.clone(); - if let modrinth::version::DependencyType::Required = dep.dependency_type { + if let modrinth::version::DependencyType::Required = + dep.dependency_type + { if let Some(version_id) = version_id { installers.push(Box::new(move || { Box::pin(async move { @@ -879,9 +953,11 @@ impl ResourceInstaller for ModrinthModInstaller { .await .and_then(|version| { // let app_clone = Arc::clone(&self.app); - ModrinthModInstaller::from_version(version).map(|installer| { - Box::new(installer) as BoxedResourceInstaller - }) + ModrinthModInstaller::from_version(version) + .map(|installer| { + Box::new(installer) + as BoxedResourceInstaller + }) }) }) })); @@ -1011,7 +1087,10 @@ impl ResourceInstaller for ModrinthModInstaller { Ok(()) } - async fn rollback(&self, _instance_data: &mut InstanceData) -> anyhow::Result<()> { + async fn rollback( + &self, + _instance_data: &mut InstanceData, + ) -> anyhow::Result<()> { let mut lock = self.applied_data.lock().await; if let Some((_applied_mod_data, downloadable)) = &*lock { match tokio::fs::try_exists(&downloadable.path).await { diff --git a/crates/carbon_app/src/managers/instance/log.rs b/crates/carbon_app/src/managers/instance/log.rs index 91e8e73cf..a8f41b02c 100644 --- a/crates/carbon_app/src/managers/instance/log.rs +++ b/crates/carbon_app/src/managers/instance/log.rs @@ -201,7 +201,10 @@ impl GameLog { } impl ManagerRef<'_, InstanceManager> { - pub async fn create_log(self, instance_id: InstanceId) -> (GameLogId, watch::Sender) { + pub async fn create_log( + self, + instance_id: InstanceId, + ) -> (GameLogId, watch::Sender) { static LOG_ID: AtomicI32 = AtomicI32::new(0); let (log_tx, log_rx) = watch::channel(GameLog::new()); let id = GameLogId(LOG_ID.fetch_add(1, Ordering::Relaxed)); diff --git a/crates/carbon_app/src/managers/instance/mod.rs b/crates/carbon_app/src/managers/instance/mod.rs index 5f23d184a..5d5bb763a 100644 --- a/crates/carbon_app/src/managers/instance/mod.rs +++ b/crates/carbon_app/src/managers/instance/mod.rs @@ -30,7 +30,9 @@ use self::run::PersistenceManager; use super::ManagerRef; -use crate::domain::instance::{self as domain, GameLogId, GroupId, InstanceFolder, InstanceId}; +use crate::domain::instance::{ + self as domain, GameLogId, GroupId, InstanceFolder, InstanceId, +}; use domain::info; pub mod export; @@ -50,7 +52,8 @@ pub struct InstanceManager { loaded_icon: Mutex)>>, persistence_manager: PersistenceManager, import_manager: InstanceImportManager, - game_logs: RwLock)>>, + game_logs: + RwLock)>>, } impl Default for InstanceManager { @@ -111,7 +114,9 @@ impl<'s> ManagerRef<'s, InstanceManager> { .iter() .find(|instance| instance.shortpath == shortpath); - let Some(mut instance) = self.scan_instance(shortpath, path, cached).await? else { + let Some(mut instance) = + self.scan_instance(shortpath, path, cached).await? + else { continue; }; let InstanceType::Valid(data) = &instance.type_ else { @@ -195,7 +200,9 @@ impl<'s> ManagerRef<'s, InstanceManager> { match schema::parse_instance_config(&config_text) { Ok(config) => { let instance = InstanceData { - favorite: cached.map(|cached| cached.favorite).unwrap_or(false), + favorite: cached + .map(|cached| cached.favorite) + .unwrap_or(false), config, state: run::LaunchState::Inactive { failed_task: None }, icon_revision: 0, @@ -207,17 +214,24 @@ impl<'s> ManagerRef<'s, InstanceManager> { })) } Err(e) => { - let error = InvalidConfiguration::Invalid(ConfigurationParseError { - type_: match e.classify() { - JsonErrorType::Data => ConfigurationParseErrorType::Data, - JsonErrorType::Syntax => ConfigurationParseErrorType::Syntax, - JsonErrorType::Eof => ConfigurationParseErrorType::Eof, - JsonErrorType::Io => unreachable!(), - }, - line: e.line() as u32, // will panic with more lines but that dosen't really seem like a problem - message: e.to_string(), - config_text, - }); + let error = + InvalidConfiguration::Invalid(ConfigurationParseError { + type_: match e.classify() { + JsonErrorType::Data => { + ConfigurationParseErrorType::Data + } + JsonErrorType::Syntax => { + ConfigurationParseErrorType::Syntax + } + JsonErrorType::Eof => { + ConfigurationParseErrorType::Eof + } + JsonErrorType::Io => unreachable!(), + }, + line: e.line() as u32, // will panic with more lines but that dosen't really seem like a problem + message: e.to_string(), + config_text, + }); Ok(Some(Instance { shortpath, @@ -317,7 +331,11 @@ impl<'s> ManagerRef<'s, InstanceManager> { /// Move the given group to the index directly before `before`. /// If `before` is None, move to the end of the list. - pub async fn move_group(self, group: GroupId, before: Option) -> anyhow::Result<()> { + pub async fn move_group( + self, + group: GroupId, + before: Option, + ) -> anyhow::Result<()> { use db::instance_group::{SetParam, UniqueWhereParam, WhereParam}; // lock indexes while we're changing them @@ -330,20 +348,25 @@ impl<'s> ManagerRef<'s, InstanceManager> { .find_unique(UniqueWhereParam::IdEquals(*group)) .exec() .await? - .ok_or_else(|| anyhow!("GroupId is not in database, this should never happen"))? + .ok_or_else(|| { + anyhow!("GroupId is not in database, this should never happen") + })? .group_index; let target_idx = match before { - Some(target) => { - self.app - .prisma_client - .instance_group() - .find_unique(UniqueWhereParam::IdEquals(*target)) - .exec() - .await? - .ok_or_else(|| anyhow!("GroupId is not in database, this should never happen"))? - .group_index - } + Some(target) => self + .app + .prisma_client + .instance_group() + .find_unique(UniqueWhereParam::IdEquals(*target)) + .exec() + .await? + .ok_or_else(|| { + anyhow!( + "GroupId is not in database, this should never happen" + ) + })? + .group_index, None => { self.app .prisma_client @@ -452,22 +475,30 @@ impl<'s> ManagerRef<'s, InstanceManager> { let index_shifts = if start_group == target_group { vec![match (start_idx, target_idx) { - (start, target) if start < target => self.app.prisma_client.instance().update_many( - vec![ - WhereParam::GroupId(IntFilter::Equals(*target_group)), - WhereParam::Index(IntFilter::Gt(start)), - WhereParam::Index(IntFilter::Lte(target)), - ], - vec![SetParam::DecrementIndex(1)], - ), - (start, target) if start > target => self.app.prisma_client.instance().update_many( - vec![ - WhereParam::GroupId(IntFilter::Equals(*target_group)), - WhereParam::Index(IntFilter::Gte(target)), - WhereParam::Index(IntFilter::Lt(start)), - ], - vec![SetParam::IncrementIndex(1)], - ), + (start, target) if start < target => { + self.app.prisma_client.instance().update_many( + vec![ + WhereParam::GroupId(IntFilter::Equals( + *target_group, + )), + WhereParam::Index(IntFilter::Gt(start)), + WhereParam::Index(IntFilter::Lte(target)), + ], + vec![SetParam::DecrementIndex(1)], + ) + } + (start, target) if start > target => { + self.app.prisma_client.instance().update_many( + vec![ + WhereParam::GroupId(IntFilter::Equals( + *target_group, + )), + WhereParam::Index(IntFilter::Gte(target)), + WhereParam::Index(IntFilter::Lt(start)), + ], + vec![SetParam::IncrementIndex(1)], + ) + } _ => return Ok(()), }] } else { @@ -527,7 +558,9 @@ impl<'s> ManagerRef<'s, InstanceManager> { .app .prisma_client .instance_group() - .find_first(vec![WhereParam::Id(IntFilter::Equals(groupid))]) + .find_first(vec![WhereParam::Id(IntFilter::Equals( + groupid, + ))]) .exec() .await?; @@ -590,7 +623,9 @@ impl<'s> ManagerRef<'s, InstanceManager> { .app .prisma_client .instance_group() - .find_first(vec![WhereParam::Name(StringFilter::Equals(name.clone()))]) + .find_first(vec![WhereParam::Name(StringFilter::Equals( + name.clone(), + ))]) .exec() .await?; @@ -629,12 +664,11 @@ impl<'s> ManagerRef<'s, InstanceManager> { .prisma_client ._batch(( // delete any existing entry at the same shortpath - self.app - .prisma_client - .instance() - .delete_many(vec![WhereParam::Shortpath(StringFilter::Contains( + self.app.prisma_client.instance().delete_many(vec![ + WhereParam::Shortpath(StringFilter::Contains( shortpath.clone(), - ))]), + )), + ]), self.app.prisma_client.instance().create( name, shortpath, @@ -665,7 +699,11 @@ impl<'s> ManagerRef<'s, InstanceManager> { Ok(()) } - pub async fn set_favorite(self, instance_id: InstanceId, favorite: bool) -> anyhow::Result<()> { + pub async fn set_favorite( + self, + instance_id: InstanceId, + favorite: bool, + ) -> anyhow::Result<()> { use db::instance::{SetParam, UniqueWhereParam}; let mut instances = self.instances.write().await; @@ -696,7 +734,10 @@ impl<'s> ManagerRef<'s, InstanceManager> { Ok(()) } - async fn next_folder(self, name: &str) -> anyhow::Result<(String, PathBuf)> { + async fn next_folder( + self, + name: &str, + ) -> anyhow::Result<(String, PathBuf)> { if name.is_empty() { bail!("Attempted to find an instance directory name for an unnamed instance"); } @@ -727,10 +768,11 @@ impl<'s> ManagerRef<'s, InstanceManager> { let name = &name[0..usize::min(name.len(), 28)]; // sanitize any illegal filenames - let mut name = match ILLEGAL_NAMES.contains(&(&name.to_lowercase() as &str)) { - true => format!("_{name}"), - false => name.to_string(), - }; + let mut name = + match ILLEGAL_NAMES.contains(&(&name.to_lowercase() as &str)) { + true => format!("_{name}"), + false => name.to_string(), + }; // stop us from making hidden files on macos/linux ('~' disallowed for sanity) if name.starts_with('.') || name.starts_with('~') { @@ -787,9 +829,9 @@ impl<'s> ManagerRef<'s, InstanceManager> { } pub async fn load_icon(self, icon: PathBuf) -> anyhow::Result> { - let data = tokio::fs::read(icon.clone()) - .await - .with_context(|| format!("Reading file `{}`", icon.to_string_lossy()))?; + let data = tokio::fs::read(icon.clone()).await.with_context(|| { + format!("Reading file `{}`", icon.to_string_lossy()) + })?; let extension = match icon.extension() { Some(ext) => ext, @@ -823,7 +865,8 @@ impl<'s> ManagerRef<'s, InstanceManager> { .bytes() .await?; - *self.loaded_icon.lock().await = Some((format!("icon.{extension}"), data.to_vec())); + *self.loaded_icon.lock().await = + Some((format!("icon.{extension}"), data.to_vec())); Ok(()) } @@ -836,9 +879,14 @@ impl<'s> ManagerRef<'s, InstanceManager> { version: InstanceVersionSource, notes: String, ) -> anyhow::Result { - self.create_instance_ext(group, name, use_loaded_icon, version, notes, |_| async { - Ok(()) - }) + self.create_instance_ext( + group, + name, + use_loaded_icon, + version, + notes, + |_| async { Ok(()) }, + ) .await } @@ -865,7 +913,8 @@ impl<'s> ManagerRef<'s, InstanceManager> { tokio::fs::create_dir(tmpdir.join("instance")).await?; - let icon = match (use_loaded_icon, self.loaded_icon.lock().await.take()) { + let icon = match (use_loaded_icon, self.loaded_icon.lock().await.take()) + { (true, Some((path, data))) => { tokio::fs::write(tmpdir.join(&path), data) .await @@ -879,9 +928,10 @@ impl<'s> ManagerRef<'s, InstanceManager> { let (version, modpack) = match version { InstanceVersionSource::Version(version) => (Some(version), None), InstanceVersionSource::Modpack(modpack) => (None, Some(modpack)), - InstanceVersionSource::ModpackWithKnownVersion(version, modpack) => { - (Some(version), Some(modpack)) - } + InstanceVersionSource::ModpackWithKnownVersion( + version, + modpack, + ) => (Some(version), Some(modpack)), }; let info = info::Instance { @@ -973,24 +1023,26 @@ impl<'s> ManagerRef<'s, InstanceManager> { let mut info = data.config.clone(); if let Some(use_loaded_icon) = update.use_loaded_icon { - let icon = match (use_loaded_icon, self.loaded_icon.lock().await.take()) { - (true, Some((ipath, data))) => { - tokio::fs::write(path.join(&ipath), data) - .await - .context("saving instance icon")?; - - if let InstanceIcon::RelativePath(oldpath) = &info.icon { - if *oldpath != ipath { - tokio::fs::remove_file(path.join(oldpath)) - .await - .context("removing old instance icon")?; + let icon = + match (use_loaded_icon, self.loaded_icon.lock().await.take()) { + (true, Some((ipath, data))) => { + tokio::fs::write(path.join(&ipath), data) + .await + .context("saving instance icon")?; + + if let InstanceIcon::RelativePath(oldpath) = &info.icon + { + if *oldpath != ipath { + tokio::fs::remove_file(path.join(oldpath)) + .await + .context("removing old instance icon")?; + } } - } - InstanceIcon::RelativePath(ipath) - } - _ => InstanceIcon::Default, - }; + InstanceIcon::RelativePath(ipath) + } + _ => InstanceIcon::Default, + }; info.icon = icon; data.icon_revision += 1; @@ -1011,10 +1063,9 @@ impl<'s> ManagerRef<'s, InstanceManager> { Some(info::GameVersion::Standard(info::StandardVersion { release: version, modloaders: match &info.game_configuration.version { - Some(info::GameVersion::Standard(info::StandardVersion { - modloaders, - .. - })) => modloaders.clone(), + Some(info::GameVersion::Standard( + info::StandardVersion { modloaders, .. }, + )) => modloaders.clone(), _ => HashSet::new(), }, })); @@ -1025,10 +1076,9 @@ impl<'s> ManagerRef<'s, InstanceManager> { info.game_configuration.version = Some(info::GameVersion::Standard(info::StandardVersion { release: match &info.game_configuration.version { - Some(info::GameVersion::Standard(info::StandardVersion { - release, - .. - })) => release.clone(), + Some(info::GameVersion::Standard( + info::StandardVersion { release, .. }, + )) => release.clone(), _ => bail!("custom versions are not yet supported"), }, modloaders: match modloader { @@ -1147,7 +1197,10 @@ impl<'s> ManagerRef<'s, InstanceManager> { Ok(()) } - pub async fn delete_instance(self, instance_id: InstanceId) -> anyhow::Result<()> { + pub async fn delete_instance( + self, + instance_id: InstanceId, + ) -> anyhow::Result<()> { let mut instances = self.instances.write().await; let instance = instances .get(&instance_id) @@ -1201,7 +1254,8 @@ impl<'s> ManagerRef<'s, InstanceManager> { .group_id; let mut new_info = instance.data()?.config.clone(); - let (new_shortpath, new_path) = self.next_folder(&instance.shortpath).await?; + let (new_shortpath, new_path) = + self.next_folder(&instance.shortpath).await?; new_info.name = name; let path = self @@ -1285,13 +1339,23 @@ impl<'s> ManagerRef<'s, InstanceManager> { InstanceFolder::Data => path.get_data_path().to_path_buf(), InstanceFolder::Mods => path.get_mods_path().to_path_buf(), InstanceFolder::Configs => path.get_config_path().to_path_buf(), - InstanceFolder::Screenshots => path.get_screenshots_path().to_path_buf(), + InstanceFolder::Screenshots => { + path.get_screenshots_path().to_path_buf() + } InstanceFolder::Saves => path.get_saves_path().to_path_buf(), InstanceFolder::Logs => path.get_logs_path().to_path_buf(), - InstanceFolder::CrashReports => path.get_crash_reports_path().to_path_buf(), - InstanceFolder::ResourcePacks => path.get_resourcepacks_path().to_path_buf(), - InstanceFolder::TexturePacks => path.get_texturepacks_path().to_path_buf(), - InstanceFolder::ShaderPacks => path.get_shaderpacks_path().to_path_buf(), + InstanceFolder::CrashReports => { + path.get_crash_reports_path().to_path_buf() + } + InstanceFolder::ResourcePacks => { + path.get_resourcepacks_path().to_path_buf() + } + InstanceFolder::TexturePacks => { + path.get_texturepacks_path().to_path_buf() + } + InstanceFolder::ShaderPacks => { + path.get_shaderpacks_path().to_path_buf() + } }; if !path.is_dir() { @@ -1344,16 +1408,19 @@ impl<'s> ManagerRef<'s, InstanceManager> { .prisma_client ._batch(( self.app.prisma_client.instance().update_many( - vec![instance::WhereParam::GroupId(IntFilter::Equals(*group))], + vec![instance::WhereParam::GroupId(IntFilter::Equals( + *group, + ))], vec![ instance::SetParam::SetGroupId(*default_group), - instance::SetParam::IncrementIndex(base_index as i32), + instance::SetParam::IncrementIndex( + base_index as i32, + ), ], ), - self.app - .prisma_client - .instance_group() - .delete(instance_group::UniqueWhereParam::IdEquals(*group)), + self.app.prisma_client.instance_group().delete( + instance_group::UniqueWhereParam::IdEquals(*group), + ), )) .await?; } else { @@ -1388,13 +1455,22 @@ impl<'s> ManagerRef<'s, InstanceManager> { favorite: instance.favorite, name: instance.config.name.clone(), version: match &instance.config.game_configuration.version { - Some(info::GameVersion::Standard(version)) => Some(version.release.clone()), + Some(info::GameVersion::Standard(version)) => { + Some(version.release.clone()) + } Some(info::GameVersion::Custom(custom)) => Some(custom.clone()), None => None, }, modpack: instance.config.modpack.clone(), - global_java_args: instance.config.game_configuration.global_java_args, - extra_java_args: instance.config.game_configuration.extra_java_args.clone(), + global_java_args: instance + .config + .game_configuration + .global_java_args, + extra_java_args: instance + .config + .game_configuration + .extra_java_args + .clone(), memory: instance.config.game_configuration.memory, last_played: instance.config.last_played, seconds_played: instance.config.seconds_played as u32, @@ -1460,7 +1536,10 @@ impl<'s> ManagerRef<'s, InstanceManager> { }) } - async fn next_instance_index(self, group: GroupId) -> anyhow::Result> { + async fn next_instance_index( + self, + group: GroupId, + ) -> anyhow::Result> { use db::instance::WhereParam; let guard = self.manager.index_lock.lock().await; @@ -1577,7 +1656,9 @@ impl InstanceType { } } - pub fn data_mut(&mut self) -> Result<&mut InstanceData, InvalidInstanceDataError> { + pub fn data_mut( + &mut self, + ) -> Result<&mut InstanceData, InvalidInstanceDataError> { match self { Self::Valid(data) => Ok(data), Self::Invalid(_) => Err(InvalidInstanceDataError), @@ -1590,7 +1671,9 @@ impl Instance { self.type_.data() } - pub fn data_mut(&mut self) -> Result<&mut InstanceData, InvalidInstanceDataError> { + pub fn data_mut( + &mut self, + ) -> Result<&mut InstanceData, InvalidInstanceDataError> { self.type_.data_mut() } } @@ -1669,8 +1752,8 @@ mod test { db::{self, read_filters::IntFilter, PrismaClient}, domain::instance::{info, InstanceSettingsUpdate}, managers::instance::{ - GroupId, InstanceId, InstanceMoveTarget, ListGroup, ListInstance, ListInstanceStatus, - ValidListInstance, + GroupId, InstanceId, InstanceMoveTarget, ListGroup, ListInstance, + ListInstanceStatus, ValidListInstance, }, }; @@ -1680,7 +1763,9 @@ mod test { async fn move_groups() -> anyhow::Result<()> { let app = crate::setup_managers_for_test().await; - async fn get_ordered_groups(prisma_client: &PrismaClient) -> anyhow::Result> { + async fn get_ordered_groups( + prisma_client: &PrismaClient, + ) -> anyhow::Result> { use crate::db::instance_group::OrderByParam; Ok(prisma_client @@ -1797,7 +1882,11 @@ mod test { async move { let id = app .instance_manager() - .add_instance(shortpath.to_string(), shortpath.to_string(), group) + .add_instance( + shortpath.to_string(), + shortpath.to_string(), + group, + ) .await?; Ok::<_, anyhow::Error>(id) @@ -1830,7 +1919,10 @@ mod test { // move 1 to end of list app.instance_manager() - .move_instance(group0_instances[1], InstanceMoveTarget::EndOfGroup(group0)) + .move_instance( + group0_instances[1], + InstanceMoveTarget::EndOfGroup(group0), + ) .await?; group0_instances = [ @@ -1846,7 +1938,10 @@ mod test { // move 0 to end of list app.instance_manager() - .move_instance(group0_instances[0], InstanceMoveTarget::EndOfGroup(group0)) + .move_instance( + group0_instances[0], + InstanceMoveTarget::EndOfGroup(group0), + ) .await?; group0_instances = [ @@ -1925,7 +2020,10 @@ mod test { // move 0:0 to end of group 1 app.instance_manager() - .move_instance(group0_instances[0], InstanceMoveTarget::EndOfGroup(group1)) + .move_instance( + group0_instances[0], + InstanceMoveTarget::EndOfGroup(group1), + ) .await?; let group1_instances = [ @@ -1962,7 +2060,11 @@ mod test { .create_group(String::from("foo")) .await?; app.instance_manager() - .add_instance(String::from("baz"), String::from("baz"), default_group) + .add_instance( + String::from("baz"), + String::from("baz"), + default_group, + ) .await?; app.instance_manager() .add_instance(String::from("bar"), String::from("bar"), group) @@ -2048,7 +2150,8 @@ mod test { let mut app = crate::setup_managers_for_test().await; // create - let default_group_id = app.instance_manager().get_default_group().await?; + let default_group_id = + app.instance_manager().get_default_group().await?; let default_group = &app.instance_manager().list_groups().await?[0]; let instance_id = app .instance_manager() diff --git a/crates/carbon_app/src/managers/instance/mods.rs b/crates/carbon_app/src/managers/instance/mods.rs index e85fbfd3f..92aafede9 100644 --- a/crates/carbon_app/src/managers/instance/mods.rs +++ b/crates/carbon_app/src/managers/instance/mods.rs @@ -2,8 +2,8 @@ use anyhow::bail; use thiserror::Error; use crate::db::{ - curse_forge_mod_cache as cfdb, mod_file_cache as fcdb, mod_metadata as metadb, - modrinth_mod_cache as mrdb, + curse_forge_mod_cache as cfdb, mod_file_cache as fcdb, + mod_metadata as metadb, modrinth_mod_cache as mrdb, }; use crate::domain::instance as domain; use crate::domain::instance::info::ModLoaderType; @@ -15,7 +15,10 @@ use super::{ }; impl ManagerRef<'_, InstanceManager> { - pub async fn list_mods(self, instance_id: InstanceId) -> anyhow::Result> { + pub async fn list_mods( + self, + instance_id: InstanceId, + ) -> anyhow::Result> { { let instances = self.instances.read().await; if instances.get(&instance_id).is_none() { @@ -31,8 +34,14 @@ impl ManagerRef<'_, InstanceManager> { .with( fcdb::metadata::fetch() .with(metadb::logo_image::fetch()) - .with(metadb::curseforge::fetch().with(cfdb::logo_image::fetch())) - .with(metadb::modrinth::fetch().with(mrdb::logo_image::fetch())), + .with( + metadb::curseforge::fetch() + .with(cfdb::logo_image::fetch()), + ) + .with( + metadb::modrinth::fetch() + .with(mrdb::logo_image::fetch()), + ), ) .exec() .await? @@ -41,24 +50,28 @@ impl ManagerRef<'_, InstanceManager> { id: m.id, filename: m.filename, enabled: m.enabled, - metadata: m.metadata.as_ref().map(|m| domain::ModFileMetadata { - modid: m.modid.clone(), - name: m.name.clone(), - version: m.version.clone(), - description: m.description.clone(), - authors: m.authors.clone(), - modloaders: m - .modloaders - .split(',') - // ignore unknown modloaders - .flat_map(|loader| ModLoaderType::try_from(loader).ok()) - .collect::>(), - has_image: m - .logo_image - .as_ref() - .map(|v| v.as_ref().map(|_| ())) - .flatten() - .is_some(), + metadata: m.metadata.as_ref().map(|m| { + domain::ModFileMetadata { + modid: m.modid.clone(), + name: m.name.clone(), + version: m.version.clone(), + description: m.description.clone(), + authors: m.authors.clone(), + modloaders: m + .modloaders + .split(',') + // ignore unknown modloaders + .flat_map(|loader| { + ModLoaderType::try_from(loader).ok() + }) + .collect::>(), + has_image: m + .logo_image + .as_ref() + .map(|v| v.as_ref().map(|_| ())) + .flatten() + .is_some(), + } }), curseforge: m .metadata @@ -80,8 +93,8 @@ impl ManagerRef<'_, InstanceManager> { .flatten() .is_some(), }), - modrinth: m.metadata.and_then(|m| m.modrinth).flatten().map(|m| { - domain::ModrinthModMetadata { + modrinth: m.metadata.and_then(|m| m.modrinth).flatten().map( + |m| domain::ModrinthModMetadata { project_id: m.project_id, version_id: m.version_id, title: m.title, @@ -95,8 +108,8 @@ impl ManagerRef<'_, InstanceManager> { .map(|row| row.data.as_ref().map(|_| ())) .flatten() .is_some(), - } - }), + }, + ), }); Ok(mods.collect::>()) @@ -168,7 +181,11 @@ impl ManagerRef<'_, InstanceManager> { Ok(()) } - pub async fn delete_mod(self, instance_id: InstanceId, id: String) -> anyhow::Result<()> { + pub async fn delete_mod( + self, + instance_id: InstanceId, + id: String, + ) -> anyhow::Result<()> { let instances = self.instances.read().await; let instance = instances .get(&instance_id) @@ -219,9 +236,10 @@ impl ManagerRef<'_, InstanceManager> { project_id: u32, file_id: u32, ) -> anyhow::Result { - let installer = CurseforgeModInstaller::create(self.app, project_id, file_id) - .await? - .into_installer(); + let installer = + CurseforgeModInstaller::create(self.app, project_id, file_id) + .await? + .into_installer(); let task_id = installer.install(self.app, instance_id).await?; @@ -234,9 +252,10 @@ impl ManagerRef<'_, InstanceManager> { project_id: String, version_id: String, ) -> anyhow::Result { - let installer = ModrinthModInstaller::create(self.app, project_id, version_id) - .await? - .into_installer(); + let installer = + ModrinthModInstaller::create(self.app, project_id, version_id) + .await? + .into_installer(); let task_id = installer.install(self.app, instance_id).await?; @@ -262,8 +281,14 @@ impl ManagerRef<'_, InstanceManager> { .with( fcdb::metadata::fetch() .with(metadb::logo_image::fetch()) - .with(metadb::curseforge::fetch().with(cfdb::logo_image::fetch())) - .with(metadb::modrinth::fetch().with(mrdb::logo_image::fetch())), + .with( + metadb::curseforge::fetch() + .with(cfdb::logo_image::fetch()), + ) + .with( + metadb::modrinth::fetch() + .with(mrdb::logo_image::fetch()), + ), ) .exec() .await? diff --git a/crates/carbon_app/src/managers/instance/run.rs b/crates/carbon_app/src/managers/instance/run.rs index fd5be0a6f..6dfcc7287 100644 --- a/crates/carbon_app/src/managers/instance/run.rs +++ b/crates/carbon_app/src/managers/instance/run.rs @@ -40,7 +40,9 @@ use crate::{ }, }; -use super::{InstanceId, InstanceManager, InstanceType, InvalidInstanceIdError}; +use super::{ + InstanceId, InstanceManager, InstanceType, InvalidInstanceIdError, +}; #[derive(Debug)] pub struct PersistenceManager { @@ -55,7 +57,11 @@ impl PersistenceManager { } } type InstanceCallback = Box< - dyn FnOnce(Subtask) -> Pin> + Send>> + Send, + dyn FnOnce( + Subtask, + ) -> Pin< + Box> + Send>, + > + Send, >; impl ManagerRef<'_, InstanceManager> { @@ -72,7 +78,9 @@ impl ManagerRef<'_, InstanceManager> { .ok_or(InvalidInstanceIdError(instance_id))?; let InstanceType::Valid(data) = &mut instance.type_ else { - return Err(anyhow!("Instance {instance_id} is not in a valid state")); + return Err(anyhow!( + "Instance {instance_id} is not in a valid state" + )); }; match &data.state { @@ -104,7 +112,8 @@ impl ManagerRef<'_, InstanceManager> { .map(|c| (c.xms as u16, c.xmx as u16))?, }; - let global_java_args = match config.game_configuration.global_java_args { + let global_java_args = match config.game_configuration.global_java_args + { true => self .app .settings_manager() @@ -866,7 +875,8 @@ impl ManagerRef<'_, InstanceManager> { let start_time = Utc::now(); - let (log_id, log) = app.instance_manager().create_log(instance_id).await; + let (log_id, log) = + app.instance_manager().create_log(instance_id).await; let _ = app.instance_manager() .change_launch_state( instance_id, @@ -946,7 +956,10 @@ impl ManagerRef<'_, InstanceManager> { last_stored_time = now; let r = app .instance_manager() - .update_playtime(instance_id, diff.num_seconds() as u64) + .update_playtime( + instance_id, + diff.num_seconds() as u64, + ) .await; if let Err(e) = r { tracing::error!({ error = ?e }, "error updating instance playtime"); @@ -966,7 +979,8 @@ impl ManagerRef<'_, InstanceManager> { .instance_manager() .update_playtime( instance_id, - (Utc::now() - last_stored_time).num_seconds() as u64, + (Utc::now() - last_stored_time).num_seconds() + as u64, ) .await; if let Err(e) = r { @@ -974,7 +988,9 @@ impl ManagerRef<'_, InstanceManager> { } if let Ok(exitcode) = child.wait().await { - log.send_modify(|log| log.push(EntryType::System, &exitcode.to_string())); + log.send_modify(|log| { + log.push(EntryType::System, &exitcode.to_string()) + }); } let _ = app.rich_presence_manager().stop_activity().await; @@ -1024,7 +1040,10 @@ impl ManagerRef<'_, InstanceManager> { Ok((&instance.data()?.state).into()) } - pub async fn kill_instance(self, instance_id: InstanceId) -> anyhow::Result<()> { + pub async fn kill_instance( + self, + instance_id: InstanceId, + ) -> anyhow::Result<()> { let instances = self.instances.read().await; let instance = instances .get(&instance_id) @@ -1108,10 +1127,12 @@ mod test { app.instance_manager().get_default_group().await?, String::from("test"), false, - InstanceVersionSource::Version(info::GameVersion::Standard(StandardVersion { - release: String::from("1.16.5"), - modloaders: HashSet::new(), - })), + InstanceVersionSource::Version(info::GameVersion::Standard( + StandardVersion { + release: String::from("1.16.5"), + modloaders: HashSet::new(), + }, + )), String::new(), ) .await?; @@ -1127,23 +1148,25 @@ mod test { .prepare_game(instance_id, Some(account), None) .await?; - let task = match app.instance_manager().get_launch_state(instance_id).await? { - domain::LaunchState::Preparing(taskid) => taskid, - _ => unreachable!(), - }; + let task = + match app.instance_manager().get_launch_state(instance_id).await? { + domain::LaunchState::Preparing(taskid) => taskid, + _ => unreachable!(), + }; app.task_manager().wait_with_log(task).await?; app.wait_for_invalidation(keys::instance::INSTANCE_DETAILS) .await?; tracing::info!("Task exited"); - let log_id = match app.instance_manager().get_launch_state(instance_id).await? { - domain::LaunchState::Inactive { .. } => { - tracing::info!("Game not running"); - return Ok(()); - } - domain::LaunchState::Running { log_id, .. } => log_id, - _ => unreachable!(), - }; + let log_id = + match app.instance_manager().get_launch_state(instance_id).await? { + domain::LaunchState::Inactive { .. } => { + tracing::info!("Game not running"); + return Ok(()); + } + domain::LaunchState::Running { log_id, .. } => log_id, + _ => unreachable!(), + }; let mut log = app.instance_manager().get_log(log_id).await?; diff --git a/crates/carbon_app/src/managers/instance/schema/mod.rs b/crates/carbon_app/src/managers/instance/schema/mod.rs index 5abcdc10a..b931996c2 100644 --- a/crates/carbon_app/src/managers/instance/schema/mod.rs +++ b/crates/carbon_app/src/managers/instance/schema/mod.rs @@ -11,7 +11,9 @@ enum InstanceConfig { V1(v1::Instance), } -pub fn parse_instance_config(config: &str) -> Result { +pub fn parse_instance_config( + config: &str, +) -> Result { let config = serde_json::from_str::(config)?; Ok(match config { @@ -19,6 +21,8 @@ pub fn parse_instance_config(config: &str) -> Result Result { +pub fn make_instance_config( + info: info::Instance, +) -> Result { serde_json::to_string_pretty(&InstanceConfig::V1(info.into())) } diff --git a/crates/carbon_app/src/managers/java/discovery/finder.rs b/crates/carbon_app/src/managers/java/discovery/finder.rs index d21f5d1c0..12fc6be17 100644 --- a/crates/carbon_app/src/managers/java/discovery/finder.rs +++ b/crates/carbon_app/src/managers/java/discovery/finder.rs @@ -10,7 +10,8 @@ async fn load_java_paths_from_env() -> anyhow::Result> { for env_var in SEARCH_ENV_VARS.iter() { let env_path = std::env::var(env_var); if let Ok(env_path) = env_path { - let paths: Vec<_> = env_path.split(PATH_SEPARATOR).map(PathBuf::from).collect(); + let paths: Vec<_> = + env_path.split(PATH_SEPARATOR).map(PathBuf::from).collect(); for path in paths { java_paths.extend(search_java_binary_in_path(path)); } @@ -45,8 +46,12 @@ pub(super) async fn find_java_paths() -> Vec { let library_jvm_java = library_jvm_java.path(); javas.extend( vec![ - search_java_binary_in_path(library_jvm_java.join("Contents/Home")), - search_java_binary_in_path(library_jvm_java.join("Contents/Home/jre")), + search_java_binary_in_path( + library_jvm_java.join("Contents/Home"), + ), + search_java_binary_in_path( + library_jvm_java.join("Contents/Home/jre"), + ), ] .concat(), ); @@ -54,7 +59,8 @@ pub(super) async fn find_java_paths() -> Vec { } // System Library JVM - let system_library_jvm_dir = PathBuf::from("/System/Library/Java/JavaVirtualMachines"); + let system_library_jvm_dir = + PathBuf::from("/System/Library/Java/JavaVirtualMachines"); let system_library_jvm_javas = std::fs::read_dir(system_library_jvm_dir); if let Ok(system_library_jvm_javas) = system_library_jvm_javas { for system_library_jvm_java in system_library_jvm_javas.flatten() { @@ -62,8 +68,12 @@ pub(super) async fn find_java_paths() -> Vec { javas.extend( vec![ - search_java_binary_in_path(system_library_jvm_java.join("Contents/Home")), - search_java_binary_in_path(system_library_jvm_java.join("Contents/Commands")), + search_java_binary_in_path( + system_library_jvm_java.join("Contents/Home"), + ), + search_java_binary_in_path( + system_library_jvm_java.join("Contents/Commands"), + ), ] .concat(), ); @@ -118,11 +128,15 @@ fn read_registry_key( if let Some(additional_keypath) = additional_keypath { let subkeys = key_reg.enum_keys(); for subkey in subkeys.flatten() { - let joined_subkey = format!("{}\\{}\\{}", key, subkey, additional_keypath); + let joined_subkey = + format!("{}\\{}\\{}", key, subkey, additional_keypath); let subkey_reg = hkcu.open_subkey(&joined_subkey)?; - let subkey_reg_value: std::result::Result = subkey_reg.get_value(value); + let subkey_reg_value: std::result::Result = + subkey_reg.get_value(value); if let Ok(registry_str) = subkey_reg_value { - results.extend(search_java_binary_in_path(PathBuf::from(registry_str))); + results.extend(search_java_binary_in_path(PathBuf::from( + registry_str, + ))); } } } else { @@ -204,7 +218,8 @@ pub(super) async fn find_java_paths() -> Vec { } // Load from disk options - let potential_parent_dirs = vec!["C:/Program Files/Java", "C:/Program Files (x86)/Java"]; + let potential_parent_dirs = + vec!["C:/Program Files/Java", "C:/Program Files (x86)/Java"]; for potential_parent_dir in potential_parent_dirs { let parent_dir = PathBuf::from(potential_parent_dir); if parent_dir.exists() { diff --git a/crates/carbon_app/src/managers/java/java_checker.rs b/crates/carbon_app/src/managers/java/java_checker.rs index 2cf9d3d6a..ff26101b2 100644 --- a/crates/carbon_app/src/managers/java/java_checker.rs +++ b/crates/carbon_app/src/managers/java/java_checker.rs @@ -4,7 +4,9 @@ use anyhow::bail; use tokio::process::Command; use tracing::instrument; -use crate::domain::java::{JavaArch, JavaComponent, JavaComponentType, JavaOs, JavaVersion}; +use crate::domain::java::{ + JavaArch, JavaComponent, JavaComponentType, JavaOs, JavaVersion, +}; use super::{ parser::parse_cmd_output_java, @@ -31,7 +33,8 @@ impl JavaChecker for RealJavaChecker { _type: JavaComponentType, ) -> anyhow::Result { let java_checker_path = locate_java_check_class().await?; - if java_bin_path.to_string_lossy() != "java" && !java_bin_path.exists() { + if java_bin_path.to_string_lossy() != "java" && !java_bin_path.exists() + { bail!( "Java binary not found at {}", java_bin_path.to_string_lossy() diff --git a/crates/carbon_app/src/managers/java/managed/azul_zulu.rs b/crates/carbon_app/src/managers/java/managed/azul_zulu.rs index 1c55aa9f1..d0c95a216 100644 --- a/crates/carbon_app/src/managers/java/managed/azul_zulu.rs +++ b/crates/carbon_app/src/managers/java/managed/azul_zulu.rs @@ -18,10 +18,14 @@ use crate::{ java::{JavaArch, JavaOs, JavaVersion}, runtime_path::{ManagedJavasPath, TempPath}, }, - managers::java::{java_checker::JavaChecker, scan_and_sync::add_java_component_to_db}, + managers::java::{ + java_checker::JavaChecker, scan_and_sync::add_java_component_to_db, + }, }; -use super::{Managed, ManagedJavaArchMap, ManagedJavaOsMap, ManagedJavaVersion, Step}; +use super::{ + Managed, ManagedJavaArchMap, ManagedJavaOsMap, ManagedJavaVersion, Step, +}; #[derive(Debug, Default)] pub struct AzulZulu { @@ -47,12 +51,14 @@ impl Managed for AzulZulu { let content_length = reqwest::get(download_url).await?.content_length(); let downloadable = if let Some(content_length) = content_length { - Downloadable::new(download_url, download_temp_path).with_size(content_length) + Downloadable::new(download_url, download_temp_path) + .with_size(content_length) } else { Downloadable::new(download_url, download_temp_path) }; - let (p_sender, mut p_recv) = tokio::sync::watch::channel(Progress::new()); + let (p_sender, mut p_recv) = + tokio::sync::watch::channel(Progress::new()); let progress_report_clone = progress_report.clone(); let progress_proxy = tokio::spawn(async move { @@ -210,7 +216,8 @@ impl Managed for AzulZulu { ) .await?; - let java_id = add_java_component_to_db(db_client, java_component).await?; + let java_id = + add_java_component_to_db(db_client, java_component).await?; Ok(java_id) } @@ -257,10 +264,19 @@ impl AzulAPI { download_url: version.download_url.clone(), id: version.package_uuid.clone(), java_version: JavaVersion { - major: version.java_version.first().cloned().ok_or( - anyhow::anyhow!("No major version found for {}", version.name), - )?, - minor: version.java_version.get(1).cloned().unwrap_or(0), + major: version + .java_version + .first() + .cloned() + .ok_or(anyhow::anyhow!( + "No major version found for {}", + version.name + ))?, + minor: version + .java_version + .get(1) + .cloned() + .unwrap_or(0), patch: version .java_version .get(2) diff --git a/crates/carbon_app/src/managers/java/managed/mod.rs b/crates/carbon_app/src/managers/java/managed/mod.rs index 065a7b6d2..ea300f922 100644 --- a/crates/carbon_app/src/managers/java/managed/mod.rs +++ b/crates/carbon_app/src/managers/java/managed/mod.rs @@ -141,19 +141,26 @@ impl ManagedService { let versions = self.azul_zulu.fetch_all_versions().await?; let version = versions .get(&os) - .ok_or_else(|| anyhow::anyhow!("No versions for os: {:?}", os))? + .ok_or_else(|| { + anyhow::anyhow!("No versions for os: {:?}", os) + })? .get(&arch) - .ok_or_else(|| anyhow::anyhow!("No versions for arch: {:?}", arch))? + .ok_or_else(|| { + anyhow::anyhow!("No versions for arch: {:?}", arch) + })? .iter() .find(|v| v.id == id) - .ok_or_else(|| anyhow::anyhow!("No version for id: {}", id))?; + .ok_or_else(|| { + anyhow::anyhow!("No version for id: {}", id) + })?; let tmp_path = app.settings_manager().runtime_path.get_temp(); let base_managed_java_path = app.settings_manager().runtime_path.get_managed_javas(); let db_client = &app.prisma_client.clone(); - let (sender, mut recv) = tokio::sync::watch::channel(Step::Idle); + let (sender, mut recv) = + tokio::sync::watch::channel(Step::Idle); let progress_ref = Arc::clone(&self.setup_progress); @@ -168,7 +175,10 @@ impl ManagedService { } app.invalidate(GET_SETUP_MANAGED_JAVA_PROGRESS, None); drop(progress_ref); - tokio::time::sleep(std::time::Duration::from_millis(100)).await; + tokio::time::sleep(std::time::Duration::from_millis( + 100, + )) + .await; } }); diff --git a/crates/carbon_app/src/managers/java/mod.rs b/crates/carbon_app/src/managers/java/mod.rs index 50ffc73ca..4ee045abe 100644 --- a/crates/carbon_app/src/managers/java/mod.rs +++ b/crates/carbon_app/src/managers/java/mod.rs @@ -1,4 +1,6 @@ -use prisma_client_rust::{prisma_errors::query_engine::UniqueKeyViolation, QueryError}; +use prisma_client_rust::{ + prisma_errors::query_engine::UniqueKeyViolation, QueryError, +}; use strum::IntoEnumIterator; use tokio::sync::watch; use tracing::{debug, error, trace}; @@ -14,8 +16,8 @@ use crate::{ api::keys::java::GET_SYSTEM_JAVA_PROFILES, db::PrismaClient, domain::java::{ - Java, JavaArch, JavaComponent, JavaComponentType, JavaOs, JavaVendor, SystemJavaProfile, - SystemJavaProfileName, + Java, JavaArch, JavaComponent, JavaComponentType, JavaOs, JavaVendor, + SystemJavaProfile, SystemJavaProfileName, }, managers::java::java_checker::RealJavaChecker, }; @@ -44,10 +46,15 @@ impl JavaManager { } } - pub async fn ensure_profiles_in_db(db_client: &PrismaClient) -> anyhow::Result<()> { + pub async fn ensure_profiles_in_db( + db_client: &PrismaClient, + ) -> anyhow::Result<()> { debug!("Ensuring system java profiles are in db"); for profile in SystemJavaProfileName::iter() { - let creation: Result = db_client + let creation: Result< + crate::db::java_system_profile::Data, + QueryError, + > = db_client .java_system_profile() .create(profile.to_string(), vec![]) .exec() @@ -90,7 +97,9 @@ impl JavaManager { } impl ManagerRef<'_, JavaManager> { - pub async fn get_available_javas(&self) -> anyhow::Result>> { + pub async fn get_available_javas( + &self, + ) -> anyhow::Result>> { let db = &self.app.prisma_client; let all_javas = db.java().find_many(vec![]).exec().await?; @@ -105,7 +114,9 @@ impl ManagerRef<'_, JavaManager> { Ok(result) } - pub async fn get_system_java_profiles(&self) -> anyhow::Result> { + pub async fn get_system_java_profiles( + &self, + ) -> anyhow::Result> { let db = &self.app.prisma_client; let all_profiles = db .java_system_profile() @@ -154,7 +165,10 @@ impl ManagerRef<'_, JavaManager> { Ok(()) } - pub async fn delete_java_version(&self, java_id: String) -> anyhow::Result<()> { + pub async fn delete_java_version( + &self, + java_id: String, + ) -> anyhow::Result<()> { let auto_manage_java = self .app .settings_manager() @@ -173,9 +187,12 @@ impl ManagerRef<'_, JavaManager> { .find_unique(crate::db::java::id::equals(java_id.clone())) .exec() .await? - .ok_or_else(|| anyhow::anyhow!("Java with id {} not found", java_id.clone()))?; + .ok_or_else(|| { + anyhow::anyhow!("Java with id {} not found", java_id.clone()) + })?; - let java_component_type = JavaComponentType::try_from(&*java_from_db.r#type)?; + let java_component_type = + JavaComponentType::try_from(&*java_from_db.r#type)?; match java_component_type { JavaComponentType::Custom => { @@ -201,7 +218,8 @@ impl ManagerRef<'_, JavaManager> { .next() .ok_or_else(|| anyhow::anyhow!("Could not strip prefix"))?; - let managed_java_dir = root_managed_path.join(managed_java_dir_name); + let managed_java_dir = + root_managed_path.join(managed_java_dir_name); if managed_java_dir.exists() { std::fs::remove_dir_all(managed_java_dir)?; @@ -215,7 +233,10 @@ impl ManagerRef<'_, JavaManager> { .await?; } JavaComponentType::Local => { - anyhow::bail!("Java with id {} is local. Cannot delete.", java_id.clone()); + anyhow::bail!( + "Java with id {} is local. Cannot delete.", + java_id.clone() + ); } } @@ -235,7 +256,9 @@ impl ManagerRef<'_, JavaManager> { .into_iter() .find(|profile| profile.name == target_profile) .ok_or_else(|| { - anyhow::anyhow!("system java profile not found for {target_profile:?}") + anyhow::anyhow!( + "system java profile not found for {target_profile:?}" + ) })?; let java = match profile.java_id { @@ -271,9 +294,16 @@ impl ManagerRef<'_, JavaManager> { self.app .prisma_client ._batch(( - self.app.prisma_client.java_system_profile().update( - java_system_profile::name::equals(profile.name.to_string()), - vec![java_system_profile::java::disconnect()], + self.app + .prisma_client + .java_system_profile() + .update( + java_system_profile::name::equals( + profile.name.to_string(), + ), + vec![ + java_system_profile::java::disconnect(), + ], ), self.app .prisma_client @@ -360,7 +390,9 @@ impl ManagerRef<'_, JavaManager> { .prisma_client .java_system_profile() .update( - crate::db::java_system_profile::name::equals(target_profile.to_string()), + crate::db::java_system_profile::name::equals( + target_profile.to_string(), + ), vec![crate::db::java_system_profile::java::connect( crate::db::java::id::equals(id.clone()), )], @@ -386,7 +418,9 @@ impl ManagerRef<'_, JavaManager> { .prisma_client .java_system_profile() .update( - crate::db::java_system_profile::name::equals(system_profile.to_string()), + crate::db::java_system_profile::name::equals( + system_profile.to_string(), + ), vec![crate::db::java_system_profile::java::connect( crate::db::java::id::equals(id.clone()), )], @@ -422,7 +456,8 @@ mod test { .unwrap() .unwrap(); - let profiles_in_db = java_manager.get_system_java_profiles().await.unwrap(); + let profiles_in_db = + java_manager.get_system_java_profiles().await.unwrap(); assert_eq!( profiles_in_db @@ -466,7 +501,8 @@ mod test { ) .await .unwrap(); - let count = app.prisma_client.java().count(vec![]).exec().await.unwrap(); + let count = + app.prisma_client.java().count(vec![]).exec().await.unwrap(); assert_eq!(count, 1); let from_db = app @@ -491,7 +527,9 @@ mod test { .app_configuration() .update( crate::db::app_configuration::id::equals(0), - vec![crate::db::app_configuration::auto_manage_java::set(false)], + vec![crate::db::app_configuration::auto_manage_java::set( + false, + )], ) .exec() .await @@ -504,7 +542,8 @@ mod test { assert!(result_second_delete.is_ok()); - let count = app.prisma_client.java().count(vec![]).exec().await.unwrap(); + let count = + app.prisma_client.java().count(vec![]).exec().await.unwrap(); assert_eq!(count, 0); assert!(!std::path::Path::new(&from_db.path).exists()); diff --git a/crates/carbon_app/src/managers/java/parser.rs b/crates/carbon_app/src/managers/java/parser.rs index b9a18d498..9e05f8224 100644 --- a/crates/carbon_app/src/managers/java/parser.rs +++ b/crates/carbon_app/src/managers/java/parser.rs @@ -9,7 +9,9 @@ pub struct JavaCmdParsedOutput { pub vendor: String, } -pub fn parse_cmd_output_java(cmd_output: &str) -> anyhow::Result { +pub fn parse_cmd_output_java( + cmd_output: &str, +) -> anyhow::Result { let mut version = None; let mut arch = None; let mut vendor = None; @@ -20,7 +22,8 @@ pub fn parse_cmd_output_java(cmd_output: &str) -> anyhow::Result anyhow::Result { trace!("Java is invalid due to: {:?}", err); - let is_java_used_in_profile = java_profiles.iter().any(|profile| { - let Some(java) = profile.java.as_ref() else { - return false; - }; - let Some(java) = java.as_ref() else { - return false; - }; - let java_path = java.path.clone(); - java_path == resolved_java_path.display().to_string() - }); + let is_java_used_in_profile = + java_profiles.iter().any(|profile| { + let Some(java) = profile.java.as_ref() else { + return false; + }; + let Some(java) = java.as_ref() else { + return false; + }; + let java_path = java.path.clone(); + java_path == resolved_java_path.display().to_string() + }); // If it is in the db, update it to invalid if db_entry.is_some() { @@ -178,9 +185,11 @@ where .await?; } else { db.java() - .delete(crate::db::java::UniqueWhereParam::PathEquals( - resolved_java_path.display().to_string(), - )) + .delete( + crate::db::java::UniqueWhereParam::PathEquals( + resolved_java_path.display().to_string(), + ), + ) .exec() .await?; } @@ -199,9 +208,9 @@ where .await?; for local_java_from_db in local_javas_from_db { - let has_been_scanned = local_javas - .iter() - .any(|local_java| local_java_from_db.path == local_java.display().to_string()); + let has_been_scanned = local_javas.iter().any(|local_java| { + local_java_from_db.path == local_java.display().to_string() + }); if has_been_scanned { continue; @@ -218,10 +227,13 @@ where }; Some(java.path.clone()) }) - .any(|java_profile_path| local_java_from_db.path == java_profile_path); + .any(|java_profile_path| { + local_java_from_db.path == java_profile_path + }); if is_used_in_profile && !auto_manage_java { - update_java_component_in_db_to_invalid(db, local_java_from_db.path).await?; + update_java_component_in_db_to_invalid(db, local_java_from_db.path) + .await?; } else { db.java() .delete(crate::db::java::UniqueWhereParam::PathEquals( @@ -236,7 +248,10 @@ where } #[tracing::instrument(level = "trace", skip_all)] -pub async fn scan_and_sync_custom(db: &Arc, java_checker: &G) -> anyhow::Result<()> +pub async fn scan_and_sync_custom( + db: &Arc, + java_checker: &G, +) -> anyhow::Result<()> where G: JavaChecker, { @@ -257,7 +272,8 @@ where .await; if java_bin_info.is_err() { - update_java_component_in_db_to_invalid(db, custom_java.path).await?; + update_java_component_in_db_to_invalid(db, custom_java.path) + .await?; } } @@ -289,7 +305,8 @@ where .await; if java_bin_info.is_err() { - update_java_component_in_db_to_invalid(db, managed_java.path).await?; + update_java_component_in_db_to_invalid(db, managed_java.path) + .await?; } } @@ -297,10 +314,13 @@ where } #[tracing::instrument(level = "trace", skip_all)] -pub async fn sync_system_java_profiles(db: &Arc) -> anyhow::Result<()> { +pub async fn sync_system_java_profiles( + db: &Arc, +) -> anyhow::Result<()> { let all_javas = db.java().find_many(vec![]).exec().await?; - let is32bit = std::env::consts::ARCH == "x86" || std::env::consts::ARCH == "arm"; + let is32bit = + std::env::consts::ARCH == "x86" || std::env::consts::ARCH == "arm"; for profile in SystemJavaProfileName::iter() { trace!("Syncing system java profile: {}", profile.to_string()); @@ -335,7 +355,8 @@ pub async fn sync_system_java_profiles(db: &Arc) -> anyhow::Result continue; } - let java_version = JavaVersion::try_from(java.full_version.as_str())?; + let java_version = + JavaVersion::try_from(java.full_version.as_str())?; let java_arch = JavaArch::try_from(java.arch.as_str())?; let is_arch_allowed = match java_arch { @@ -343,7 +364,9 @@ pub async fn sync_system_java_profiles(db: &Arc) -> anyhow::Result _ => true, }; - if profile.is_java_version_compatible(&java_version) && is_arch_allowed { + if profile.is_java_version_compatible(&java_version) + && is_arch_allowed + { trace!( "Java {} is compatible with profile {}", java.path, @@ -351,7 +374,9 @@ pub async fn sync_system_java_profiles(db: &Arc) -> anyhow::Result ); db.java_system_profile() .update( - crate::db::java_system_profile::name::equals(profile.to_string()), + crate::db::java_system_profile::name::equals( + profile.to_string(), + ), vec![crate::db::java_system_profile::java::connect( crate::db::java::id::equals(java.id.clone()), )], @@ -372,14 +397,15 @@ mod test { use crate::{ domain::java::{ - JavaArch, JavaComponent, JavaComponentType, JavaOs, JavaVersion, SystemJavaProfileName, + JavaArch, JavaComponent, JavaComponentType, JavaOs, JavaVersion, + SystemJavaProfileName, }, managers::java::{ discovery::MockDiscovery, java_checker::{MockJavaChecker, MockJavaCheckerInvalid}, scan_and_sync::{ - add_java_component_to_db, scan_and_sync_custom, scan_and_sync_local, - sync_system_java_profiles, + add_java_component_to_db, scan_and_sync_custom, + scan_and_sync_local, sync_system_java_profiles, }, JavaManager, }, @@ -441,7 +467,8 @@ mod test { vendor: "Azul Systems, Inc.".to_string(), }; - let result = add_java_component_to_db(db, almost_equal_java_component).await; + let result = + add_java_component_to_db(db, almost_equal_java_component).await; assert!(result.is_err()); } diff --git a/crates/carbon_app/src/managers/metadata/cache/curseforge.rs b/crates/carbon_app/src/managers/metadata/cache/curseforge.rs index 5786fa184..93db74743 100644 --- a/crates/carbon_app/src/managers/metadata/cache/curseforge.rs +++ b/crates/carbon_app/src/managers/metadata/cache/curseforge.rs @@ -22,8 +22,8 @@ use super::BundleSender; use super::ModplatformCacher; use super::UpdateNotifier; use crate::db::{ - curse_forge_mod_cache as cfdb, curse_forge_mod_image_cache as cfimgdb, mod_file_cache as fcdb, - mod_metadata as metadb, + curse_forge_mod_cache as cfdb, curse_forge_mod_image_cache as cfimgdb, + mod_file_cache as fcdb, mod_metadata as metadb, }; pub struct CurseforgeModCacher; @@ -49,20 +49,23 @@ impl ModplatformCacher for CurseforgeModCacher { .mod_file_cache() .find_many(vec![ fcdb::WhereParam::InstanceId(IntFilter::Equals(*instance_id)), - fcdb::WhereParam::MetadataIs(vec![metadb::WhereParam::CurseforgeIsNot(vec![ - cfdb::WhereParam::CachedAt(DateTimeFilter::Gt( - (chrono::Utc::now() - chrono::Duration::days(1)).into(), - )), - ])]), + fcdb::WhereParam::MetadataIs(vec![ + metadb::WhereParam::CurseforgeIsNot(vec![ + cfdb::WhereParam::CachedAt(DateTimeFilter::Gt( + (chrono::Utc::now() - chrono::Duration::days(1)) + .into(), + )), + ]), + ]), ]) .with(fcdb::metadata::fetch()) .exec() .await? .into_iter() .map(|m| { - let metadata = m - .metadata - .expect("metadata was queried with mod cache yet is not present"); + let metadata = m.metadata.expect( + "metadata was queried with mod cache yet is not present", + ); ( metadata.murmur_2 as u32, @@ -101,7 +104,9 @@ impl ModplatformCacher for CurseforgeModCacher { .drain(0..usize::min(1000, modlist.len())) .unzip::<_, _, Vec<_>, Vec<_>>(); - trace!("querying curseforge mod batch for instance {instance_id}"); + trace!( + "querying curseforge mod batch for instance {instance_id}" + ); let fp_response = app .modplatforms_manager() @@ -125,7 +130,12 @@ impl ModplatformCacher for CurseforgeModCacher { .await? .data; - sender.send((fingerprints, metadata, fp_response, mods_response)); + sender.send(( + fingerprints, + metadata, + fp_response, + mods_response, + )); } Ok::<_, anyhow::Error>(()) @@ -138,7 +148,8 @@ impl ModplatformCacher for CurseforgeModCacher { let entry = failed_instances .entry(instance_id) .or_insert((Instant::now(), 0)); - entry.0 = Instant::now() + Duration::from_secs(u64::pow(2, entry.1)); + entry.0 = + Instant::now() + Duration::from_secs(u64::pow(2, entry.1)); entry.1 += 1; } else { let mut failed_instances = mcm.failed_cf_instances.write().await; @@ -160,12 +171,15 @@ impl ModplatformCacher for CurseforgeModCacher { .into_iter() .zip(fp_response.exact_matches.into_iter()) .zip(mods_response.into_iter()) - .map(|((fingerprint, fileinfo), modinfo)| (fingerprint, (fileinfo, modinfo))) + .map(|((fingerprint, fileinfo), modinfo)| { + (fingerprint, (fileinfo, modinfo)) + }) .collect::>(); let mcm = app.meta_cache_manager(); let mut ignored_hashes = mcm.ignored_remote_cf_hashes.write().await; - ignored_hashes.extend(fingerprints.iter().filter(|fp| !matches.contains_key(fp))); + ignored_hashes + .extend(fingerprints.iter().filter(|fp| !matches.contains_key(fp))); drop(ignored_hashes); let futures = batch.into_iter().filter_map(|(metadata_id, murmur2)| { @@ -191,22 +205,27 @@ impl ModplatformCacher for CurseforgeModCacher { futures::future::join_all(futures).await; } - async fn cache_icons(app: &App, instance_id: InstanceId, update_notifier: &UpdateNotifier) { + async fn cache_icons( + app: &App, + instance_id: InstanceId, + update_notifier: &UpdateNotifier, + ) { let modlist = app .prisma_client .mod_file_cache() .find_many(vec![ fcdb::WhereParam::InstanceId(IntFilter::Equals(*instance_id)), - fcdb::WhereParam::MetadataIs(vec![metadb::WhereParam::CurseforgeIs(vec![ - cfdb::WhereParam::LogoImageIs(vec![cfimgdb::WhereParam::UpToDate( - IntFilter::Equals(0), - )]), - ])]), + fcdb::WhereParam::MetadataIs(vec![ + metadb::WhereParam::CurseforgeIs(vec![ + cfdb::WhereParam::LogoImageIs(vec![ + cfimgdb::WhereParam::UpToDate(IntFilter::Equals(0)), + ]), + ]), + ]), ]) - .with( - fcdb::metadata::fetch() - .with(metadb::curseforge::fetch().with(cfdb::logo_image::fetch())), - ) + .with(fcdb::metadata::fetch().with( + metadb::curseforge::fetch().with(cfdb::logo_image::fetch()), + )) .exec() .await; @@ -354,12 +373,11 @@ async fn cache_curseforge_meta_unchecked( Vec::new(), ); - let o_delete_cfmeta = - prev.as_ref().map(|_| { - app.prisma_client.curse_forge_mod_cache().delete( - cfdb::UniqueWhereParam::MetadataIdEquals(metadata_id.clone()), - ) - }); + let o_delete_cfmeta = prev.as_ref().map(|_| { + app.prisma_client.curse_forge_mod_cache().delete( + cfdb::UniqueWhereParam::MetadataIdEquals(metadata_id.clone()), + ) + }); let old_image = prev .map(|p| { diff --git a/crates/carbon_app/src/managers/metadata/cache/mod.rs b/crates/carbon_app/src/managers/metadata/cache/mod.rs index 2e1311b89..b77f67690 100644 --- a/crates/carbon_app/src/managers/metadata/cache/mod.rs +++ b/crates/carbon_app/src/managers/metadata/cache/mod.rs @@ -237,17 +237,19 @@ impl CacheTargets { } } - fn release_target(&mut self, instance_id: InstanceId, r: anyhow::Result<()>) -> bool { + fn release_target( + &mut self, + instance_id: InstanceId, + r: anyhow::Result<()>, + ) -> bool { let mut changed = false; let check_target_callback = |target: &mut CacheTarget| { if target.instance_id == instance_id { if let Some(callback) = target.callback.take() { - callback.complete( - r.as_ref() - .map(|_| ()) - .map_err(|_| anyhow!("error caching mods for instance")), - ); + callback.complete(r.as_ref().map(|_| ()).map_err(|_| { + anyhow!("error caching mods for instance") + })); } true @@ -292,7 +294,9 @@ impl CacheTargets { if let Some(target) = target_option { if target.instance_id == instance_id { if let Some(callback) = target.callback.take() { - callback.complete(Err(anyhow!("This cache target was revoked"))); + callback.complete(Err(anyhow!( + "This cache target was revoked" + ))); } *target_option = None; @@ -328,7 +332,8 @@ impl CacheTargets { fn cancel_override(&mut self) { if let Some(old) = self.priority.take() { if let Some(callback) = old.callback { - callback.complete(Err(anyhow!("Backend override was canceled"))); + callback + .complete(Err(anyhow!("Backend override was canceled"))); } } } @@ -460,12 +465,21 @@ trait ModplatformCacher { sender: &mut BundleSender, ) -> anyhow::Result<()>; - async fn save_batch(app: &App, instance_id: InstanceId, batch: Self::SaveBundle); + async fn save_batch( + app: &App, + instance_id: InstanceId, + batch: Self::SaveBundle, + ); - async fn cache_icons(app: &App, instance_id: InstanceId, update_notifier: &UpdateNotifier); + async fn cache_icons( + app: &App, + instance_id: InstanceId, + update_notifier: &UpdateNotifier, + ); } -type ModplatformCacheBundle = (InstanceId, bool, Option, Option>); +type ModplatformCacheBundle = + (InstanceId, bool, Option, Option>); struct BundleSender<'a, T> { should_wait: bool, @@ -501,9 +515,12 @@ impl<'a, T> BundleSender<'a, T> { }; self.active_wait = rx; - let _ = self - .sender - .send((self.instance_id, self.update_images, Some(bundle), tx)); + let _ = self.sender.send(( + self.instance_id, + self.update_images, + Some(bundle), + tx, + )); } async fn wait(self) { @@ -513,9 +530,12 @@ impl<'a, T> BundleSender<'a, T> { } None => { if self.update_images { - let _ = self - .sender - .send((self.instance_id, self.update_images, None, None)); + let _ = self.sender.send(( + self.instance_id, + self.update_images, + None, + None, + )); } } } @@ -561,7 +581,9 @@ fn cache_modplatform( ); let save_loop = async { - while let Some((instance_id, update_images, bundle, notify)) = batch_rx.recv().await { + while let Some((instance_id, update_images, bundle, notify)) = + batch_rx.recv().await + { if let Some(bundle) = bundle { debug!( "Saving {} mod cache update bundle for instance {instance_id}", @@ -583,13 +605,17 @@ fn cache_modplatform( }; let mut image_loop_watcher = LoopWatcher::new(image_rx).await; - let image_loop = image_loop_watcher.loop_interrupt(|instance_id| async move { - debug!("Caching {} mod icons for instance {instance_id}", C::NAME); + let image_loop = + image_loop_watcher.loop_interrupt(|instance_id| async move { + debug!( + "Caching {} mod icons for instance {instance_id}", + C::NAME + ); - C::cache_icons(&app, instance_id, &update_notifier).await; + C::cache_icons(&app, instance_id, &update_notifier).await; - |_: &mut Option| false - }); + |_: &mut Option| false + }); // None of the futures should ever exit. // This join polls both while allowing them to share variables in this scope. @@ -646,18 +672,22 @@ impl ManagerRef<'_, MetaCacheManager> { let mcm = app.meta_cache_manager(); join!( - mcm.curseforge_targets.send_modify_always(move |targets| { - targets.set_priority(CacheTarget { - instance_id, - callback: None, - }) - }), - mcm.modrinth_targets.send_modify_always(move |targets| { - targets.set_priority(CacheTarget { - instance_id, - callback: None, - }) - }) + mcm.curseforge_targets.send_modify_always( + move |targets| { + targets.set_priority(CacheTarget { + instance_id, + callback: None, + }) + } + ), + mcm.modrinth_targets.send_modify_always( + move |targets| { + targets.set_priority(CacheTarget { + instance_id, + callback: None, + }) + } + ) ); }); } @@ -770,18 +800,21 @@ impl ManagerRef<'_, MetaCacheManager> { let content = tokio::fs::read(path).await?; let content_len = content.len(); - let (content, sha512, meta, murmur2) = tokio::task::spawn_blocking(move || { - let sha512: [u8; 64] = Sha512::new_with_prefix(&content).finalize().into(); - let meta = super::mods::parse_metadata(Cursor::new(&content)); - - // curseforge's api removes whitespace in murmur2 hashes - let mut murmur_content = content.clone(); - murmur_content.retain(|&x| x != 9 && x != 10 && x != 13 && x != 32); - let murmur2 = murmurhash32::murmurhash2(&murmur_content); - - (content, sha512, meta, murmur2) - }) - .await?; + let (content, sha512, meta, murmur2) = + tokio::task::spawn_blocking(move || { + let sha512: [u8; 64] = + Sha512::new_with_prefix(&content).finalize().into(); + let meta = super::mods::parse_metadata(Cursor::new(&content)); + + // curseforge's api removes whitespace in murmur2 hashes + let mut murmur_content = content.clone(); + murmur_content + .retain(|&x| x != 9 && x != 10 && x != 13 && x != 32); + let murmur2 = murmurhash32::murmurhash2(&murmur_content); + + (content, sha512, meta, murmur2) + }) + .await?; let meta = match meta { Ok(meta) => meta, @@ -797,7 +830,9 @@ impl ManagerRef<'_, MetaCacheManager> { .mod_metadata() // just check both hashes for now .find_first(vec![ - metadb::WhereParam::Sha512(BytesFilter::Equals(Vec::from(sha512))), + metadb::WhereParam::Sha512(BytesFilter::Equals(Vec::from( + sha512, + ))), metadb::WhereParam::Murmur2(IntFilter::Equals(murmur2 as i32)), ]) .exec() @@ -816,18 +851,20 @@ impl ManagerRef<'_, MetaCacheManager> { let logo_file = logo_file.to_string(); let mcm = self.app.meta_cache_manager(); - let guard = mcm - .image_scale_semaphore - .acquire() - .await - .expect("the image scale semaphore is never closed"); + let guard = + mcm.image_scale_semaphore.acquire().await.expect( + "the image scale semaphore is never closed", + ); let logo = tokio::task::spawn_blocking(move || { - let mut zip = zip::ZipArchive::new(Cursor::new(&content)).unwrap(); + let mut zip = + zip::ZipArchive::new(Cursor::new(&content)) + .unwrap(); let Ok(mut file) = zip.by_name(&logo_file) else { return Ok(None); }; - let mut image = Vec::with_capacity(file.size() as usize); + let mut image = + Vec::with_capacity(file.size() as usize); file.read_to_end(&mut image)?; let scaled = scale_mod_image(&image[..])?; Ok::<_, anyhow::Error>(Some(scaled)) @@ -837,13 +874,18 @@ impl ManagerRef<'_, MetaCacheManager> { drop(guard); match logo { - Ok(Ok(Some(data))) => { - Some(self.app.prisma_client.local_mod_image_cache().create( - data, - metadb::UniqueWhereParam::IdEquals(meta_id.clone()), - Vec::new(), - )) - } + Ok(Ok(Some(data))) => Some( + self.app + .prisma_client + .local_mod_image_cache() + .create( + data, + metadb::UniqueWhereParam::IdEquals( + meta_id.clone(), + ), + Vec::new(), + ), + ), Ok(Ok(None)) => None, Ok(Err(e)) => { error!({ error = ?e }, "could not scale mod icon for {}", mod_filename); @@ -862,7 +904,9 @@ impl ManagerRef<'_, MetaCacheManager> { Vec::from(sha512), meta.as_ref() .map(|meta| &meta.modloaders) - .map(|modloaders| modloaders.iter().map(ToString::to_string).join(",")) + .map(|modloaders| { + modloaders.iter().map(ToString::to_string).join(",") + }) .unwrap_or(String::new()), match meta { Some(meta) => vec![ @@ -889,10 +933,13 @@ impl ManagerRef<'_, MetaCacheManager> { } }; - let filecache_delete = self.app.prisma_client.mod_file_cache().delete_many(vec![ - fcdb::WhereParam::InstanceId(IntFilter::Equals(*instance_id)), - fcdb::WhereParam::Filename(StringFilter::Equals(mod_filename.to_string())), - ]); + let filecache_delete = + self.app.prisma_client.mod_file_cache().delete_many(vec![ + fcdb::WhereParam::InstanceId(IntFilter::Equals(*instance_id)), + fcdb::WhereParam::Filename(StringFilter::Equals( + mod_filename.to_string(), + )), + ]); let filecache_insert = self.app.prisma_client.mod_file_cache().create( crate::db::instance::UniqueWhereParam::IdEquals(*instance_id), @@ -963,7 +1010,11 @@ fn scale_mod_image(image: &[u8]) -> anyhow::Result> { Ok(output) } -fn cache_local(app: App, rx: LockNotify, update_notifier: UpdateNotifier) { +fn cache_local( + app: App, + rx: LockNotify, + update_notifier: UpdateNotifier, +) { tokio::spawn(async move { let app = &app; let update_notifier = &update_notifier; @@ -973,9 +1024,9 @@ fn cache_local(app: App, rx: LockNotify, update_notifier: UpdateNo let cached_entries = tokio::spawn(async move { app2.prisma_client .mod_file_cache() - .find_many(vec![fcdb::WhereParam::InstanceId(IntFilter::Equals( - *instance_id, - ))]) + .find_many(vec![fcdb::WhereParam::InstanceId( + IntFilter::Equals(*instance_id), + )]) .exec() .await }); @@ -992,7 +1043,8 @@ fn cache_local(app: App, rx: LockNotify, update_notifier: UpdateNo .get_mods_path(); let mut pathbuf = PathBuf::new(); - pathbuf.push(app.settings_manager().runtime_path.get_root().to_path()); + pathbuf + .push(app.settings_manager().runtime_path.get_root().to_path()); pathbuf.push(&subpath); if !pathbuf.is_dir() { @@ -1017,7 +1069,9 @@ fn cache_local(app: App, rx: LockNotify, update_notifier: UpdateNo continue; }; - let allowed_base_ext = [".jar", ".zip"].iter().any(|&ext| utf8_name.ends_with(ext)); + let allowed_base_ext = [".jar", ".zip"] + .iter() + .any(|&ext| utf8_name.ends_with(ext)); let allowed_disabled_ext = [".jar.disabled", ".zip.disabled"] .iter() .any(|&ext| utf8_name.ends_with(ext)); @@ -1026,7 +1080,8 @@ fn cache_local(app: App, rx: LockNotify, update_notifier: UpdateNo continue; } - utf8_name = utf8_name.strip_suffix(".disabled").unwrap_or(utf8_name); + utf8_name = + utf8_name.strip_suffix(".disabled").unwrap_or(utf8_name); let Ok(metadata) = entry.metadata().await else { continue; @@ -1047,9 +1102,13 @@ fn cache_local(app: App, rx: LockNotify, update_notifier: UpdateNo if let Ok(Ok(cached_entries)) = cached_entries.await { for entry in cached_entries { - if let Some((enabled, real_size)) = modpaths.get(&entry.filename) { + if let Some((enabled, real_size)) = + modpaths.get(&entry.filename) + { // enabled probably shouldn't be here - if *real_size == entry.filesize as u64 && *enabled == entry.enabled { + if *real_size == entry.filesize as u64 + && *enabled == entry.enabled + { modpaths.remove(&entry.filename); trace!( "up to data metadata entry for mod `{}`, skipping", @@ -1082,16 +1141,22 @@ fn cache_local(app: App, rx: LockNotify, update_notifier: UpdateNo } } - let entry_futures = modpaths.into_iter().map(|(subpath, (enabled, _))| { - let pathbuf = &pathbuf; - - async move { - app.meta_cache_manager() - .cache_mod_file_unchecked(instance_id, pathbuf, subpath, enabled) - .await - .map(|_| ()) - } - }); + let entry_futures = + modpaths.into_iter().map(|(subpath, (enabled, _))| { + let pathbuf = &pathbuf; + + async move { + app.meta_cache_manager() + .cache_mod_file_unchecked( + instance_id, + pathbuf, + subpath, + enabled, + ) + .await + .map(|_| ()) + } + }); let r = futures::future::join_all(entry_futures) .await diff --git a/crates/carbon_app/src/managers/metadata/cache/modrinth.rs b/crates/carbon_app/src/managers/metadata/cache/modrinth.rs index eae0d8033..f8af771ec 100644 --- a/crates/carbon_app/src/managers/metadata/cache/modrinth.rs +++ b/crates/carbon_app/src/managers/metadata/cache/modrinth.rs @@ -14,7 +14,9 @@ use crate::{ instance::InstanceId, modplatforms::modrinth::{ project::Project, - responses::{ProjectsResponse, TeamResponse, VersionHashesResponse}, + responses::{ + ProjectsResponse, TeamResponse, VersionHashesResponse, + }, search::{ProjectIDs, TeamIDs, VersionHashesQuery}, version::HashAlgorithm, }, @@ -47,20 +49,23 @@ impl ModplatformCacher for ModrinthModCacher { .mod_file_cache() .find_many(vec![ fcdb::WhereParam::InstanceId(IntFilter::Equals(*instance_id)), - fcdb::WhereParam::MetadataIs(vec![metadb::WhereParam::ModrinthIsNot(vec![ - mrdb::WhereParam::CachedAt(DateTimeFilter::Gt( - (chrono::Utc::now() - chrono::Duration::days(1)).into(), - )), - ])]), + fcdb::WhereParam::MetadataIs(vec![ + metadb::WhereParam::ModrinthIsNot(vec![ + mrdb::WhereParam::CachedAt(DateTimeFilter::Gt( + (chrono::Utc::now() - chrono::Duration::days(1)) + .into(), + )), + ]), + ]), ]) .with(fcdb::metadata::fetch()) .exec() .await? .into_iter() .map(|m| { - let metadata = m - .metadata - .expect("metadata was queried with mod cache yet is not present"); + let metadata = m.metadata.expect( + "metadata was queried with mod cache yet is not present", + ); let sha512 = hex::encode(&metadata.sha_512); (sha512.clone(), (metadata.id, sha512)) @@ -94,7 +99,9 @@ impl ModplatformCacher for ModrinthModCacher { let (sha512_hashes, metadata) = modlist .drain(0..usize::min(1000, modlist.len())) .unzip::<_, _, Vec<_>, Vec<_>>(); - trace!("querying modrinth mod batch for instance {instance_id}"); + trace!( + "querying modrinth mod batch for instance {instance_id}" + ); let versions_response = app .modplatforms_manager() @@ -146,7 +153,8 @@ impl ModplatformCacher for ModrinthModCacher { let entry = failed_instances .entry(instance_id) .or_insert((Instant::now(), 0)); - entry.0 = Instant::now() + Duration::from_secs(u64::pow(2, entry.1)); + entry.0 = + Instant::now() + Duration::from_secs(u64::pow(2, entry.1)); entry.1 += 1; } else { let mut failed_instances = mcm.failed_cf_instances.write().await; @@ -224,22 +232,27 @@ impl ModplatformCacher for ModrinthModCacher { futures::future::join_all(futures).await; } - async fn cache_icons(app: &App, instance_id: InstanceId, update_notifier: &UpdateNotifier) { + async fn cache_icons( + app: &App, + instance_id: InstanceId, + update_notifier: &UpdateNotifier, + ) { let modlist = app .prisma_client .mod_file_cache() .find_many(vec![ fcdb::WhereParam::InstanceId(IntFilter::Equals(*instance_id)), - fcdb::WhereParam::MetadataIs(vec![metadb::WhereParam::ModrinthIs(vec![ - mrdb::WhereParam::LogoImageIs(vec![mrimgdb::WhereParam::UpToDate( - IntFilter::Equals(0), - )]), - ])]), + fcdb::WhereParam::MetadataIs(vec![ + metadb::WhereParam::ModrinthIs(vec![ + mrdb::WhereParam::LogoImageIs(vec![ + mrimgdb::WhereParam::UpToDate(IntFilter::Equals(0)), + ]), + ]), + ]), ]) - .with( - fcdb::metadata::fetch() - .with(metadb::modrinth::fetch().with(mrdb::logo_image::fetch())), - ) + .with(fcdb::metadata::fetch().with( + metadb::modrinth::fetch().with(mrdb::logo_image::fetch()), + )) .exec() .await; @@ -389,11 +402,9 @@ async fn cache_modrinth_meta_unchecked( ); let o_delete_mrmeta = prev.as_ref().map(|_| { - app.prisma_client - .modrinth_mod_cache() - .delete(mrdb::UniqueWhereParam::MetadataIdEquals( - metadata_id.clone(), - )) + app.prisma_client.modrinth_mod_cache().delete( + mrdb::UniqueWhereParam::MetadataIdEquals(metadata_id.clone()), + ) }); let old_image = prev diff --git a/crates/carbon_app/src/managers/metadata/mods.rs b/crates/carbon_app/src/managers/metadata/mods.rs index e8c19a6ce..814234c84 100644 --- a/crates/carbon_app/src/managers/metadata/mods.rs +++ b/crates/carbon_app/src/managers/metadata/mods.rs @@ -50,10 +50,12 @@ struct NewMcModInfoObj { struct McModInfo { modid: Option, name: Option, - #[serde(alias = "mcversion")] // cccmod.info uses mcversion instead of version + #[serde(alias = "mcversion")] + // cccmod.info uses mcversion instead of version version: Option, description: Option, - #[serde(alias = "authorList")] // cccmod.info uses authorList instead of authors + #[serde(alias = "authorList")] + // cccmod.info uses authorList instead of authors authors: Option>, #[serde(rename = "logoFile")] logo_file: Option, @@ -79,7 +81,9 @@ impl TryFrom for McModInfo { use McModInfoContainer as Container; let meta = match value { - Container::Old(mod_list) => mod_list.into_iter().next().map(Into::into), + Container::Old(mod_list) => { + mod_list.into_iter().next().map(Into::into) + } Container::New(NewMcModInfo { mod_list }) => { mod_list.into_iter().next().map(Into::into) } @@ -233,7 +237,9 @@ fn pick_best_icon(icons: HashMap) -> Option { for (width, path) in icons.into_iter().rev() { match best { None => best = Some((width, path)), - Some((old_width, _)) if width < old_width && width >= 45 => best = Some((width, path)), + Some((old_width, _)) if width < old_width && width >= 45 => { + best = Some((width, path)) + } _ => {} } } @@ -601,10 +607,12 @@ impl TryFrom for ModFileMetadata { impl From for ModFileMetadata { fn from(value: QuiltModJson) -> Self { - let (name, description, authors, icon) = if let Some(metadata) = value.quilt_loader.metadata + let (name, description, authors, icon) = if let Some(metadata) = + value.quilt_loader.metadata { let authors = metadata.contributors.map(|contributors| { - let authors_string = contributors.keys().cloned().collect::>().join(", "); + let authors_string = + contributors.keys().cloned().collect::>().join(", "); authors_string }); ( @@ -650,7 +658,9 @@ fn merge_mod_metadata( } } -pub fn parse_metadata(reader: impl Read + Seek) -> anyhow::Result> { +pub fn parse_metadata( + reader: impl Read + Seek, +) -> anyhow::Result> { let mut zip = zip::ZipArchive::new(reader)?; let mut mod_metadata: Option = None; @@ -677,7 +687,9 @@ pub fn parse_metadata(reader: impl Read + Seek) -> anyhow::Result anyhow::Result(&content)?; - mod_metadata = merge_mod_metadata(mod_metadata, fabric_mod_json.try_into()?); + mod_metadata = + merge_mod_metadata(mod_metadata, fabric_mod_json.try_into()?); } 'quilt_mod_json: { @@ -740,10 +753,12 @@ pub fn parse_metadata(reader: impl Read + Seek) -> anyhow::Result(file.expect("we just checked this")) - .unwrap_or_default() - .try_into() - .unwrap_or_default(); + serde_json::from_reader::<_, McModInfoContainer>( + file.expect("we just checked this"), + ) + .unwrap_or_default() + .try_into() + .unwrap_or_default(); mod_metadata = merge_mod_metadata(mod_metadata, mcmod.into()); } @@ -761,11 +776,15 @@ mod test { use super::{parse_metadata, ModFileMetadata}; - pub fn parsemeta(path: &str, content: &str) -> anyhow::Result> { + pub fn parsemeta( + path: &str, + content: &str, + ) -> anyhow::Result> { // write meta zip let mut vec = Vec::::new(); let mut zip = ZipWriter::new(Cursor::new(&mut vec)); - let options = FileOptions::default().compression_method(CompressionMethod::Stored); + let options = FileOptions::default() + .compression_method(CompressionMethod::Stored); zip.start_file(path, options)?; zip.write(content.as_bytes())?; zip.finish()?; diff --git a/crates/carbon_app/src/managers/minecraft/assets.rs b/crates/carbon_app/src/managers/minecraft/assets.rs index 01d7ff3fe..3e730d23f 100644 --- a/crates/carbon_app/src/managers/minecraft/assets.rs +++ b/crates/carbon_app/src/managers/minecraft/assets.rs @@ -41,15 +41,16 @@ pub async fn load_index( index_id: &str, asset_indexes_path: PathBuf, ) -> anyhow::Result { - let asset_index_bytes = tokio::fs::read(asset_indexes_path.join(format!("{}.json", index_id))) - .await - .with_context(|| { - format!( - "Failed to read asset index `{}` from `{}`", - index_id, - asset_indexes_path.to_string_lossy() - ) - })?; + let asset_index_bytes = + tokio::fs::read(asset_indexes_path.join(format!("{}.json", index_id))) + .await + .with_context(|| { + format!( + "Failed to read asset index `{}` from `{}`", + index_id, + asset_indexes_path.to_string_lossy() + ) + })?; Ok(serde_json::from_slice(&asset_index_bytes)?) } @@ -74,7 +75,8 @@ pub async fn get_assets_dir( assets_path: AssetsPath, resources_dir: PathBuf, ) -> anyhow::Result { - let assets_index = load_index(index_id, assets_path.get_indexes_path()).await?; + let assets_index = + load_index(index_id, assets_path.get_indexes_path()).await?; if assets_index.map_virtual { Ok(AssetsDir::Virtual( assets_path.get_virtual_path().join(index_id), @@ -91,7 +93,8 @@ pub async fn reconstruct_assets( assets_path: AssetsPath, resources_dir: PathBuf, ) -> anyhow::Result<()> { - let assets_index = load_index(index_id, assets_path.get_indexes_path()).await?; + let assets_index = + load_index(index_id, assets_path.get_indexes_path()).await?; let target_path = if assets_index.map_virtual { Some(assets_path.get_virtual_path().join(index_id)) } else if assets_index.map_to_resources { @@ -110,16 +113,18 @@ pub async fn reconstruct_assets( ) })?; - let mut existing_files: HashSet = walkdir::WalkDir::new(&target_path) - .into_iter() - .filter_map(|e| e.ok()) - .map(|e| e.path().to_path_buf()) - .collect(); + let mut existing_files: HashSet = + walkdir::WalkDir::new(&target_path) + .into_iter() + .filter_map(|e| e.ok()) + .map(|e| e.path().to_path_buf()) + .collect(); let objects_path = assets_path.get_objects_path(); for (path, object) in assets_index.objects.iter() { - let object_path = objects_path.join(&object.hash[0..2]).join(&object.hash); + let object_path = + objects_path.join(&object.hash[0..2]).join(&object.hash); let asset_path = target_path.join(path); existing_files.remove(&asset_path); @@ -127,9 +132,14 @@ pub async fn reconstruct_assets( let exists = tokio::fs::try_exists(&asset_path).await.ok(); if exists != Some(true) { if let Some(parent) = asset_path.parent() { - tokio::fs::create_dir_all(parent).await.with_context(|| { - format!("Failed to create directory `{}`", parent.to_string_lossy()) - })?; + tokio::fs::create_dir_all(parent).await.with_context( + || { + format!( + "Failed to create directory `{}`", + parent.to_string_lossy() + ) + }, + )?; } tokio::fs::copy(&object_path, &asset_path) .await diff --git a/crates/carbon_app/src/managers/minecraft/curseforge.rs b/crates/carbon_app/src/managers/minecraft/curseforge.rs index 0c7107af4..6769ead32 100644 --- a/crates/carbon_app/src/managers/minecraft/curseforge.rs +++ b/crates/carbon_app/src/managers/minecraft/curseforge.rs @@ -41,7 +41,9 @@ pub async fn download_modpack_zip( app: &App, cf_addon: &File, target_path: &Path, - progress_percentage_sender: tokio::sync::watch::Sender>, + progress_percentage_sender: tokio::sync::watch::Sender< + UpdateValue<(u64, u64)>, + >, ) -> anyhow::Result<()> { let modpack_download_url = cf_addon .download_url @@ -55,8 +57,9 @@ pub async fn download_modpack_zip( .get_temp() .maketmpfile() .await?; - let file_downloadable = Downloadable::new(&modpack_download_url, file.to_path_buf()) - .with_size(cf_addon.file_length as u64); + let file_downloadable = + Downloadable::new(&modpack_download_url, file.to_path_buf()) + .with_size(cf_addon.file_length as u64); tokio::fs::create_dir_all( &file @@ -71,14 +74,19 @@ pub async fn download_modpack_zip( tokio::spawn(async move { while download_progress_recv.borrow_mut().changed().await.is_ok() { let p = download_progress_recv.borrow(); - progress_percentage_sender - .send_modify(|progress| progress.set((p.current_size, p.total_size))); + progress_percentage_sender.send_modify(|progress| { + progress.set((p.current_size, p.total_size)) + }); } Ok::<_, anyhow::Error>(progress_percentage_sender) }); - carbon_net::download_file(&file_downloadable, Some(download_progress_sender)).await?; + carbon_net::download_file( + &file_downloadable, + Some(download_progress_sender), + ) + .await?; file.rename(target_path).await?; Ok(()) @@ -110,7 +118,8 @@ pub async fn prepare_modpack_from_zip( let mut handles = Vec::new(); let semaphore = Arc::new(tokio::sync::Semaphore::new(20)); - let atomic_counter_download_metadata = Arc::new(std::sync::atomic::AtomicU64::new(0)); + let atomic_counter_download_metadata = + Arc::new(std::sync::atomic::AtomicU64::new(0)); let files_len = manifest.files.len() as u64; @@ -118,7 +127,8 @@ pub async fn prepare_modpack_from_zip( let semaphore = semaphore.clone(); let app = app.clone(); let instance_path = instance_path.clone(); - let progress_percentage_sender_clone = progress_percentage_sender.clone(); + let progress_percentage_sender_clone = + progress_percentage_sender.clone(); let atomic_counter = atomic_counter_download_metadata.clone(); let mod_id = file.project_id; @@ -130,20 +140,25 @@ pub async fn prepare_modpack_from_zip( let cf_manager = &app.modplatforms_manager().curseforge; let CurseForgeResponse { data: mod_file, .. } = cf_manager - .get_mod_file(curseforge::filters::ModFileParameters { mod_id, file_id }) + .get_mod_file(curseforge::filters::ModFileParameters { + mod_id, + file_id, + }) .await?; let instance_path = instance_path.get_mods_path(); // TODO: they could also be other things let downloadable = Downloadable::new( - mod_file - .download_url - .ok_or(anyhow::anyhow!("Failed to get download url for mod"))?, + mod_file.download_url.ok_or(anyhow::anyhow!( + "Failed to get download url for mod" + ))?, instance_path.join(mod_file.file_name), ) .with_size(mod_file.file_length as u64); progress_percentage_sender_clone.send_modify(|progress| { progress.acquire_addon_metadata.set(( - atomic_counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1, + atomic_counter + .fetch_add(1, std::sync::atomic::Ordering::SeqCst) + + 1, files_len, )); }); @@ -175,8 +190,9 @@ pub async fn prepare_modpack_from_zip( } let outpath = match file.enclosed_name() { - Some(path) => Path::new(&override_full_path) - .join(path.strip_prefix(&override_folder_name).unwrap()), + Some(path) => Path::new(&override_full_path).join( + path.strip_prefix(&override_folder_name).unwrap(), + ), None => continue, }; diff --git a/crates/carbon_app/src/managers/minecraft/fabric.rs b/crates/carbon_app/src/managers/minecraft/fabric.rs index 89faaa52f..7303db9d6 100644 --- a/crates/carbon_app/src/managers/minecraft/fabric.rs +++ b/crates/carbon_app/src/managers/minecraft/fabric.rs @@ -45,9 +45,11 @@ pub fn replace_template( ) -> PartialVersionInfo { let mut version_info = template_info.clone(); version_info.id = version_info.id.replace(template, game_version); - version_info.inherits_from = version_info.inherits_from.replace(template, game_version); + version_info.inherits_from = + version_info.inherits_from.replace(template, game_version); for library in version_info.libraries.iter_mut() { - library.name.version = library.name.version.replace(template, game_version); + library.name.version = + library.name.version.replace(template, game_version); } version_info diff --git a/crates/carbon_app/src/managers/minecraft/forge.rs b/crates/carbon_app/src/managers/minecraft/forge.rs index a602bdd1f..08ad019d8 100644 --- a/crates/carbon_app/src/managers/minecraft/forge.rs +++ b/crates/carbon_app/src/managers/minecraft/forge.rs @@ -6,7 +6,9 @@ use std::{ use anyhow::bail; use daedalus::{ - modded::{LoaderVersion, Manifest, PartialVersionInfo, Processor, SidedDataEntry}, + modded::{ + LoaderVersion, Manifest, PartialVersionInfo, Processor, SidedDataEntry, + }, GradleSpecifier, }; use prisma_client_rust::QueryError; @@ -58,7 +60,10 @@ pub async fn get_version( Ok(new_manifest) } -fn get_class_paths_jar(libraries_path: &Path, libraries: &[String]) -> anyhow::Result { +fn get_class_paths_jar( + libraries_path: &Path, + libraries: &[String], +) -> anyhow::Result { let cps = libraries .iter() .map(|library| { @@ -75,15 +80,18 @@ fn get_class_paths_jar(libraries_path: &Path, libraries: &[String]) -> anyhow::R Ok(cps.join(PATH_SEPARATOR)) } -async fn get_processor_main_class(path: String) -> anyhow::Result> { +async fn get_processor_main_class( + path: String, +) -> anyhow::Result> { let main_class = tokio::task::spawn_blocking(move || { let zipfile = std::fs::File::open(&path)?; - let mut archive = zip::ZipArchive::new(zipfile) - .map_err(|_| anyhow::anyhow!("Cannot read processor at {}", path))?; + let mut archive = zip::ZipArchive::new(zipfile).map_err(|_| { + anyhow::anyhow!("Cannot read processor at {}", path) + })?; - let file = archive - .by_name("META-INF/MANIFEST.MF") - .map_err(|_| anyhow::anyhow!("Cannot read processor manifest at {}", path))?; + let file = archive.by_name("META-INF/MANIFEST.MF").map_err(|_| { + anyhow::anyhow!("Cannot read processor manifest at {}", path) + })?; let reader = BufReader::new(file); @@ -205,16 +213,26 @@ pub async fn execute_processors<'callback>( classpath.extend(processor.classpath.clone()); classpath.push(processor.jar.clone()); - let classpath = get_class_paths_jar(&libraries_path.to_path(), &classpath)?; + let classpath = + get_class_paths_jar(&libraries_path.to_path(), &classpath)?; let main_class_path = libraries_path .to_path() .join(processor.jar.parse::()?.into_path()); - let main_class = get_processor_main_class(main_class_path.to_string_lossy().to_string()) - .await? - .ok_or_else(|| { - anyhow::anyhow!("Could not find processor main class for {}", processor.jar) - })?; - let arguments = get_processor_arguments(&libraries_path.to_path(), &processor.args, &data)?; + let main_class = get_processor_main_class( + main_class_path.to_string_lossy().to_string(), + ) + .await? + .ok_or_else(|| { + anyhow::anyhow!( + "Could not find processor main class for {}", + processor.jar + ) + })?; + let arguments = get_processor_arguments( + &libraries_path.to_path(), + &processor.args, + &data, + )?; let child = Command::new(java_binary.to_string_lossy().to_string()) .arg("-cp") @@ -224,7 +242,11 @@ pub async fn execute_processors<'callback>( .output() .await .map_err(|err| { - anyhow::anyhow!("Could not execute processor {}: {}", processor.jar, err) + anyhow::anyhow!( + "Could not execute processor {}: {}", + processor.jar, + err + ) })?; info!("{}", String::from_utf8_lossy(&child.stdout)); diff --git a/crates/carbon_app/src/managers/minecraft/minecraft.rs b/crates/carbon_app/src/managers/minecraft/minecraft.rs index c21f4e9c2..3ee0d296f 100644 --- a/crates/carbon_app/src/managers/minecraft/minecraft.rs +++ b/crates/carbon_app/src/managers/minecraft/minecraft.rs @@ -8,15 +8,15 @@ use crate::{ domain::{ java::{JavaArch, JavaComponent}, minecraft::minecraft::{ - chain_lwjgl_libs_with_base_libs, get_default_jvm_args, is_rule_allowed, - library_is_allowed, OsExt, ARCH_WIDTH, + chain_lwjgl_libs_with_base_libs, get_default_jvm_args, + is_rule_allowed, library_is_allowed, OsExt, ARCH_WIDTH, }, }, }; use anyhow::Context; use daedalus::minecraft::{ - Argument, ArgumentType, ArgumentValue, Library, LibraryGroup, Os, Version, VersionInfo, - VersionManifest, + Argument, ArgumentType, ArgumentValue, Library, LibraryGroup, Os, Version, + VersionInfo, VersionManifest, }; use prisma_client_rust::QueryError; use regex::{Captures, Regex}; @@ -213,7 +213,10 @@ struct ReplacerArgs { user_properties: String, } -fn replace_placeholder(replacer_args: &ReplacerArgs, placeholder: ArgPlaceholder) -> String { +fn replace_placeholder( + replacer_args: &ReplacerArgs, + placeholder: ArgPlaceholder, +) -> String { match placeholder { ArgPlaceholder::AuthPlayerName => replacer_args.player_name.clone(), ArgPlaceholder::VersionName => replacer_args.version_name.clone(), @@ -222,17 +225,27 @@ fn replace_placeholder(replacer_args: &ReplacerArgs, placeholder: ArgPlaceholder .get_data_path() .display() .to_string(), - ArgPlaceholder::AssetsRoot => replacer_args.assets_root.display().to_string(), - ArgPlaceholder::GameAssets => replacer_args.game_assets.display().to_string(), - ArgPlaceholder::AssetsIndexName => replacer_args.assets_index_name.clone(), + ArgPlaceholder::AssetsRoot => { + replacer_args.assets_root.display().to_string() + } + ArgPlaceholder::GameAssets => { + replacer_args.game_assets.display().to_string() + } + ArgPlaceholder::AssetsIndexName => { + replacer_args.assets_index_name.clone() + } ArgPlaceholder::AuthUuid => replacer_args.auth_uuid.clone(), - ArgPlaceholder::AuthAccessToken => replacer_args.auth_access_token.clone(), + ArgPlaceholder::AuthAccessToken => { + replacer_args.auth_access_token.clone() + } ArgPlaceholder::AuthSession => replacer_args.auth_session.clone(), ArgPlaceholder::UserType => replacer_args.user_type.clone(), // Hardcoded to mojang apparently ????? ArgPlaceholder::VersionType => replacer_args.version_type.clone(), ArgPlaceholder::UserProperties => replacer_args.user_properties.clone(), // Not sure what this is, ArgPlaceholder::ClassPath => replacer_args.libraries.clone(), - ArgPlaceholder::NativesDirectory => replacer_args.natives_path.display().to_string(), + ArgPlaceholder::NativesDirectory => { + replacer_args.natives_path.display().to_string() + } ArgPlaceholder::LauncherName => "GDLauncher".to_string(), ArgPlaceholder::LauncherVersion => APP_VERSION.to_string(), ArgPlaceholder::ClasspathSeparator => CLASSPATH_SEPARATOR.to_string(), @@ -288,7 +301,8 @@ pub async fn generate_startup_command( Regex::new(r"--(?P\S+)\s+\$\{(?P[^}]+)\}|(\$\{(?P[^}]+)\})") .unwrap(); - let extra_args_regex = Regex::new(r#"("(?P(\\"|[^"])*)"|(?P([^ ]+)))"#).unwrap(); + let extra_args_regex = + Regex::new(r#"("(?P(\\"|[^"])*)"|(?P([^ ]+)))"#).unwrap(); let player_token = match full_account.type_ { FullAccountType::Offline => "offline".to_owned(), @@ -306,7 +320,8 @@ pub async fn generate_startup_command( ) .await?; - let instance_mapped_assets = matches!(&assets_dir, super::assets::AssetsDir::InstanceMapped(_)); + let instance_mapped_assets = + matches!(&assets_dir, super::assets::AssetsDir::InstanceMapped(_)); let replacer_args = ReplacerArgs { player_name: full_account.username, @@ -356,10 +371,16 @@ pub async fn generate_startup_command( return String::new(); } }; - return format!("--{} {}", caps.name("arg").unwrap().as_str(), value); + return format!( + "--{} {}", + caps.name("arg").unwrap().as_str(), + value + ); } else if let Some(standalone) = caps.name("standalone") { return match standalone.as_str().try_into() { - Ok(standalone) => replace_placeholder(&replacer_args, standalone), + Ok(standalone) => { + replace_placeholder(&replacer_args, standalone) + } Err(err) => { warn!("Failed to parse argument: {}", err); return String::new(); @@ -376,39 +397,41 @@ pub async fn generate_startup_command( .replace("\\\\", "\\") }; - let substitute_arguments = |command: &mut Vec, arguments: &Vec| { - for arg in arguments { - match arg { - Argument::Normal(arg) => { - // fix for pre legacy 1.5.x and older minecraft - // drop --assetsDir arg, they are found automatically inside the instance - // resources folder - if instance_mapped_assets - && (arg.starts_with("--assetsDir") || arg.starts_with("${game_assets}")) - { - continue; - } - - command.push(substitute_argument(arg)) - } - Argument::Ruled { rules, value } => { - let is_allowed = rules - .iter() - .all(|rule| is_rule_allowed(rule, &java_component.arch)); - - match (is_allowed, value) { - (false, _) => {} - (true, ArgumentValue::Single(arg)) => { - command.push(substitute_argument(arg)) + let substitute_arguments = + |command: &mut Vec, arguments: &Vec| { + for arg in arguments { + match arg { + Argument::Normal(arg) => { + // fix for pre legacy 1.5.x and older minecraft + // drop --assetsDir arg, they are found automatically inside the instance + // resources folder + if instance_mapped_assets + && (arg.starts_with("--assetsDir") + || arg.starts_with("${game_assets}")) + { + continue; } - (true, ArgumentValue::Many(arr)) => { - command.extend(arr.iter().map(|arg| substitute_argument(arg))) + + command.push(substitute_argument(arg)) + } + Argument::Ruled { rules, value } => { + let is_allowed = rules.iter().all(|rule| { + is_rule_allowed(rule, &java_component.arch) + }); + + match (is_allowed, value) { + (false, _) => {} + (true, ArgumentValue::Single(arg)) => { + command.push(substitute_argument(arg)) + } + (true, ArgumentValue::Many(arr)) => command.extend( + arr.iter().map(|arg| substitute_argument(arg)), + ), } } } } - } - }; + }; let mut command = Vec::with_capacity(100); @@ -416,7 +439,9 @@ pub async fn generate_startup_command( command.push(format!("-Xms{xms_memory}m")); if let Some(logging_xml) = version.logging { - if let Some(client) = logging_xml.get(&daedalus::minecraft::LoggingConfigName::Client) { + if let Some(client) = + logging_xml.get(&daedalus::minecraft::LoggingConfigName::Client) + { let logging_path = runtime_path .get_logging_configs() .get_client_path(&client.file.id); @@ -477,7 +502,9 @@ pub async fn generate_startup_command( } for cap in extra_args_regex.captures_iter(extra_java_args) { - let ((Some(arg), _) | (_, Some(arg))) = (cap.name("quoted"), cap.name("raw")) else { + let ((Some(arg), _) | (_, Some(arg))) = + (cap.name("quoted"), cap.name("raw")) + else { continue; }; command.push(arg.as_str().replace("\\\"", "\"").replace("\\\\", "\\")); @@ -486,7 +513,9 @@ pub async fn generate_startup_command( if Os::native() == Os::Osx { let lwjgl_3 = version .requires - .map(|requires| requires.iter().any(|require| require.uid == "org.lwjgl3")) + .map(|requires| { + requires.iter().any(|require| require.uid == "org.lwjgl3") + }) .unwrap_or(false); let can_find_start_on_first_thread = command @@ -501,7 +530,10 @@ pub async fn generate_startup_command( command.push("-Dorg.lwjgl.util.Debug=true".to_string()); command.push(version.main_class); - substitute_arguments(&mut command, arguments.get(&ArgumentType::Game).unwrap()); + substitute_arguments( + &mut command, + arguments.get(&ArgumentType::Game).unwrap(), + ); Ok(command) } @@ -603,15 +635,22 @@ pub async fn extract_natives( { match &library.natives { Some(natives) => { - if let Some(native_name) = natives.get(&Os::native_arch(java_arch)) { - extract_single_library_natives(runtime_path, library, &dest, native_name) - .await - .with_context(|| { - format!( - "Failed to extract native `{}` for library `{}`", - &native_name, &library.name - ) - })?; + if let Some(native_name) = + natives.get(&Os::native_arch(java_arch)) + { + extract_single_library_natives( + runtime_path, + library, + &dest, + native_name, + ) + .await + .with_context(|| { + format!( + "Failed to extract native `{}` for library `{}`", + &native_name, &library.name + ) + })?; } } None => continue, @@ -663,7 +702,8 @@ mod tests { .unwrap(); let lwjgl_group = get_lwjgl_meta( - &reqwest_middleware::ClientBuilder::new(reqwest::Client::new()).build(), + &reqwest_middleware::ClientBuilder::new(reqwest::Client::new()) + .build(), &version, &app.minecraft_manager().meta_base_url, ) @@ -708,10 +748,11 @@ mod tests { let command = serde_json::to_string(&command).unwrap(); // write to file - let mut file = - tokio::fs::File::create("./src/managers/minecraft/test_fixtures/test_command.json") - .await - .unwrap(); + let mut file = tokio::fs::File::create( + "./src/managers/minecraft/test_fixtures/test_command.json", + ) + .await + .unwrap(); file.write_all(command.as_bytes()).await.unwrap(); } @@ -739,7 +780,8 @@ mod tests { .unwrap(); let lwjgl_group = get_lwjgl_meta( - &reqwest_middleware::ClientBuilder::new(reqwest::Client::new()).build(), + &reqwest_middleware::ClientBuilder::new(reqwest::Client::new()) + .build(), &version, &app.minecraft_manager().meta_base_url, ) @@ -768,8 +810,13 @@ mod tests { .await .unwrap(); - extract_natives(runtime_path, &version, &lwjgl_group, &JavaArch::X86_64) - .await - .unwrap(); + extract_natives( + runtime_path, + &version, + &lwjgl_group, + &JavaArch::X86_64, + ) + .await + .unwrap(); } } diff --git a/crates/carbon_app/src/managers/minecraft/mod.rs b/crates/carbon_app/src/managers/minecraft/mod.rs index cdc4304c6..12b36fc9f 100644 --- a/crates/carbon_app/src/managers/minecraft/mod.rs +++ b/crates/carbon_app/src/managers/minecraft/mod.rs @@ -38,15 +38,19 @@ impl MinecraftManager { } impl ManagerRef<'_, MinecraftManager> { - pub async fn get_minecraft_manifest(&self) -> anyhow::Result { - minecraft::get_manifest(&self.app.reqwest_client, &self.meta_base_url).await + pub async fn get_minecraft_manifest( + &self, + ) -> anyhow::Result { + minecraft::get_manifest(&self.app.reqwest_client, &self.meta_base_url) + .await } pub async fn get_minecraft_version( self, manifest_version_meta: Version, ) -> anyhow::Result { - minecraft::get_version(&self.app.reqwest_client, manifest_version_meta).await + minecraft::get_version(&self.app.reqwest_client, manifest_version_meta) + .await } pub async fn get_forge_manifest(&self) -> anyhow::Result { @@ -54,7 +58,8 @@ impl ManagerRef<'_, MinecraftManager> { } pub async fn get_fabric_manifest(&self) -> anyhow::Result { - fabric::get_manifest(&self.app.reqwest_client, &self.meta_base_url).await + fabric::get_manifest(&self.app.reqwest_client, &self.meta_base_url) + .await } pub async fn get_quilt_manifest(&self) -> anyhow::Result { @@ -76,8 +81,12 @@ impl ManagerRef<'_, MinecraftManager> { let mut all_files = vec![]; - let lwjgl = - get_lwjgl_meta(&self.app.reqwest_client, &version_info, &self.meta_base_url).await?; + let lwjgl = get_lwjgl_meta( + &self.app.reqwest_client, + &version_info, + &self.meta_base_url, + ) + .await?; let tmp: Vec<_> = version_info .libraries @@ -112,7 +121,9 @@ impl ManagerRef<'_, MinecraftManager> { ); if let Some(logging_xml) = version_info.logging { - if let Some(client) = logging_xml.get(&daedalus::minecraft::LoggingConfigName::Client) { + if let Some(client) = + logging_xml.get(&daedalus::minecraft::LoggingConfigName::Client) + { all_files.push( Downloadable::new( client.file.url.clone(), @@ -121,7 +132,9 @@ impl ManagerRef<'_, MinecraftManager> { .get_client_path(&client.file.id), ) .with_size(client.file.size as u64) - .with_checksum(Some(carbon_net::Checksum::Sha1(client.file.sha1.clone()))), + .with_checksum(Some( + carbon_net::Checksum::Sha1(client.file.sha1.clone()), + )), ); } } @@ -150,7 +163,11 @@ impl UpdateValue { &self.0 } - pub fn update_from(&mut self, from: &Self, update_callback: impl FnOnce(T)) { + pub fn update_from( + &mut self, + from: &Self, + update_callback: impl FnOnce(T), + ) { if self.0 != from.0 { self.0 = from.0; update_callback(self.0); @@ -191,7 +208,8 @@ mod tests { .unwrap(); let runtime_path = &app.app.settings_manager().runtime_path; - let instance_path = runtime_path.get_instances().get_instance_path("test"); + let instance_path = + runtime_path.get_instances().get_instance_path("test"); std::fs::create_dir_all(instance_path.get_root()).unwrap(); @@ -217,7 +235,8 @@ mod tests { .unwrap(); let lwjgl_group = get_lwjgl_meta( - &reqwest_middleware::ClientBuilder::new(reqwest::Client::new()).build(), + &reqwest_middleware::ClientBuilder::new(reqwest::Client::new()) + .build(), &version_info, &app.minecraft_manager().meta_base_url, ) @@ -241,12 +260,17 @@ mod tests { .clone(); let forge_version_info = - crate::managers::minecraft::forge::get_version(&app.reqwest_client, forge_manifest) - .await - .unwrap(); + crate::managers::minecraft::forge::get_version( + &app.reqwest_client, + forge_manifest, + ) + .await + .unwrap(); - let version_info = - daedalus::modded::merge_partial_version(forge_version_info, version_info); + let version_info = daedalus::modded::merge_partial_version( + forge_version_info, + version_info, + ); // -----FORGE @@ -261,7 +285,10 @@ mod tests { let vanilla_files = app .minecraft_manager() - .get_all_version_info_files(version_info.clone(), &java_component.arch) + .get_all_version_info_files( + version_info.clone(), + &java_component.arch, + ) .await .unwrap(); diff --git a/crates/carbon_app/src/managers/minecraft/modrinth.rs b/crates/carbon_app/src/managers/minecraft/modrinth.rs index 641ca3dd6..d01d088be 100644 --- a/crates/carbon_app/src/managers/minecraft/modrinth.rs +++ b/crates/carbon_app/src/managers/minecraft/modrinth.rs @@ -112,7 +112,9 @@ pub async fn download_mrpack( app: &App, mrpack_file: &VersionFile, target_path: &Path, - progress_percentage_sender: tokio::sync::watch::Sender>, + progress_percentage_sender: tokio::sync::watch::Sender< + UpdateValue<(u64, u64)>, + >, ) -> anyhow::Result<()> { let _pack_download_url = mrpack_file.url.clone(); @@ -123,8 +125,9 @@ pub async fn download_mrpack( .get_temp() .maketmpfile() .await?; - let file_downloadable = Downloadable::new(&mrpack_file.url.to_string(), file.to_path_buf()) - .with_size(mrpack_file.size as u64); + let file_downloadable = + Downloadable::new(&mrpack_file.url.to_string(), file.to_path_buf()) + .with_size(mrpack_file.size as u64); tokio::fs::create_dir_all( &file @@ -139,14 +142,19 @@ pub async fn download_mrpack( tokio::spawn(async move { while download_progress_recv.borrow_mut().changed().await.is_ok() { let p = download_progress_recv.borrow(); - progress_percentage_sender - .send_modify(|progress| progress.set((p.current_size, p.total_size))); + progress_percentage_sender.send_modify(|progress| { + progress.set((p.current_size, p.total_size)) + }); } Ok::<_, anyhow::Error>(progress_percentage_sender) }); - carbon_net::download_file(&file_downloadable, Some(download_progress_sender)).await?; + carbon_net::download_file( + &file_downloadable, + Some(download_progress_sender), + ) + .await?; file.rename(target_path).await?; Ok(()) @@ -202,7 +210,8 @@ pub async fn prepare_modpack_from_mrpack( let mut handles = Vec::new(); let semaphore = Arc::new(tokio::sync::Semaphore::new(20)); - let atomic_counter_download_metadata = Arc::new(std::sync::atomic::AtomicU64::new(0)); + let atomic_counter_download_metadata = + Arc::new(std::sync::atomic::AtomicU64::new(0)); let files_len = required_files.len() as u64; @@ -213,7 +222,8 @@ pub async fn prepare_modpack_from_mrpack( let semaphore = semaphore.clone(); let _app = app.clone(); let instance_path = instance_path.clone(); - let progress_percentage_sender_clone = progress_percentage_sender.clone(); + let progress_percentage_sender_clone = + progress_percentage_sender.clone(); let atomic_counter = atomic_counter_download_metadata.clone(); let data_path = instance_path.get_data_path(); @@ -224,15 +234,20 @@ pub async fn prepare_modpack_from_mrpack( let downloadable = Downloadable::new( file.downloads .first() - .ok_or(anyhow::anyhow!("Failed to get download url for mod"))? + .ok_or(anyhow::anyhow!( + "Failed to get download url for mod" + ))? .to_string(), target_path, ) .with_size(file.file_size as u64); - progress_percentage_sender_clone.send(ProgressState::AcquiringPackMetadata( - atomic_counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst), - files_len, - ))?; + progress_percentage_sender_clone.send( + ProgressState::AcquiringPackMetadata( + atomic_counter + .fetch_add(1, std::sync::atomic::Ordering::SeqCst), + files_len, + ), + )?; Ok::(downloadable) }); diff --git a/crates/carbon_app/src/managers/minecraft/quilt.rs b/crates/carbon_app/src/managers/minecraft/quilt.rs index 170f878a4..df30d40c8 100644 --- a/crates/carbon_app/src/managers/minecraft/quilt.rs +++ b/crates/carbon_app/src/managers/minecraft/quilt.rs @@ -45,9 +45,11 @@ pub fn replace_template( ) -> PartialVersionInfo { let mut version_info = template_info.clone(); version_info.id = version_info.id.replace(template, game_version); - version_info.inherits_from = version_info.inherits_from.replace(template, game_version); + version_info.inherits_from = + version_info.inherits_from.replace(template, game_version); for library in version_info.libraries.iter_mut() { - library.name.version = library.name.version.replace(template, game_version); + library.name.version = + library.name.version.replace(template, game_version); } version_info diff --git a/crates/carbon_app/src/managers/mod.rs b/crates/carbon_app/src/managers/mod.rs index ef2ae556d..7435ae9ae 100644 --- a/crates/carbon_app/src/managers/mod.rs +++ b/crates/carbon_app/src/managers/mod.rs @@ -51,8 +51,9 @@ mod app { use crate::cache_middleware; use super::{ - java::JavaManager, metadata::cache::MetaCacheManager, metrics::MetricsManager, - modplatforms::ModplatformsManager, system_info::SystemInfoManager, *, + java::JavaManager, metadata::cache::MetaCacheManager, + metrics::MetricsManager, modplatforms::ModplatformsManager, + system_info::SystemInfoManager, *, }; pub struct AppInner { @@ -75,7 +76,9 @@ mod app { macro_rules! manager_getter { ($manager:ident: $type:path) => { - pub(crate) fn $manager<'a>(self: &'a Arc) -> ManagerRef<'a, $type> { + pub(crate) fn $manager<'a>( + self: &'a Arc, + ) -> ManagerRef<'a, $type> { ManagerRef { manager: &self.$manager, app: &self, @@ -89,11 +92,13 @@ mod app { invalidation_channel: broadcast::Sender, runtime_path: PathBuf, ) -> App { - let db_client = prisma_client::load_and_migrate(runtime_path.clone()) - .await - .unwrap(); + let db_client = + prisma_client::load_and_migrate(runtime_path.clone()) + .await + .unwrap(); - let app = Arc::new(UnsafeCell::new(MaybeUninit::::uninit())); + let app = + Arc::new(UnsafeCell::new(MaybeUninit::::uninit())); let unsaferef = UnsafeAppRef(Arc::downgrade(&app)); // SAFETY: cannot be used until after the ref is initialized. @@ -115,7 +120,10 @@ mod app { let inner = Arc::into_raw(app); (*inner).get().write(MaybeUninit::new(AppInner { - settings_manager: SettingsManager::new(runtime_path, reqwest.clone()), + settings_manager: SettingsManager::new( + runtime_path, + reqwest.clone(), + ), java_manager: JavaManager::new(), minecraft_manager: MinecraftManager::new(), account_manager: AccountManager::new(), @@ -129,7 +137,8 @@ mod app { prisma_client: Arc::new(db_client), task_manager: VisualTaskManager::new(), system_info_manager: SystemInfoManager::new(), - rich_presence_manager: rich_presence::RichPresenceManager::new(), + rich_presence_manager: + rich_presence::RichPresenceManager::new(), })); // SAFETY: This pointer cast is safe because UnsafeCell and MaybeUninit do not @@ -150,7 +159,8 @@ mod app { let _app = app.clone(); tokio::spawn(async move { - let _ = _app.clone().rich_presence_manager().start_presence().await; + let _ = + _app.clone().rich_presence_manager().start_presence().await; }); app @@ -217,8 +227,12 @@ impl Drop for AppInner { debug!("Collecting metric for app close"); let res = self.metrics_manager.track_event(close_event).await; match res { - Ok(_) => debug!("Successfully collected metric for app close"), - Err(e) => error!("Error collecting metric for app close: {e}"), + Ok(_) => { + debug!("Successfully collected metric for app close") + } + Err(e) => { + error!("Error collecting metric for app close: {e}") + } } }); } diff --git a/crates/carbon_app/src/managers/modplatforms/curseforge.rs b/crates/carbon_app/src/managers/modplatforms/curseforge.rs index 2dd33477f..e3ce1e616 100644 --- a/crates/carbon_app/src/managers/modplatforms/curseforge.rs +++ b/crates/carbon_app/src/managers/modplatforms/curseforge.rs @@ -7,9 +7,9 @@ use url::Url; use crate::{ domain::modplatforms::curseforge::{ filters::{ - FilesParameters, ModDescriptionParameters, ModFileChangelogParameters, - ModFileParameters, ModFilesParameters, ModParameters, ModSearchParameters, - ModsParameters, + FilesParameters, ModDescriptionParameters, + ModFileChangelogParameters, ModFileParameters, ModFilesParameters, + ModParameters, ModSearchParameters, ModsParameters, }, Category, CurseForgeResponse, File, FingerprintsMatchesResult, Mod, }, @@ -32,7 +32,9 @@ impl CurseForge { } #[tracing::instrument(skip(self))] - pub async fn get_categories(&self) -> anyhow::Result>> { + pub async fn get_categories( + &self, + ) -> anyhow::Result>> { let mut url = self.base_url.join("categories")?; url.set_query(Some("gameId=432")); @@ -78,7 +80,9 @@ impl CurseForge { .get(url.as_str()) .send() .await? - .json_with_context_reporting::>>("curseforge::search") + .json_with_context_reporting::>>( + "curseforge::search", + ) .await?; Ok(resp) @@ -100,7 +104,9 @@ impl CurseForge { .get(url.as_str()) .send() .await? - .json_with_context_reporting::>("curseforge::get_mod") + .json_with_context_reporting::>( + "curseforge::get_mod", + ) .await?; Ok(resp) @@ -129,7 +135,9 @@ impl CurseForge { .body(body.to_string()) .send() .await? - .json_with_context_reporting::>>("curseforge::get_mods") + .json_with_context_reporting::>>( + "curseforge::get_mods", + ) .await?; Ok(resp) @@ -201,7 +209,9 @@ impl CurseForge { .get(url.as_str()) .send() .await? - .json_with_context_reporting::>("curseforge::get_mod_file") + .json_with_context_reporting::>( + "curseforge::get_mod_file", + ) .await?; Ok(resp) } @@ -250,7 +260,9 @@ impl CurseForge { .json(&body) .send() .await? - .json_with_context_reporting::>>("curseforge::get_files") + .json_with_context_reporting::>>( + "curseforge::get_files", + ) .await?; Ok(resp) diff --git a/crates/carbon_app/src/managers/modplatforms/mod.rs b/crates/carbon_app/src/managers/modplatforms/mod.rs index c8bb0e738..75bab9539 100644 --- a/crates/carbon_app/src/managers/modplatforms/mod.rs +++ b/crates/carbon_app/src/managers/modplatforms/mod.rs @@ -13,10 +13,12 @@ pub struct ModplatformsManager { impl ModplatformsManager { pub fn new(unsafeappref: UnsafeAppRef) -> Self { Self { - curseforge: curseforge::CurseForge::new(cache_middleware::new_client( - unsafeappref.clone(), - get_client(), - )), + curseforge: curseforge::CurseForge::new( + cache_middleware::new_client( + unsafeappref.clone(), + get_client(), + ), + ), modrinth: modrinth::Modrinth::new(cache_middleware::new_client( unsafeappref, get_client(), diff --git a/crates/carbon_app/src/managers/modplatforms/modrinth.rs b/crates/carbon_app/src/managers/modplatforms/modrinth.rs index ea7cb89fa..c5f777bf5 100644 --- a/crates/carbon_app/src/managers/modplatforms/modrinth.rs +++ b/crates/carbon_app/src/managers/modplatforms/modrinth.rs @@ -7,12 +7,13 @@ use crate::{ domain::modplatforms::modrinth::{ project::{Project, ProjectVersionsFilters}, responses::{ - CategoriesResponse, LoadersResponse, ProjectsResponse, TeamResponse, - VersionHashesResponse, VersionsResponse, + CategoriesResponse, LoadersResponse, ProjectsResponse, + TeamResponse, VersionHashesResponse, VersionsResponse, }, search::{ - ProjectID, ProjectIDs, ProjectSearchParameters, ProjectSearchResponse, TeamID, TeamIDs, - VersionHashesQuery, VersionID, VersionIDs, + ProjectID, ProjectIDs, ProjectSearchParameters, + ProjectSearchResponse, TeamID, TeamIDs, VersionHashesQuery, + VersionID, VersionIDs, }, version::Version, }, @@ -90,7 +91,10 @@ impl Modrinth { } #[tracing::instrument(skip(self))] - pub async fn get_project(&self, project: ProjectID) -> anyhow::Result { + pub async fn get_project( + &self, + project: ProjectID, + ) -> anyhow::Result { let url = self.base_url.join(&format!("project/{}", &*project))?; trace!("GET {}", url); @@ -117,11 +121,15 @@ impl Modrinth { let mut query_pairs = url.query_pairs_mut(); if let Some(game_version) = filters.game_version { - query_pairs.append_pair("game_versions", &format!(r#"["{}"]"#, &game_version)); + query_pairs.append_pair( + "game_versions", + &format!(r#"["{}"]"#, &game_version), + ); } if let Some(loaders) = filters.loaders { - query_pairs.append_pair("loaders", &format!(r#"["{}"]"#, &loaders)); + query_pairs + .append_pair("loaders", &format!(r#"["{}"]"#, &loaders)); } } @@ -138,7 +146,10 @@ impl Modrinth { } #[tracing::instrument(skip(self))] - pub async fn get_projects(&self, projects: ProjectIDs) -> anyhow::Result { + pub async fn get_projects( + &self, + projects: ProjectIDs, + ) -> anyhow::Result { let mut url = self.base_url.join("projects")?; let query = projects.into_query_parameters()?; url.set_query(Some(&query)); @@ -156,7 +167,10 @@ impl Modrinth { } #[tracing::instrument(skip(self))] - pub async fn get_version(&self, version: VersionID) -> anyhow::Result { + pub async fn get_version( + &self, + version: VersionID, + ) -> anyhow::Result { let url = self.base_url.join(&format!("version/{}", &*version))?; trace!("GET {}", url); @@ -172,7 +186,10 @@ impl Modrinth { } #[tracing::instrument(skip(self))] - pub async fn get_versions(&self, version_ids: VersionIDs) -> anyhow::Result { + pub async fn get_versions( + &self, + version_ids: VersionIDs, + ) -> anyhow::Result { let mut url = self.base_url.join("versions")?; let query = version_ids.into_query_parameters()?; url.set_query(Some(&query)); @@ -231,7 +248,10 @@ impl Modrinth { } #[tracing::instrument(skip(self))] - pub async fn get_teams(&self, team_ids: TeamIDs) -> anyhow::Result> { + pub async fn get_teams( + &self, + team_ids: TeamIDs, + ) -> anyhow::Result> { let mut url = self.base_url.join("teams")?; let query = team_ids.into_query_parameters()?; url.set_query(Some(&query)); @@ -243,16 +263,23 @@ impl Modrinth { .get(url.as_str()) .send() .await? - .json_with_context_reporting::>("modrinth::get_teams") + .json_with_context_reporting::>( + "modrinth::get_teams", + ) .await? .into_iter() - .map(|team| team.into_iter().filter(|member| member.accepted).collect()) + .map(|team| { + team.into_iter().filter(|member| member.accepted).collect() + }) .collect::>(); Ok(teams) } #[tracing::instrument(skip(self))] - pub async fn get_project_team(&self, project: ProjectID) -> anyhow::Result { + pub async fn get_project_team( + &self, + project: ProjectID, + ) -> anyhow::Result { let url = self .base_url .join(&format!("project/{}/members", &*project))?; @@ -264,7 +291,9 @@ impl Modrinth { .get(url.as_str()) .send() .await? - .json_with_context_reporting::("modrinth::get_project_team") + .json_with_context_reporting::( + "modrinth::get_project_team", + ) .await? .into_iter() .filter(|member| member.accepted) @@ -488,7 +517,9 @@ mod test { let results = modrinth .get_versions_from_hash(&VersionHashesQuery { - hashes: vec!["09b63cb3bf2bf6ea89967684d352f58f7951b242".to_string()], + hashes: vec![ + "09b63cb3bf2bf6ea89967684d352f58f7951b242".to_string() + ], algorithm: HashAlgorithm::SHA1, }) .await?; diff --git a/crates/carbon_app/src/managers/prisma_client.rs b/crates/carbon_app/src/managers/prisma_client.rs index edeb381da..289c9df47 100644 --- a/crates/carbon_app/src/managers/prisma_client.rs +++ b/crates/carbon_app/src/managers/prisma_client.rs @@ -26,7 +26,9 @@ pub enum DatabaseError { } #[instrument] -pub(super) async fn load_and_migrate(runtime_path: PathBuf) -> Result { +pub(super) async fn load_and_migrate( + runtime_path: PathBuf, +) -> Result { let runtime_path = dunce::simplified(&runtime_path); let db_uri = format!( @@ -114,7 +116,9 @@ async fn seed_init_db(db_client: &PrismaClient) -> Result<(), DatabaseError> { .metrics_enabled_last_update; if let Some(metrics_enabled_last_update) = metrics_enabled_last_update { - if metrics_enabled_last_update < chrono::Utc::now() - chrono::Duration::days(365) { + if metrics_enabled_last_update + < chrono::Utc::now() - chrono::Duration::days(365) + { db_client .app_configuration() .update( diff --git a/crates/carbon_app/src/managers/settings/mod.rs b/crates/carbon_app/src/managers/settings/mod.rs index bc4ee5542..ea4655628 100644 --- a/crates/carbon_app/src/managers/settings/mod.rs +++ b/crates/carbon_app/src/managers/settings/mod.rs @@ -19,7 +19,10 @@ pub(crate) struct SettingsManager { } impl SettingsManager { - pub fn new(runtime_path: PathBuf, reqwest_client: ClientWithMiddleware) -> Self { + pub fn new( + runtime_path: PathBuf, + reqwest_client: ClientWithMiddleware, + ) -> Self { Self { runtime_path: runtime_path::RuntimePath::new(runtime_path), terms_and_privacy: TermsAndPrivacy::new(reqwest_client), @@ -28,7 +31,9 @@ impl SettingsManager { } impl ManagerRef<'_, SettingsManager> { - pub async fn get_settings(self) -> anyhow::Result { + pub async fn get_settings( + self, + ) -> anyhow::Result { self.app .prisma_client .app_configuration() @@ -39,7 +44,10 @@ impl ManagerRef<'_, SettingsManager> { } #[tracing::instrument(skip(self))] - pub async fn set_settings(self, incoming_settings: FESettingsUpdate) -> anyhow::Result<()> { + pub async fn set_settings( + self, + incoming_settings: FESettingsUpdate, + ) -> anyhow::Result<()> { let db = &self.app.prisma_client; let crate::db::app_configuration::Data { @@ -77,7 +85,8 @@ impl ManagerRef<'_, SettingsManager> { something_changed = true; } - if let Some(discord_integration) = incoming_settings.discord_integration { + if let Some(discord_integration) = incoming_settings.discord_integration + { queries.push(self.app.prisma_client.app_configuration().update( app_configuration::id::equals(0), vec![app_configuration::discord_integration::set( @@ -97,7 +106,9 @@ impl ManagerRef<'_, SettingsManager> { something_changed = true; } - if let Some(concurrent_downloads) = incoming_settings.concurrent_downloads { + if let Some(concurrent_downloads) = + incoming_settings.concurrent_downloads + { queries.push(self.app.prisma_client.app_configuration().update( app_configuration::id::equals(0), vec![app_configuration::concurrent_downloads::set( @@ -152,7 +163,9 @@ impl ManagerRef<'_, SettingsManager> { if let Some(java_custom_args) = incoming_settings.java_custom_args { queries.push(self.app.prisma_client.app_configuration().update( app_configuration::id::equals(0), - vec![app_configuration::java_custom_args::set(java_custom_args)], + vec![app_configuration::java_custom_args::set( + java_custom_args, + )], )); something_changed = true; } @@ -160,12 +173,16 @@ impl ManagerRef<'_, SettingsManager> { if let Some(auto_manage_java) = incoming_settings.auto_manage_java { queries.push(self.app.prisma_client.app_configuration().update( app_configuration::id::equals(0), - vec![app_configuration::auto_manage_java::set(auto_manage_java)], + vec![app_configuration::auto_manage_java::set( + auto_manage_java, + )], )); something_changed = true; } - if let Some(preferred_mod_channel) = incoming_settings.preferred_mod_channel { + if let Some(preferred_mod_channel) = + incoming_settings.preferred_mod_channel + { queries.push(self.app.prisma_client.app_configuration().update( app_configuration::id::equals(0), vec![app_configuration::preferred_mod_channel::set( @@ -174,7 +191,9 @@ impl ManagerRef<'_, SettingsManager> { )); } - if let Some(terms_and_privacy_accepted) = incoming_settings.terms_and_privacy_accepted { + if let Some(terms_and_privacy_accepted) = + incoming_settings.terms_and_privacy_accepted + { queries.push(self.app.prisma_client.app_configuration().update( app_configuration::id::equals(0), vec![app_configuration::terms_and_privacy_accepted::set( @@ -199,7 +218,9 @@ impl ManagerRef<'_, SettingsManager> { app_configuration::id::equals(0), vec![ app_configuration::metrics_enabled::set(metrics_enabled), - app_configuration::metrics_enabled_last_update::set(Some(Utc::now().into())), + app_configuration::metrics_enabled_last_update::set(Some( + Utc::now().into(), + )), ], )); @@ -223,7 +244,10 @@ impl ManagerRef<'_, SettingsManager> { Ok(()) } - pub async fn set(self, value: app_configuration::SetParam) -> anyhow::Result<()> { + pub async fn set( + self, + value: app_configuration::SetParam, + ) -> anyhow::Result<()> { self.app .prisma_client .app_configuration() diff --git a/crates/carbon_app/src/managers/settings/terms_and_privacy.rs b/crates/carbon_app/src/managers/settings/terms_and_privacy.rs index b88154b30..be0c716bc 100644 --- a/crates/carbon_app/src/managers/settings/terms_and_privacy.rs +++ b/crates/carbon_app/src/managers/settings/terms_and_privacy.rs @@ -8,8 +8,10 @@ use uuid::Uuid; use crate::{app_version::APP_VERSION, managers::GDL_API_BASE}; -const BASE_GH_API_REPO_URL: &str = "https://api.github.com/repos/gorilla-devs/ToS-Privacy"; -const BASE_GH_REPO_URL: &str = "https://raw.githubusercontent.com/gorilla-devs/ToS-Privacy"; +const BASE_GH_API_REPO_URL: &str = + "https://api.github.com/repos/gorilla-devs/ToS-Privacy"; +const BASE_GH_REPO_URL: &str = + "https://raw.githubusercontent.com/gorilla-devs/ToS-Privacy"; #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] diff --git a/crates/carbon_app/src/managers/vtask.rs b/crates/carbon_app/src/managers/vtask.rs index 68377d9b0..8174bfbf8 100644 --- a/crates/carbon_app/src/managers/vtask.rs +++ b/crates/carbon_app/src/managers/vtask.rs @@ -91,7 +91,10 @@ impl ManagerRef<'_, VisualTaskManager> { } } - pub async fn dismiss_task(self, task_id: VisualTaskId) -> anyhow::Result<()> { + pub async fn dismiss_task( + self, + task_id: VisualTaskId, + ) -> anyhow::Result<()> { let mut tasklist = self.tasks.write().await; let task = tasklist.get(&task_id).ok_or(InvalidTaskIdError)?; @@ -110,7 +113,10 @@ impl ManagerRef<'_, VisualTaskManager> { } #[cfg(test)] - pub async fn wait_with_log(self, task_id: VisualTaskId) -> anyhow::Result<()> { + pub async fn wait_with_log( + self, + task_id: VisualTaskId, + ) -> anyhow::Result<()> { use tracing::info; let tasklist = self.tasks.read().await; @@ -139,11 +145,13 @@ impl ManagerRef<'_, VisualTaskManager> { for task in domain.active_subtasks { let progress = match task.progress { domain::SubtaskProgress::Opaque => String::from("opaque"), - domain::SubtaskProgress::Download { downloaded, total } => format!( - "{}kb / {}kb", - downloaded as f32 * 0.001, - total as f32 * 0.001 - ), + domain::SubtaskProgress::Download { downloaded, total } => { + format!( + "{}kb / {}kb", + downloaded as f32 * 0.001, + total as f32 * 0.001 + ) + } domain::SubtaskProgress::Item { current, total } => { format!("{current} / {total}") } @@ -333,7 +341,9 @@ impl VisualTask { name: name.into(), progress: match state { TaskState::Indeterminate => domain::Progress::Indeterminate, - TaskState::KnownProgress => domain::Progress::Known(self.progress_float().await), + TaskState::KnownProgress => { + domain::Progress::Known(self.progress_float().await) + } TaskState::Failed(error) => domain::Progress::Failed(error), }, downloaded, @@ -377,7 +387,12 @@ impl Subtask { // complete_on_match is an explicit parameter instead of a following call to make sure // a conscious decision is made on a case by case basis. - pub fn update_download(&self, downloaded: u32, total: u32, complete_on_match: bool) { + pub fn update_download( + &self, + downloaded: u32, + total: u32, + complete_on_match: bool, + ) { self.update_progress(Progress::Download { downloaded, total, diff --git a/crates/carbon_app/src/runtime_path_override.rs b/crates/carbon_app/src/runtime_path_override.rs index 9152816eb..d72dc4afc 100644 --- a/crates/carbon_app/src/runtime_path_override.rs +++ b/crates/carbon_app/src/runtime_path_override.rs @@ -22,8 +22,9 @@ pub(crate) async fn get_runtime_path_override() -> PathBuf { let data_path = path.expect("Runtime path not found").join("data"); - fs::create_dir_all(&data_path) - .expect(format!("Failed to create data directory: {:?}", data_path).as_str()); + fs::create_dir_all(&data_path).expect( + format!("Failed to create data directory: {:?}", data_path).as_str(), + ); dunce::canonicalize(data_path).unwrap() } diff --git a/crates/carbon_compression/src/lib.rs b/crates/carbon_compression/src/lib.rs index a29265643..0a834dfb0 100644 --- a/crates/carbon_compression/src/lib.rs +++ b/crates/carbon_compression/src/lib.rs @@ -35,7 +35,9 @@ impl CompressionFormat { } } -fn detect_compression_format(file: &mut T) -> Result +fn detect_compression_format( + file: &mut T, +) -> Result where T: Read, { @@ -94,7 +96,10 @@ where use std::os::unix::fs::PermissionsExt; if let Some(mode) = file.unix_mode() { - std::fs::set_permissions(&outpath, std::fs::Permissions::from_mode(mode))?; + std::fs::set_permissions( + &outpath, + std::fs::Permissions::from_mode(mode), + )?; } } } @@ -113,7 +118,10 @@ where Ok(()) } -fn decompress_gzip(archive_path: PathBuf, dest_folder: PathBuf) -> Result<(), CompressionError> { +fn decompress_gzip( + archive_path: PathBuf, + dest_folder: PathBuf, +) -> Result<(), CompressionError> { let archive_file = std::fs::File::open(&archive_path)?; let mut archive = flate2::read::GzDecoder::new(archive_file); @@ -138,7 +146,10 @@ fn decompress_gzip(archive_path: PathBuf, dest_folder: PathBuf) -> Result<(), Co // TODO: Ideally decompression would recursively look for another compressed file until it can't find any more. // accept both paths and strings -pub async fn decompress(path: T, dest_folder: &Path) -> Result<(), CompressionError> +pub async fn decompress( + path: T, + dest_folder: &Path, +) -> Result<(), CompressionError> where T: AsRef + Send + Sync, { @@ -188,7 +199,8 @@ mod tests { let format = detect_compression_format(&mut file).unwrap(); assert_eq!(CompressionFormat::Tar, format); - let mut file = std::fs::File::open("fixtures/compressed.tar.gz").unwrap(); + let mut file = + std::fs::File::open("fixtures/compressed.tar.gz").unwrap(); let format = detect_compression_format(&mut file).unwrap(); assert_eq!(CompressionFormat::Gzip, format); diff --git a/crates/carbon_macro/src/lib.rs b/crates/carbon_macro/src/lib.rs index 02e5e9425..c93cfc53f 100644 --- a/crates/carbon_macro/src/lib.rs +++ b/crates/carbon_macro/src/lib.rs @@ -3,7 +3,10 @@ use quote::quote; use syn::{parse_macro_input, Data, DeriveInput, Fields}; #[proc_macro_attribute] -pub fn into_query_parameters(_attr: TokenStream, item: TokenStream) -> TokenStream { +pub fn into_query_parameters( + _attr: TokenStream, + item: TokenStream, +) -> TokenStream { let input = parse_macro_input!(item as DeriveInput); let struct_name = input.ident; let fields = match input.data { diff --git a/crates/carbon_net/src/lib.rs b/crates/carbon_net/src/lib.rs index f77722251..e5c94cad3 100644 --- a/crates/carbon_net/src/lib.rs +++ b/crates/carbon_net/src/lib.rs @@ -219,13 +219,15 @@ pub async fn download_multiple( let downloads = Arc::new(tokio::sync::Semaphore::new(concurrency)); - let mut tasks: Vec>> = vec![]; + let mut tasks: Vec>> = + vec![]; let arced_progress = Arc::new(progress); let progress_counter = Arc::new(AtomicU64::new(0)); let file_counter = Arc::new(AtomicU64::new(0)); - let total_size = Arc::new(AtomicU64::new(files.iter().filter_map(|f| f.size).sum())); + let total_size = + Arc::new(AtomicU64::new(files.iter().filter_map(|f| f.size).sum())); let total_count = files.len() as u64; From f7e2f9b60548ac9271b302ed4a8360b681b10500 Mon Sep 17 00:00:00 2001 From: Jose Quesada Date: Fri, 3 Nov 2023 08:17:57 -0600 Subject: [PATCH 3/4] Revert "added `rustfmt.toml`" This reverts commit ddbc1a8d4d3f1c88b85216ef19c02f67f2a2a040. --- rustfmt.toml | 1 - 1 file changed, 1 deletion(-) delete mode 100644 rustfmt.toml diff --git a/rustfmt.toml b/rustfmt.toml deleted file mode 100644 index df99c6919..000000000 --- a/rustfmt.toml +++ /dev/null @@ -1 +0,0 @@ -max_width = 80 From f18c98a769b0b4fe427de18321a1f1315ff875a1 Mon Sep 17 00:00:00 2001 From: Jose Quesada Date: Fri, 3 Nov 2023 08:21:31 -0600 Subject: [PATCH 4/4] leave `rustfmt.toml` with default settings --- rustfmt.toml | 1 + 1 file changed, 1 insertion(+) create mode 100644 rustfmt.toml diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1 @@ +