From 30662045b1b3d0f065684d8bbc660843fac3c646 Mon Sep 17 00:00:00 2001 From: null8626 Date: Mon, 23 Sep 2024 16:53:31 +0700 Subject: [PATCH] refactor: use fs::write instead of File::create + f.write_all --- rustfmt.toml | 4 ++++ src/app/downloading.rs | 14 ++++++------ src/app/from_string.rs | 30 ++++++++++++------------ src/app/mod.rs | 4 ++-- src/commands/add/modrinth.rs | 6 ++--- src/commands/cache.rs | 10 ++++---- src/commands/env/workflow_packwiz.rs | 10 ++++---- src/commands/env/workflow_test.rs | 10 ++++---- src/commands/init/mod.rs | 29 ++++++++++++------------ src/commands/version.rs | 6 ++--- src/core/mod.rs | 7 ++---- src/core/scripts.rs | 4 ++-- src/core/serverjar.rs | 11 ++++----- src/hot_reload/config.rs | 11 ++------- src/hot_reload/mod.rs | 20 ++++++++-------- src/interop/hooks.rs | 2 +- src/interop/markdown.rs | 34 +++++++++++++--------------- src/interop/packwiz.rs | 22 ++++++++---------- src/main.rs | 2 +- src/model/downloadable/markdown.rs | 22 +++++++++--------- src/model/downloadable/mod.rs | 6 ++--- src/model/network.rs | 12 ++++------ src/model/servertoml.rs | 12 ++++------ src/model/servertype/interactive.rs | 2 +- src/model/servertype/meta.rs | 20 ++++++++-------- src/model/servertype/mod.rs | 12 +++++----- src/sources/curserinth.rs | 2 +- src/sources/github.rs | 4 ++-- src/sources/hangar.rs | 8 +++---- src/sources/maven.rs | 2 +- src/sources/modrinth.rs | 2 +- src/util/env.rs | 21 +++++++++-------- src/util/mod.rs | 2 +- 33 files changed, 176 insertions(+), 187 deletions(-) create mode 100644 rustfmt.toml diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..4a3edc2 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,4 @@ +edition = "2021" +match_block_trailing_comma = true +newline_style = "Unix" +use_field_init_shorthand = true \ No newline at end of file diff --git a/src/app/downloading.rs b/src/app/downloading.rs index fdb287a..c50983c 100644 --- a/src/app/downloading.rs +++ b/src/app/downloading.rs @@ -151,11 +151,11 @@ impl App { )? { 0 => { tokio::fs::remove_dir_all(&file_path).await?; - } + }, 1 => { self.notify(Prefix::SkippedWarning, progress_bar.message()); return Ok(resolved); - } + }, 2 => bail!(message), _ => unreachable!(), } @@ -208,10 +208,10 @@ impl App { cached.to_string_lossy() )); None - } + }, _ => Some((cached, cached_size)), } - } + }, _ => None, } { progress_bar.disable_steady_tick(); @@ -276,9 +276,9 @@ impl App { } progress_bar.set_length(len); - } + }, (Some(size), None) | (None, Some(size)) => progress_bar.set_length(size), - _ => {} + _ => {}, } progress_bar.disable_steady_tick(); @@ -318,7 +318,7 @@ impl App { if let Some(cached_file_path) = match &resolved.cache { CacheStrategy::File { namespace, path } => { self.get_cache(namespace).map(|c| c.path(path)) - } + }, CacheStrategy::Indexed { .. } => todo!(), CacheStrategy::None => None, } { diff --git a/src/app/from_string.rs b/src/app/from_string.rs index 40bc523..bb79ffc 100644 --- a/src/app/from_string.rs +++ b/src/app/from_string.rs @@ -21,28 +21,28 @@ impl App { id: id.to_owned(), version: version.to_owned(), }) - } + }, ("cr" | "cf" | "curseforge" | "curserinth", id) => { let (id, version) = id.split_once(',').unwrap_or((id, "latest")); Ok(Downloadable::CurseRinth { id: id.to_owned(), version: version.to_owned(), }) - } + }, ("hangar" | "h", id) => { let (id, version) = id.split_once(',').unwrap_or((id, "latest")); Ok(Downloadable::Hangar { id: id.to_owned(), version: version.to_owned(), }) - } + }, ("spigot" | "spiget", id) => { let (id, version) = id.split_once(',').unwrap_or((id, "latest")); Ok(Downloadable::Spigot { id: id.to_owned(), version: version.to_owned(), }) - } + }, ("ghrel" | "gh" | "github", id) => { let (repo, tag) = id.split_once(',').unwrap_or((id, "latest")); @@ -51,7 +51,7 @@ impl App { tag: tag.to_owned(), asset: "first".to_owned(), }) - } + }, (ty, _) => bail!("Unknown identifier '{ty}'"), } } else { @@ -76,7 +76,7 @@ impl App { id: id.to_owned().to_owned(), version: version.to_owned().to_owned(), }) - } + }, (Some("modrinth.com"), ["mod" | "plugin" | "datapack", id, rest @ ..]) => { let version = if let ["version", v] = rest { @@ -112,7 +112,7 @@ impl App { id: id.to_owned().to_owned(), version: version.clone(), }) - } + }, (Some("curserinth.kuylar.dev"), ["mod", id, rest @ ..]) => { let version = if let ["version", v] = rest { @@ -148,7 +148,7 @@ impl App { id: (*id).to_string(), version, }) - } + }, // https://www.curseforge.com/minecraft/mc-mods/betterwithpatches (Some("www.curseforge.com"), ["minecraft", "mc-mods", id, rest @ ..]) => { @@ -184,7 +184,7 @@ impl App { }; Ok(Downloadable::CurseRinth { id, version }) - } + }, // https://www.spigotmc.org/resources/http-requests.101253/ (Some("www.spigotmc.org"), ["resources", id]) => Ok(Downloadable::Spigot { @@ -266,7 +266,7 @@ impl App { tag: tag.to_string(), asset, }) - } + }, (domain, path) => { let def = match domain { @@ -278,7 +278,7 @@ impl App { } else { 0 } - } + }, }; let selection = self.select_with_default( @@ -310,7 +310,7 @@ impl App { filename: Some(input), desc: if desc.is_empty() { None } else { Some(desc) }, }) - } + }, 1 => { // TODO: ... let j_url = if self.confirm(&format!( @@ -359,7 +359,7 @@ impl App { build, artifact, }) - } + }, 2 => { let mut repo = None; let mut group_id = None; @@ -464,10 +464,10 @@ impl App { version, filename, }) - } + }, _ => unreachable!(), } - } + }, } } } diff --git a/src/app/mod.rs b/src/app/mod.rs index a83204d..36944d8 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -148,7 +148,7 @@ impl App { } } list - } + }, AddonType::Mod => { let mut list: Vec = self.server.mods.clone(); if let Some(nw) = &self.network { @@ -173,7 +173,7 @@ impl App { } } list - } + }, } } diff --git a/src/commands/add/modrinth.rs b/src/commands/add/modrinth.rs index b586e36..b76bb48 100644 --- a/src/commands/add/modrinth.rs +++ b/src/commands/add/modrinth.rs @@ -94,7 +94,7 @@ pub async fn run(mut app: App, args: Args) -> Result<()> { } { "modpack" => { todo!("Modpack importing currently unsupported") - } + }, "mod" => { app.add_addon_inferred(Downloadable::Modrinth { id: project.slug.clone(), @@ -104,7 +104,7 @@ pub async fn run(mut app: App, args: Args) -> Result<()> { app.save_changes()?; app.notify(Prefix::Imported, format!("{} from modrinth", project.title)); app.refresh_markdown().await?; - } + }, "datapack" => { app.add_datapack(Downloadable::Modrinth { id: project.slug.clone(), @@ -113,7 +113,7 @@ pub async fn run(mut app: App, args: Args) -> Result<()> { app.save_changes()?; app.refresh_markdown().await?; - } + }, ty => bail!("Unsupported modrinth project type: '{ty}'"), } diff --git a/src/commands/cache.rs b/src/commands/cache.rs index 3fe0af6..b810c71 100644 --- a/src/commands/cache.rs +++ b/src/commands/cache.rs @@ -29,7 +29,7 @@ pub fn run(commands: Commands) -> Result<()> { match commands { Commands::Path => { println!("{}", cache_folder.to_string_lossy()); - } + }, Commands::List { detailed } => { println!( @@ -65,11 +65,11 @@ pub fn run(commands: Commands) -> Result<()> { } println!(" {all} entries in {namespaces} namespaces in total"); - } + }, Commands::Open => { opener::open(cache_folder).context("Opening cache folder")?; - } + }, Commands::Clear => { let pb = ProgressBar::new_spinner() @@ -89,11 +89,11 @@ pub fn run(commands: Commands) -> Result<()> { pb.finish_and_clear(); println!(" Cache has been cleared"); - } + }, } Ok(()) - } + }, None => bail!("Cache directory was missing, maybe it's disabled?"), } diff --git a/src/commands/env/workflow_packwiz.rs b/src/commands/env/workflow_packwiz.rs index a8107f0..30023aa 100644 --- a/src/commands/env/workflow_packwiz.rs +++ b/src/commands/env/workflow_packwiz.rs @@ -1,7 +1,6 @@ -use std::{io::Write, path::Path}; +use std::{fs, path::Path}; use anyhow::Result; -use std::fs::File; use crate::{app::App, util::env::get_git_root}; @@ -10,8 +9,11 @@ pub fn run(app: &App) -> Result<()> { .join(".github") .join("workflows"); - let mut f = File::create(path.join("packwiz.yml"))?; - f.write_all(include_bytes!("../../../res/workflows/packwiz.yml"))?; + fs::write( + path.join("packwiz.yml"), + include_bytes!("../../../res/workflows/packwiz.yml"), + )?; + app.success("packwiz.yml workflow created"); Ok(()) diff --git a/src/commands/env/workflow_test.rs b/src/commands/env/workflow_test.rs index 6407fc9..aff88d2 100644 --- a/src/commands/env/workflow_test.rs +++ b/src/commands/env/workflow_test.rs @@ -1,7 +1,6 @@ -use std::{io::Write, path::Path}; +use std::{fs, path::Path}; use anyhow::Result; -use std::fs::File; use crate::{app::App, util::env::get_git_root}; @@ -10,8 +9,11 @@ pub fn run(app: &App) -> Result<()> { .join(".github") .join("workflows"); - let mut f = File::create(path.join("test.yml"))?; - f.write_all(include_bytes!("../../../res/workflows/test.yml"))?; + fs::write( + path.join("test.yml"), + include_bytes!("../../../res/workflows/test.yml"), + )?; + app.success("test.yml workflow created"); Ok(()) diff --git a/src/commands/init/mod.rs b/src/commands/init/mod.rs index 67ad15d..133a08d 100644 --- a/src/commands/init/mod.rs +++ b/src/commands/init/mod.rs @@ -8,7 +8,6 @@ use std::{ env, ffi::OsStr, fs::{self, File}, - io::Write, path::Path, }; use tempfile::Builder; @@ -103,7 +102,7 @@ pub async fn run(base_app: BaseApp, args: Args) -> Result<()> { match &ty { InitType::Normal | InitType::MRPack(_) => { app.server.name = app.prompt_string_filled("Server name?", &app.server.name)?; - } + }, InitType::Packwiz(source) => { let pack = source .parse_toml::("pack.toml") @@ -111,11 +110,11 @@ pub async fn run(base_app: BaseApp, args: Args) -> Result<()> { .context("Reading pack.toml - does it exist?")?; app.server.name = app.prompt_string_filled("Server name?", &pack.name)?; - } + }, InitType::Network => { app.network.as_mut().unwrap().name = app.prompt_string_filled("Network name?", &app.network.as_ref().unwrap().name)?; - } + }, } match &ty { @@ -158,7 +157,7 @@ pub async fn run(base_app: BaseApp, args: Args) -> Result<()> { app.prompt_string_default("Server version?", &latest_ver)? }; - } + }, InitType::Network => { let nw = app.network.as_mut().unwrap(); @@ -169,7 +168,7 @@ pub async fn run(base_app: BaseApp, args: Args) -> Result<()> { .interact_text()?; nw.port = port; - } + }, InitType::MRPack(src) => { let tmp_dir = Builder::new().prefix("mcman-mrpack-import").tempdir()?; @@ -191,10 +190,10 @@ pub async fn run(base_app: BaseApp, args: Args) -> Result<()> { app.mrpack() .import_all(MRPackReader::from_reader(f)?, None) .await?; - } + }, InitType::Packwiz(src) => { app.packwiz().import_from_source(src.clone()).await?; - } + }, } match ty { @@ -208,7 +207,7 @@ pub async fn run(base_app: BaseApp, args: Args) -> Result<()> { } match ty { - InitType::Network => {} + InitType::Network => {}, _ => { if let Some(ref mut nw) = app.network { if nw.servers.contains_key(&app.server.name) { @@ -225,7 +224,7 @@ pub async fn run(base_app: BaseApp, args: Args) -> Result<()> { app.info("Added server entry to network.toml"); } } - } + }, } //env @@ -235,8 +234,10 @@ pub async fn run(base_app: BaseApp, args: Args) -> Result<()> { fs::create_dir_all("./config")?; if app.server.jar.get_software_type() != SoftwareType::Proxy { - let mut f = File::create("./config/server.properties")?; - f.write_all(include_bytes!("../../../res/server.properties"))?; + fs::write( + "./config/server.properties", + include_bytes!("../../../res/server.properties"), + )?; } } @@ -257,8 +258,8 @@ pub async fn run(base_app: BaseApp, args: Args) -> Result<()> { if app.confirm("Render markdown now?")? { app.markdown().update_files().await?; } - } - _ => {} + }, + _ => {}, } } diff --git a/src/commands/version.rs b/src/commands/version.rs index 06f27ab..b3dc11d 100644 --- a/src/commands/version.rs +++ b/src/commands/version.rs @@ -36,10 +36,10 @@ pub async fn run(base_app: BaseApp, args: Args) -> Result<()> { match Version::parse(env!("CARGO_PKG_VERSION"))?.cmp(&latest_ver) { Ordering::Equal => { println!(" > up to date!"); - } + }, Ordering::Greater => { println!(" {}", style("> version is newer (dev/unreleased)").yellow()); - } + }, Ordering::Less => { println!( " {}\n {} {} => {}\n {} {}/releases/tag/{latest_ver}", @@ -50,7 +50,7 @@ pub async fn run(base_app: BaseApp, args: Args) -> Result<()> { style("|").cyan(), env!("CARGO_PKG_REPOSITORY"), ); - } + }, } } diff --git a/src/core/mod.rs b/src/core/mod.rs index 13a0818..917963c 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -3,7 +3,7 @@ use std::{collections::HashMap, fmt::Debug, path::PathBuf, process::Child, time: use anyhow::{Context, Result}; use console::style; use indicatif::{FormattedDuration, ProgressBar}; -use tokio::{fs::File, io::AsyncWriteExt}; +use tokio::fs; use crate::{ app::{AddonType, App, Resolvable, ResolvedFile}, @@ -97,10 +97,7 @@ impl<'a> BuildContext<'a> { } if self.app.server.launcher.eula_args && !self.app.server.jar.supports_eula_args() { - File::create(self.output_dir.join("eula.txt")) - .await? - .write_all(b"eula=true\n") - .await?; + fs::write(self.output_dir.join("eula.txt"), b"eula=true\n").await?; self.app.log("eula.txt written"); } diff --git a/src/core/scripts.rs b/src/core/scripts.rs index 3282934..7cc0945 100644 --- a/src/core/scripts.rs +++ b/src/core/scripts.rs @@ -22,7 +22,7 @@ impl<'a> BuildContext<'a> { "@libraries/net/neoforged/forge/{mcver}-{l}/unix_args.txt" )], } - } + }, ServerType::Forge { loader } => { let l = self.app.forge().resolve_version(loader).await?; @@ -34,7 +34,7 @@ impl<'a> BuildContext<'a> { "@libraries/net/minecraftforge/forge/{mcver}-{l}/unix_args.txt" )], } - } + }, _ => StartupMethod::Jar(serverjar_name.to_owned()), }) } diff --git a/src/core/serverjar.rs b/src/core/serverjar.rs index 7c0e04f..42aa904 100644 --- a/src/core/serverjar.rs +++ b/src/core/serverjar.rs @@ -47,7 +47,7 @@ impl<'a> BuildContext<'a> { .context("resolving quilt loader version id (latest/latest-beta)")? ), } - } + }, ServerType::NeoForge { loader } => InstallMethod::Installer { name: "NeoForged Installer", label: "nfi", @@ -93,7 +93,7 @@ impl<'a> BuildContext<'a> { } ), } - } + }, _ => InstallMethod::SingleJar, }) } @@ -187,13 +187,13 @@ impl<'a> BuildContext<'a> { } jar_name - } + }, InstallMethod::SingleJar => { self.downloadable(&self.app.server.jar, "", None) .await? .1 .filename - } + }, }; Ok(serverjar_name) @@ -237,8 +237,7 @@ impl<'a> BuildContext<'a> { let buf = buf.trim(); if !buf.is_empty() { - log_file.write_all(buf.as_bytes()).await?; - log_file.write_all(b"\n").await?; + log_file.write_all(format!("{buf}\n").as_bytes()).await?; if let Some(last_line) = buf.split('\n').last() { spinner.set_message(last_line.to_string()); diff --git a/src/hot_reload/config.rs b/src/hot_reload/config.rs index 9c526c9..82f9156 100644 --- a/src/hot_reload/config.rs +++ b/src/hot_reload/config.rs @@ -1,9 +1,4 @@ -use std::{ - collections::HashMap, - fs::{self, File}, - io::Write, - path::PathBuf, -}; +use std::{collections::HashMap, fs, path::PathBuf}; use anyhow::{anyhow, Result}; use glob::Pattern; @@ -80,9 +75,7 @@ impl HotReloadConfig { } pub fn save(&self) -> Result<()> { - let cfg_str = toml::to_string_pretty(&self)?; - let mut f = File::create(&self.path)?; - f.write_all(cfg_str.as_bytes())?; + fs::write(&self.path, toml::to_string_pretty(&self)?)?; Ok(()) } diff --git a/src/hot_reload/mod.rs b/src/hot_reload/mod.rs index f9dac69..0edec2c 100644 --- a/src/hot_reload/mod.rs +++ b/src/hot_reload/mod.rs @@ -385,7 +385,7 @@ impl<'a> DevSession<'a> { TestResult::Success => { self.builder.app.success("Test passed"); process::exit(0); - } + }, TestResult::Crashed | TestResult::Failed => { mp.suspend(|| { println!("{} Test failed!", ColorfulTheme::default().error_prefix); @@ -485,7 +485,7 @@ impl<'a> DevSession<'a> { } process::exit(1); - } + }, } } @@ -508,13 +508,13 @@ impl<'a> DevSession<'a> { tx.blocking_send(Command::Log(String::from("Reloaded hotreload.toml"))) .unwrap(); *guard = updated; - } + }, Err(e) => { tx.blocking_send(Command::Log(format!( "Error reloading hotreload.toml: {e}" ))) .unwrap(); - } + }, } } }, @@ -562,18 +562,18 @@ impl<'a> DevSession<'a> { "reload confirm\n".to_owned(), )) .expect("tx send err"); - } + }, HotReloadAction::Restart => { tx.blocking_send(Command::SendCommand("stop\nend\n".to_owned())) .expect("tx send err"); tx.blocking_send(Command::WaitUntilExit) .expect("tx send err"); tx.blocking_send(Command::Start).expect("tx send err"); - } + }, HotReloadAction::RunCommand(cmd) => { tx.blocking_send(Command::SendCommand(format!("{cmd}\n"))) .expect("tx send err"); - } + }, } } } @@ -639,18 +639,18 @@ impl<'a> DevSession<'a> { "reload confirm\n".to_owned(), )) .expect("tx send err"); - } + }, HotReloadAction::Restart => { tx.blocking_send(Command::SendCommand("stop\nend\n".to_owned())) .expect("tx send err"); tx.blocking_send(Command::WaitUntilExit) .expect("tx send err"); tx.blocking_send(Command::Start).expect("tx send err"); - } + }, HotReloadAction::RunCommand(cmd) => { tx.blocking_send(Command::SendCommand(format!("{cmd}\n"))) .expect("tx send err"); - } + }, } } } diff --git a/src/interop/hooks.rs b/src/interop/hooks.rs index d1adbc8..3d56b2a 100644 --- a/src/interop/hooks.rs +++ b/src/interop/hooks.rs @@ -96,7 +96,7 @@ impl<'a> HooksAPI<'a> { self.0.success(format!("Hook {filename}")); } else { match hook.onfail { - HookFailBehavior::Ignore => {} + HookFailBehavior::Ignore => {}, HookFailBehavior::Warn => self.0.warn(format!("Hook {filename} failed")), HookFailBehavior::Error => bail!("Hook {filename} failed"), } diff --git a/src/interop/markdown.rs b/src/interop/markdown.rs index ca38163..8bbabe1 100644 --- a/src/interop/markdown.rs +++ b/src/interop/markdown.rs @@ -1,10 +1,9 @@ -use std::{borrow::Cow, fs::File, io::Write, time::Duration}; +use std::{borrow::Cow, fs, time::Duration}; use anyhow::{Context, Result}; use indexmap::IndexMap; use indicatif::{ProgressBar, ProgressIterator, ProgressStyle}; use regex::Regex; -use tokio::io::AsyncWriteExt; use crate::{ app::{App, Prefix}, @@ -21,7 +20,6 @@ pub struct MarkdownAPI<'a>(pub &'a App); impl<'a> MarkdownAPI<'a> { pub fn init_server(&self) -> Result<()> { - let mut f = File::create(self.0.server.path.join("README.md"))?; let readme_content = include_str!("../../res/default_readme") .replace("{SERVER_NAME}", &self.0.server.name) .replace( @@ -33,19 +31,20 @@ impl<'a> MarkdownAPI<'a> { }, ); - f.write_all(readme_content.as_bytes())?; - - Ok(()) + Ok(fs::write( + self.0.server.path.join("README.md"), + readme_content, + )?) } pub fn init_network(&self) -> Result<()> { - let mut f = File::create(self.0.network.as_ref().unwrap().path.join("README.md"))?; let readme_content = include_str!("../../res/default_readme_network") .replace("{NETWORK_NAME}", &self.0.network.as_ref().unwrap().name); - f.write_all(readme_content.as_bytes())?; - - Ok(()) + Ok(fs::write( + self.0.network.as_ref().unwrap().path.join("README.md"), + readme_content, + )?) } pub async fn update_files(&self) -> Result<()> { @@ -101,8 +100,7 @@ impl<'a> MarkdownAPI<'a> { .to_string(); } - let mut f = tokio::fs::File::create(&path).await?; - f.write_all(content.as_bytes()).await?; + tokio::fs::write(&path, content).await?; self.0.notify(Prefix::Rendered, filename.to_string()); } @@ -275,13 +273,13 @@ impl<'a> MarkdownAPI<'a> { sanitize(&proj.description)?, version.clone(), ) - } + }, Downloadable::CurseRinth { id, version } => { let proj = self.0.curserinth().fetch_project(id).await?; (format!("{} [CF](https://www.curseforge.com/minecraft/mc-mods/{id}) [CR](https://curserinth.kuylar.dev/mod/{id})", proj.title, id = proj.slug), sanitize(&proj.description)?, version.clone()) - } + }, Downloadable::Spigot { id, version } => { let (name, desc) = self.0.spigot().fetch_info(id).await?; @@ -291,7 +289,7 @@ impl<'a> MarkdownAPI<'a> { sanitize(&desc)?, version.clone(), ) - } + }, Downloadable::Hangar { id, version } => { let proj = mcapi::hangar::fetch_project(&self.0.http_client, id).await?; @@ -305,7 +303,7 @@ impl<'a> MarkdownAPI<'a> { sanitize(&proj.description)?, version.clone(), ) - } + }, Downloadable::GithubRelease { repo, tag, asset } => { let desc = self.0.github().fetch_repo_description(repo).await?; @@ -315,7 +313,7 @@ impl<'a> MarkdownAPI<'a> { sanitize(&desc)?, format!("{tag} / `{asset}`"), ) - } + }, Downloadable::Jenkins { url, @@ -330,7 +328,7 @@ impl<'a> MarkdownAPI<'a> { sanitize(&desc)?, format!("{build} / `{artifact}`"), ) - } + }, Downloadable::Maven { version, artifact, .. diff --git a/src/interop/packwiz.rs b/src/interop/packwiz.rs index 6960ab0..b5227a6 100644 --- a/src/interop/packwiz.rs +++ b/src/interop/packwiz.rs @@ -11,7 +11,7 @@ use rpackwiz::model::{ DownloadMode, HashFormat, Mod, ModDownload, ModUpdate, Pack, PackFile, PackIndex, }; use serde::de::DeserializeOwned; -use tokio::{fs::File, io::AsyncWriteExt}; +use tokio::fs::{self, File}; use walkdir::WalkDir; use crate::{ @@ -32,7 +32,7 @@ impl FileProvider { Self::LocalFolder(folder) => { let str = tokio::fs::read_to_string(folder.join(path)).await?; Ok(toml::from_str(&str)?) - } + }, Self::RemoteURL(http_client, url) => { let contents = http_client .get(url.join(path)?) @@ -43,7 +43,7 @@ impl FileProvider { .await?; Ok(toml::from_str(&contents)?) - } + }, } } } @@ -112,7 +112,7 @@ impl<'a> PackwizInterop<'a> { match &source { FileProvider::LocalFolder(folder) => { tokio::fs::copy(folder.join(&file.file), output_path).await?; - } + }, FileProvider::RemoteURL(_, url) => { self.0 .download_resolved( @@ -140,7 +140,7 @@ impl<'a> PackwizInterop<'a> { .insert_after(&pb, ProgressBar::new_spinner()), ) .await?; - } + }, } } } @@ -235,10 +235,10 @@ impl<'a> PackwizInterop<'a> { progress_bar.set_message("Saving index..."); - let mut f = File::create(output_dir.join("index.toml")).await?; let content = toml::to_string_pretty(&index)?; let index_hash = App::hash_sha256(&content); - f.write_all(content.as_bytes()).await?; + + fs::write(output_dir.join("index.toml"), content).await?; let pack = Pack { pack_format: "packwiz:1.1.0".to_owned(), @@ -262,9 +262,7 @@ impl<'a> PackwizInterop<'a> { }, }; - let mut f = File::create(output_dir.join("pack.toml")).await?; - f.write_all(toml::to_string_pretty(&pack)?.as_bytes()) - .await?; + fs::write(output_dir.join("pack.toml"), toml::to_string_pretty(&pack)?).await?; progress_bar.finish_and_clear(); self.0.success("Exported to packwiz successfully"); @@ -301,12 +299,10 @@ impl<'a> PackwizInterop<'a> { let filename = format!("{}.pw.toml", m.name); let path = output_dir.join("mods").join(&filename); - let mut f = File::create(path).await?; - let content = toml::to_string_pretty(&m)?; let hash = App::hash_sha256(&content); - f.write_all(content.as_bytes()).await?; + fs::write(path, content).await?; self.0.notify(Prefix::Exported, format!("mods/{filename}")); diff --git a/src/main.rs b/src/main.rs index 3df8a01..4f41903 100644 --- a/src/main.rs +++ b/src/main.rs @@ -116,6 +116,6 @@ async fn main() -> Result<()> { _ => unreachable!(), } - } + }, } } diff --git a/src/model/downloadable/markdown.rs b/src/model/downloadable/markdown.rs index f24cfa6..a980960 100644 --- a/src/model/downloadable/markdown.rs +++ b/src/model/downloadable/markdown.rs @@ -14,28 +14,28 @@ impl Downloadable { } else { format!("Custom {hyperlink}") } - } + }, Self::GithubRelease { repo, .. } => { format!("[{repo}](https://github.com/{repo})") - } + }, Self::Hangar { id, .. } => { format!("[{id}](https://hangar.papermc.io/{id})") - } + }, Self::Jenkins { url, job, .. } => { format!("[{job}]({})", JenkinsAPI::get_url(url, job)) - } + }, Self::Maven { url, group, .. } => { format!("[{g}]({url}/{g})", g = group.replace('.', "/")) - } + }, Self::Spigot { id, .. } => { format!("[{id}](https://www.spigotmc.org/resources/{id})") - } + }, Self::Modrinth { id, .. } => { format!("[{id}](https://modrinth.com/mod/{id})") - } + }, Self::CurseRinth { id, .. } => { format!("`{id}`[CF](https://www.curseforge.com/minecraft/mc-mods/{id}) [CR](https://curserinth.kuylar.dev/mod/{id})") - } + }, } } @@ -67,7 +67,7 @@ impl Downloadable { Self::GithubRelease { repo, tag, asset } => { (repo.clone(), Some(asset.clone()), Some(tag.clone())) - } + }, Self::Modrinth { id, version } | Self::CurseRinth { id, version } @@ -125,12 +125,12 @@ impl Downloadable { } else { "URL".to_string() } - } + }, Self::Maven { group, artifact, .. } => { format!("Maven:{group}.{artifact}") - } + }, } } } diff --git a/src/model/downloadable/mod.rs b/src/model/downloadable/mod.rs index 72e00e6..6e5da3d 100644 --- a/src/model/downloadable/mod.rs +++ b/src/model/downloadable/mod.rs @@ -108,7 +108,7 @@ impl Resolvable for Downloadable { Self::Hangar { id, version } => app.hangar().resolve_source(id, version).await, Self::GithubRelease { repo, tag, asset } => { app.github().resolve_source(repo, tag, asset).await - } + }, Self::Jenkins { url, job, @@ -118,7 +118,7 @@ impl Resolvable for Downloadable { app.jenkins() .resolve_source(url, job, build, artifact) .await - } + }, Self::Maven { url, group, @@ -129,7 +129,7 @@ impl Resolvable for Downloadable { app.maven() .resolve_source(url, group, artifact, version, filename) .await - } + }, } } } diff --git a/src/model/network.rs b/src/model/network.rs index c9df8e9..8296b7b 100644 --- a/src/model/network.rs +++ b/src/model/network.rs @@ -1,8 +1,7 @@ use std::{ collections::HashMap, env, - fs::{read_to_string, File}, - io::Write, + fs::{self, read_to_string}, path::{Path, PathBuf}, }; @@ -87,11 +86,10 @@ impl Network { } pub fn save(&self) -> Result<()> { - let cfg_str = toml::to_string_pretty(&self)?; - let mut f = File::create(self.path.join("network.toml"))?; - f.write_all(cfg_str.as_bytes())?; - - Ok(()) + Ok(fs::write( + self.path.join("network.toml"), + toml::to_string_pretty(&self)?, + )?) } pub fn next_port(&self) -> u16 { diff --git a/src/model/servertoml.rs b/src/model/servertoml.rs index 00af156..247d52d 100644 --- a/src/model/servertoml.rs +++ b/src/model/servertoml.rs @@ -1,8 +1,7 @@ use std::{ collections::HashMap, env, - fs::{read_to_string, File}, - io::Write, + fs::{self, read_to_string}, path::{Path, PathBuf}, }; @@ -132,11 +131,10 @@ impl Server { } pub fn save(&self) -> Result<()> { - let cfg_str = toml::to_string_pretty(&self)?; - let mut f = File::create(self.path.join("server.toml"))?; - f.write_all(cfg_str.as_bytes())?; - - Ok(()) + Ok(fs::write( + self.path.join("server.toml"), + toml::to_string_pretty(&self)?, + )?) } pub fn format(&self, str: &str) -> String { diff --git a/src/model/servertype/interactive.rs b/src/model/servertype/interactive.rs index cd0bfba..db42dff 100644 --- a/src/model/servertype/interactive.rs +++ b/src/model/servertype/interactive.rs @@ -52,7 +52,7 @@ impl ServerType { .interact()?; items[idx].0.clone() - } + }, _ => unreachable!(), }) } diff --git a/src/model/servertype/meta.rs b/src/model/servertype/meta.rs index 920175d..8807574 100644 --- a/src/model/servertype/meta.rs +++ b/src/model/servertype/meta.rs @@ -25,15 +25,15 @@ impl ServerType { Self::Paper {} => "[Paper](https://papermc.io/software/paper)".to_owned(), Self::BuildTools { .. } => { "[BuildTools](https://www.spigotmc.org/wiki/buildtools/)".to_owned() - } + }, Self::BungeeCord {} => { "[BungeeCord](https://www.spigotmc.org/wiki/bungeecord/)".to_owned() - } + }, Self::Fabric { .. } => "[Fabric](https://fabricmc.net/)".to_owned(), Self::Purpur { .. } => "[Purpur](https://github.com/PurpurMC/Purpur)".to_owned(), Self::PaperMC { project, build } => { format!("[PaperMC/{project}](https://github.com/PaperMC/{project}); build {build}") - } + }, Self::Quilt { .. } => "[Quilt](https://quiltmc.org/)".to_owned(), Self::NeoForge { .. } => "[NeoForge](https://neoforged.net/)".to_owned(), Self::Forge { .. } => "[Forge](https://forums.minecraftforge.net/)".to_owned(), @@ -51,15 +51,15 @@ impl ServerType { if installer != "latest" { map.insert(Cow::Borrowed("Installer"), format!("`{installer}`")); } - } + }, Self::NeoForge { loader } | Self::Forge { loader } => { map.insert(Cow::Borrowed("Loader"), version_id!(loader)); - } + }, Self::PaperMC { build, .. } | Self::Purpur { build } => { map.insert(Cow::Borrowed("Build"), version_id!(build, |id| "`#{id}`")); - } + }, Self::Downloadable { inner } => match inner { Downloadable::Jenkins { @@ -70,7 +70,7 @@ impl ServerType { if artifact != "first" { map.insert(Cow::Borrowed("Artifact"), format!("`{artifact}`")); } - } + }, Downloadable::GithubRelease { tag, asset, .. } => { map.insert(Cow::Borrowed("Release"), version_id!(tag)); @@ -78,12 +78,12 @@ impl ServerType { if asset != "first" { map.insert(Cow::Borrowed("Asset"), format!("`{asset}`")); } - } + }, - _ => {} + _ => {}, }, - _ => {} + _ => {}, } map diff --git a/src/model/servertype/mod.rs b/src/model/servertype/mod.rs index ff04b75..b949a8b 100644 --- a/src/model/servertype/mod.rs +++ b/src/model/servertype/mod.rs @@ -98,7 +98,7 @@ impl ServerType { Self::Velocity {} | Self::BungeeCord {} | Self::Waterfall {} => SoftwareType::Proxy, Self::PaperMC { project, .. } if project == "velocity" || project == "waterfall" => { SoftwareType::Proxy - } + }, Self::Quilt { .. } | Self::Fabric { .. } | Self::NeoForge { .. } @@ -166,11 +166,11 @@ impl Resolvable for ServerType { ServerType::Vanilla {} => app.vanilla().resolve_source(version).await, ServerType::PaperMC { project, build } => { app.papermc().resolve_source(project, version, build).await - } + }, ServerType::Purpur { build } => app.purpur().resolve_source(version, build).await, ServerType::Fabric { loader, installer } => { app.fabric().resolve_source(loader, installer).await - } + }, ServerType::Quilt { installer, .. } => app.quilt().resolve_installer(installer).await, ServerType::NeoForge { loader } => app.neoforge().resolve_source(loader).await, ServerType::Forge { loader } => app.forge().resolve_source(loader).await, @@ -179,17 +179,17 @@ impl Resolvable for ServerType { app.papermc() .resolve_source("paper", version, "latest") .await - } + }, ServerType::Velocity {} => { app.papermc() .resolve_source("velocity", version, "latest") .await - } + }, ServerType::Waterfall {} => { app.papermc() .resolve_source("waterfall", version, "latest") .await - } + }, ServerType::BungeeCord {} => bungeecord().resolve_source(app).await, ServerType::Downloadable { inner } => inner.resolve_source(app).await, } diff --git a/src/sources/curserinth.rs b/src/sources/curserinth.rs index 40126c7..f172cfe 100644 --- a/src/sources/curserinth.rs +++ b/src/sources/curserinth.rs @@ -109,7 +109,7 @@ impl<'a> CurserinthAPI<'a> { versions.first().ok_or(anyhow!( "No compatible versions for CurseRinth project '{id}' (version 'latest')" ))? - } + }, ver => unfiltered_versions .iter() .find(|v| v.id == ver) diff --git a/src/sources/github.rs b/src/sources/github.rs index 2d30ad8..91ad13d 100644 --- a/src/sources/github.rs +++ b/src/sources/github.rs @@ -36,7 +36,7 @@ impl GithubWaitRatelimit for reqwest::Response { async fn wait_ratelimit(self) -> Result { Ok(match self.headers().get("x-ratelimit-remaining") { Some(h) => { - if String::from_utf8_lossy(h.as_bytes()) == "1" { + if h.as_bytes() == b"1" { let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs(); let ratelimit_reset = String::from_utf8_lossy(self.headers()["x-ratelimit-reset"].as_bytes()) @@ -47,7 +47,7 @@ impl GithubWaitRatelimit for reqwest::Response { } self - } + }, None => self.error_for_status()?, }) diff --git a/src/sources/hangar.rs b/src/sources/hangar.rs index 94e39a4..acaa040 100644 --- a/src/sources/hangar.rs +++ b/src/sources/hangar.rs @@ -59,16 +59,16 @@ impl<'a> HangarAPI<'a> { ServerType::Velocity {} => Some(mcapi::hangar::Platform::Velocity), ServerType::PaperMC { project, .. } if project == "waterfall" => { Some(mcapi::hangar::Platform::Waterfall) - } + }, ServerType::PaperMC { project, .. } if project == "velocity" => { Some(mcapi::hangar::Platform::Velocity) - } + }, ServerType::PaperMC { project, .. } if project == "paper" => { Some(mcapi::hangar::Platform::Paper) - } + }, ServerType::Paper {} | ServerType::Purpur { .. } => { Some(mcapi::hangar::Platform::Paper) - } + }, _ => None, } } diff --git a/src/sources/maven.rs b/src/sources/maven.rs index a95a6bd..c0f7a97 100644 --- a/src/sources/maven.rs +++ b/src/sources/maven.rs @@ -171,7 +171,7 @@ impl<'a> MavenAPI<'a> { .or_else(|| versions.iter().find(|v| v.contains(&id))) .ok_or(anyhow!("Couldn't resolve maven artifact version (url={url},g={group_id},a={artifact_id})"))? .clone() - } + }, }; Ok(version) diff --git a/src/sources/modrinth.rs b/src/sources/modrinth.rs index bfbeb67..a3a2fef 100644 --- a/src/sources/modrinth.rs +++ b/src/sources/modrinth.rs @@ -110,7 +110,7 @@ pub trait ModrinthWaitRatelimit { impl ModrinthWaitRatelimit for reqwest::Response { async fn wait_ratelimit(self) -> Result { let res = if let Some(h) = self.headers().get("x-ratelimit-remaining") { - if String::from_utf8_lossy(h.as_bytes()) == "1" { + if h.as_bytes() == b"1" { let ratelimit_reset = String::from_utf8_lossy(self.headers()["x-ratelimit-reset"].as_bytes()) .parse::()?; diff --git a/src/util/env.rs b/src/util/env.rs index c82d5e0..f25f5c0 100644 --- a/src/util/env.rs +++ b/src/util/env.rs @@ -1,7 +1,6 @@ use std::{ ffi::OsStr, - fs::{self, File}, - io::Write, + fs, path::{Path, PathBuf}, process::Command, }; @@ -76,9 +75,9 @@ pub fn write_gitignore() -> Result { } } - let contents = list.join(if has_r { "\r\n" } else { "\n" }) + if has_r { "\r\n" } else { "\n" }; + let newline = if has_r { "\r\n" } else { "\n" }; - fs::write(&gitignore_path, contents)?; + fs::write(&gitignore_path, list.join(newline) + newline)?; Ok(gitignore_path) } @@ -132,15 +131,17 @@ where } pub fn write_dockerfile(folder: &Path) -> Result<()> { - let mut f = File::create(folder.join("Dockerfile"))?; - f.write_all(include_bytes!("../../res/default_dockerfile"))?; - Ok(()) + Ok(fs::write( + folder.join("Dockerfile"), + include_bytes!("../../res/default_dockerfile"), + )?) } pub fn write_dockerignore(folder: &Path) -> Result<()> { - let mut f = File::create(folder.join(".dockerignore"))?; - f.write_all(include_bytes!("../../res/default_dockerignore"))?; - Ok(()) + Ok(fs::write( + folder.join(".dockerignore"), + include_bytes!("../../res/default_dockerignore"), + )?) } pub fn get_docker_version() -> Result { diff --git a/src/util/mod.rs b/src/util/mod.rs index fe7317f..bbd8de3 100644 --- a/src/util/mod.rs +++ b/src/util/mod.rs @@ -50,7 +50,7 @@ pub fn get_latest_semver(list: &[String]) -> Option { (Ok(_), Err(_)) => Ordering::Greater, _ => Ordering::Equal, } - } + }, (Some(_), None) => Ordering::Greater, (None, Some(_)) => Ordering::Less, _ => Ordering::Equal,