Skip to content

Commit

Permalink
Merge pull request #55 from null8626/main
Browse files Browse the repository at this point in the history
[perf,refactor,style]: performance improvements and large-scale code cleanup
  • Loading branch information
TheAlan404 authored Jan 31, 2024
2 parents 7272124 + ee8b8f5 commit 944771c
Show file tree
Hide file tree
Showing 56 changed files with 540 additions and 597 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ Submit a PR or open an issue if you have a mcman-server repository that we can a
> "makes even oracle linux usable"
- PureComedi

> "it's ok"
- null

> "I'm technically a contributor"
- Trash Panda

Expand Down
1 change: 1 addition & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
edition = "2021"
31 changes: 17 additions & 14 deletions src/app/actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::{
};

use super::{AddonType, App, Prefix};
use std::borrow::Cow;

impl App {
pub fn save_changes(&self) -> Result<()> {
Expand All @@ -28,23 +29,23 @@ impl App {
}
}

pub fn add_addon_inferred(&mut self, addon: &Downloadable) -> Result<()> {
pub fn add_addon_inferred(&mut self, addon: Downloadable) -> Result<()> {
let addon_type = match self.server.jar.get_software_type() {
SoftwareType::Modded => AddonType::Mod,
SoftwareType::Normal | SoftwareType::Proxy => AddonType::Plugin,
SoftwareType::Unknown => self.select(
"Import as?",
&[
SelectItem(AddonType::Mod, "Mod".to_owned()),
SelectItem(AddonType::Plugin, "Plugin".to_owned()),
SelectItem(AddonType::Mod, Cow::Borrowed("Mod")),
SelectItem(AddonType::Plugin, Cow::Borrowed("Plugin")),
],
)?,
};

self.add_addon(addon_type, addon)
}

pub fn add_addon(&mut self, addon_type: AddonType, addon: &Downloadable) -> Result<()> {
pub fn add_addon(&mut self, addon_type: AddonType, addon: Downloadable) -> Result<()> {
let existing = match addon_type {
AddonType::Plugin => self.server.plugins.iter(),
AddonType::Mod => self.server.mods.iter(),
Expand All @@ -65,7 +66,7 @@ impl App {
AddonType::Plugin => &mut self.server.plugins,
AddonType::Mod => &mut self.server.mods,
}
.push(addon.clone());
.push(addon);

Ok(())
}
Expand All @@ -78,10 +79,13 @@ impl App {
.server
.worlds
.keys()
.map(|k| SelectItem(k.clone(), k.clone()))
.map(|k| SelectItem(k.clone(), Cow::Owned(k.clone())))
.collect();

items.push(SelectItem("+".to_owned(), "+ New world entry".to_owned()));
items.push(SelectItem(
"+".to_owned(),
Cow::Borrowed("+ New world entry"),
));

self.select(prompt, &items)?
};
Expand All @@ -103,26 +107,25 @@ impl App {
Ok(world_name)
}

pub fn add_datapack(&mut self, dp: &Downloadable) -> Result<()> {
pub fn add_datapack(&mut self, dp: Downloadable) -> Result<()> {
let world_name = self.select_world("Add datapack to...")?;

self.add_datapack_to(&world_name, dp)?;

Ok(())
}

pub fn add_datapack_to(&mut self, world: &str, dp: &Downloadable) -> Result<()> {
pub fn add_datapack_to(&mut self, world: &str, dp: Downloadable) -> Result<()> {
let dp_name = dp.to_short_string();

self.server
.worlds
.get_mut(world)
.ok_or(anyhow!("World entry did not exist"))?
.datapacks
.push(dp.clone());
.push(dp);

self.notify(
Prefix::Imported,
format!("datapack {} to {world}", dp.to_short_string()),
);
self.notify(Prefix::Imported, format!("datapack {dp_name} to {world}"));

Ok(())
}
Expand Down
31 changes: 15 additions & 16 deletions src/app/caching.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{
fs::{self, File},
io::Write,
fs::File,
io::{BufReader, BufWriter},
path::PathBuf,
};

Expand All @@ -20,8 +20,10 @@ impl Cache {
}

pub fn get_json<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
let content = fs::read_to_string(self.0.join(path))?;
Ok(serde_json::from_str(&content)?)
let file = File::open(self.0.join(path))?;
let reader = BufReader::new(file);

Ok(serde_json::from_reader(reader)?)
}

pub fn path(&self, path: &str) -> PathBuf {
Expand All @@ -33,21 +35,18 @@ impl Cache {
}

pub fn try_get_json<T: DeserializeOwned>(&self, path: &str) -> Result<Option<T>> {
if self.exists(path) {
Ok(Some(self.get_json(path)?))
Ok(if self.exists(path) {
Some(self.get_json(path)?)
} else {
Ok(None)
}
None
})
}

pub fn write_json<T: serde::Serialize>(&self, path: &str, data: &T) -> Result<()> {
fs::create_dir_all(self.path(path).parent().unwrap())
.context(format!("Creating parent directory for: {path}"))?;
let content = serde_json::to_string(data)?;
let mut f =
File::create(self.path(path)).context(format!("Creating cache file at: {path}"))?;
f.write_all(content.as_bytes())?;

Ok(())
let writer = BufWriter::new(
File::create(self.path(path)).context(format!("Creating cache file at: {path}"))?,
);

Ok(serde_json::to_writer(writer, data)?)
}
}
24 changes: 10 additions & 14 deletions src/app/downloading.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{fmt::Debug, path::PathBuf, time::Duration};
use std::{borrow::Cow, fmt::Debug, fs, path::PathBuf, time::Duration};

use anyhow::{bail, Context, Result};
use digest::{Digest, DynDigest};
Expand Down Expand Up @@ -64,15 +64,13 @@ impl App {
}

pub fn create_hasher(name: &str) -> Box<dyn DynDigest> {
let digester: Box<dyn DynDigest> = match name {
match name {
"sha256" => Box::new(<Sha256 as Digest>::new()),
"sha512" => Box::new(<Sha512 as Digest>::new()),
"sha1" => Box::new(<Sha1 as Digest>::new()),
"md5" => Box::new(<Md5 as Digest>::new()),
_ => unreachable!(),
};

digester
}
}

#[allow(clippy::too_many_lines)]
Expand All @@ -95,13 +93,11 @@ impl App {
let hasher = Self::get_best_hash(&resolved.hashes);

// if resolved has hashes, Some((hash name, dyndigest, hash value))
let mut hasher = if let Some((name, hash)) = hasher {
let mut hasher = hasher.map(|(name, hash)| {
let digester: Box<dyn DynDigest> = App::create_hasher(&name);

Some((name, digester, hash))
} else {
None
};
(name, digester, hash)
});

let validate_hash = |hasher: Option<(String, Box<dyn DynDigest>, String)>| {
if let Some((hash_name, digest, resolved_hash)) = hasher {
Expand Down Expand Up @@ -148,9 +144,9 @@ impl App {
match self.select(
&message,
&[
SelectItem(0, "Delete folder and download".to_owned()),
SelectItem(1, "Skip file".to_owned()),
SelectItem(2, "Bail".to_owned()),
SelectItem(0, Cow::Borrowed("Delete folder and download")),
SelectItem(1, Cow::Borrowed("Skip file")),
SelectItem(2, Cow::Borrowed("Bail")),
],
)? {
0 => {
Expand Down Expand Up @@ -189,7 +185,7 @@ impl App {
// this bomb will explode (delete target_file) if its not defused (fn exits with Err)
let mut bomb = Bomb(true, || {
// i mean, atleast try right
let _ = std::fs::remove_file(&file_path);
let _ = fs::remove_file(&file_path);
});

if let Some((cached, cached_size)) = match &cached_file_path {
Expand Down
25 changes: 13 additions & 12 deletions src/app/feedback.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::borrow::Cow;
use core::fmt::Display;
use std::{borrow::Cow, env};

use anyhow::Result;
use console::{style, StyledObject};
Expand Down Expand Up @@ -96,44 +97,44 @@ impl From<Prefix> for Cow<'static, str> {
}

impl App {
pub fn println<S: std::fmt::Display>(&self, message: S) {
pub fn println<S: Display>(&self, message: S) {
self.multi_progress.suspend(|| println!("{message}"));
}

pub fn success<S: std::fmt::Display>(&self, message: S) {
pub fn success<S: Display>(&self, message: S) {
self.println(format!(
" {} {message}",
ColorfulTheme::default().success_prefix
));
}

pub fn log<S: std::fmt::Display>(&self, message: S) {
pub fn log<S: Display>(&self, message: S) {
self.println(format!(" {message}"));
}

pub fn log_dev<S: std::fmt::Display>(&self, message: S) {
pub fn log_dev<S: Display>(&self, message: S) {
self.println(format!("🛈 {message}"));
}

pub fn notify<S: std::fmt::Display>(&self, prefix: Prefix, message: S) {
pub fn notify<S: Display>(&self, prefix: Prefix, message: S) {
self.println(format!("{} {message}", prefix.styled()));
}

pub fn warn<S: std::fmt::Display>(&self, message: S) {
pub fn warn<S: Display>(&self, message: S) {
self.notify(Prefix::Warning, message);
}

#[allow(dead_code)]
pub fn error<S: std::fmt::Display>(&self, message: S) {
pub fn error<S: Display>(&self, message: S) {
self.notify(Prefix::Error, message);
}

pub fn info<S: std::fmt::Display>(&self, message: S) {
pub fn info<S: Display>(&self, message: S) {
self.notify(Prefix::Info, message);
}

pub fn dbg<S: std::fmt::Display>(&self, message: S) {
if std::env::var("MCMAN_DEBUG") == Ok("true".to_owned()) {
pub fn dbg<S: Display>(&self, message: S) {
if env::var("MCMAN_DEBUG") == Ok("true".to_owned()) {
self.notify(Prefix::Debug, message);
}
}
Expand All @@ -150,7 +151,7 @@ impl App {

#[allow(clippy::unused_self)]
pub fn is_ci(&self) -> bool {
std::env::var("CI").ok() == Some("true".to_owned())
env::var("CI").ok() == Some("true".to_owned())
}

pub fn ci(&self, cmd: &str) {
Expand Down
Loading

0 comments on commit 944771c

Please sign in to comment.