Skip to content

Commit

Permalink
refactor: simplify imports and other minor optimizations
Browse files Browse the repository at this point in the history
  • Loading branch information
null8626 committed Sep 23, 2024
1 parent 17423ee commit 9c15577
Show file tree
Hide file tree
Showing 17 changed files with 55 additions and 67 deletions.
16 changes: 6 additions & 10 deletions src/_archive/app/from_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,17 +334,13 @@ impl App {
let mut job = String::new();

if let Some(mut segments) = url.path_segments() {
loop {
if segments.next().unwrap_or_default() == "job" {
if let Some(job_name) = segments.next() {
if !job.is_empty() {
job += "/";
}

job += job_name;
} else {
break;
while let Some("job") = segments.next() {
if let Some(job_name) = segments.next() {
if !job.is_empty() {
job += "/";
}

job += job_name;
} else {
break;
}
Expand Down
4 changes: 2 additions & 2 deletions src/_archive/app/hashing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use indicatif::ProgressBar;
use sha2::Sha256;
use std::{collections::HashMap, marker::Unpin, path::PathBuf};
use tokio::{
fs::File,
fs::{self, File},
io::{AsyncRead, AsyncWrite},
};
use tokio_stream::StreamExt;
Expand Down Expand Up @@ -64,7 +64,7 @@ impl App {
if is_temp {
pb.set_message("Cleaning up...");

tokio::fs::remove_file(&file_path)
fs::remove_file(&file_path)
.await
.context(format!("Deleting {}", file_path.display()))?;
}
Expand Down
2 changes: 1 addition & 1 deletion src/_archive/core/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ impl<'a> BuildContext<'a> {
.with_message(banner);
progress_bar.enable_steady_tick(Duration::from_millis(250));

tokio::fs::create_dir_all(&self.output_dir)
fs::create_dir_all(&self.output_dir)
.await
.context("Creating output directory")?;

Expand Down
8 changes: 1 addition & 7 deletions src/_archive/hot_reload/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -423,13 +423,7 @@ impl<'a> DevSession<'a> {
let content = std::fs::read_to_string(&latest_log_path)
.context("Reading latest.log file")?;

let is_crash = if test_result == TestResult::Crashed {
true
} else {
content.contains(LINE_CRASHED)
};

let crash_log_path = if is_crash {
let crash_log_path = if test_result == TestResult::Crashed || content.contains(LINE_CRASHED) {
let folder = self.builder.output_dir.join("crash-reports");
if !folder.exists() {
bail!("crash-reports folder doesn't exist, cant upload to mclo.gs");
Expand Down
8 changes: 4 additions & 4 deletions src/_archive/interop/packwiz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ impl FileProvider {
pub async fn parse_toml<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
match self {
Self::LocalFolder(folder) => {
let str = tokio::fs::read_to_string(folder.join(path)).await?;
let str = fs::read_to_string(folder.join(path)).await?;
Ok(toml::from_str(&str)?)
},
Self::RemoteURL(http_client, url) => {
Expand Down Expand Up @@ -111,7 +111,7 @@ impl<'a> PackwizInterop<'a> {

match &source {
FileProvider::LocalFolder(folder) => {
tokio::fs::copy(folder.join(&file.file), output_path).await?;
fs::copy(folder.join(&file.file), output_path).await?;
},
FileProvider::RemoteURL(_, url) => {
self.0
Expand Down Expand Up @@ -290,7 +290,7 @@ impl<'a> PackwizInterop<'a> {
)?)
.with_prefix(ProgressPrefix::Exporting);

tokio::fs::create_dir_all(output_dir.join("mods")).await?;
fs::create_dir_all(output_dir.join("mods")).await?;
for dl in self.0.server.mods.iter().progress_with(pb.clone()) {
pb.set_message(dl.to_short_string());

Expand Down Expand Up @@ -354,7 +354,7 @@ impl<'a> PackwizInterop<'a> {
let source = self.0.server.path.join("config").join(&rel_path);
let dest = output_dir.join(&rel_path);

tokio::fs::create_dir_all(dest.parent().unwrap())
fs::create_dir_all(dest.parent().unwrap())
.await
.context("Creating parent directory")?;

Expand Down
2 changes: 1 addition & 1 deletion src/_archive/model/servertoml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ impl Default for MarkdownOptions {
}

impl MarkdownOptions {
pub fn is_empty(&self) -> bool {
pub const fn is_empty(&self) -> bool {
self.files.is_empty()
}
}
Expand Down
10 changes: 4 additions & 6 deletions src/_archive/util/md.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,17 +48,15 @@ impl MarkdownTable {
}

pub fn render(&self) -> String {
let mut col_lengths = vec![];

for idx in 0..self.headers.len() {
let mut col_lengths = (0..self.headers.len()).map(|idx| {
let mut li = vec![self.headers[idx].len()];

li.extend(self.rows.iter().map(|row| row[idx].len()));

col_lengths.push(li.into_iter().max().expect("col lengths iter max none"));
}
li.into_iter().max().expect("col lengths iter max none")
}).collect::<Vec<_>>();

let mut lines = vec![];
let mut lines = Vec::with_capacity(2);

lines.push({
let cols = col_lengths
Expand Down
7 changes: 4 additions & 3 deletions src/api/app/actions/build/bootstrap.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::{collections::HashSet, path::Path, sync::Arc};
use tokio::fs;

use anyhow::{Context, Result};
use futures::{StreamExt, TryStreamExt};
Expand Down Expand Up @@ -126,22 +127,22 @@ impl App {
let output_path = output_base.join(&relative);

if self.should_bootstrap_file(file).await {
let original_contents = tokio::fs::read_to_string(file)
let original_contents = fs::read_to_string(file)
.await
.with_context(|| format!("Reading contents of {file:?}"))?;

let (bootstrapped_contents, _used_vars) =
self.vars_replace_content(&original_contents).await?;

create_parents(&output_path).await?;
tokio::fs::write(&output_path, bootstrapped_contents.as_ref())
fs::write(&output_path, bootstrapped_contents.as_ref())
.await
.with_context(|| format!("Writing to {output_path:?}"))?;

log::info!("Bootstrapped: {relative:?}");
} else {
create_parents(&output_path).await?;
tokio::fs::copy(file, &output_path)
fs::copy(file, &output_path)
.await
.with_context(|| format!("Copying {file:?} to {output_path:?}"))?;

Expand Down
5 changes: 3 additions & 2 deletions src/api/app/actions/lockfile/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::{path::Path, sync::Arc};
use tokio::fs;

use anyhow::Result;

Expand All @@ -25,7 +26,7 @@ impl App {
if path.exists() {
let mut existing_lockfile = self.existing_lockfile.write().await;
*existing_lockfile = Some(serde_json::from_str::<Lockfile>(
&tokio::fs::read_to_string(base.join(LOCKFILE)).await?,
&fs::read_to_string(base.join(LOCKFILE)).await?,
)?);
}

Expand All @@ -36,7 +37,7 @@ impl App {
pub async fn write_lockfile(&self, base: &Path) -> Result<()> {
let lockfile = self.new_lockfile.read().await;

tokio::fs::write(base.join(LOCKFILE), serde_json::to_vec(&*lockfile)?).await?;
fs::write(base.join(LOCKFILE), serde_json::to_vec(&*lockfile)?).await?;

Ok(())
}
Expand Down
8 changes: 2 additions & 6 deletions src/api/app/actions/markdown/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,10 @@ impl App {
) -> Result<HashMap<String, String>> {
let markdown_options = self.get_markdown_options().await.unwrap_or_default();

let mut map = HashMap::new();

map.insert(
Ok(HashMap::from([(
String::from("addons"),
markdown_options.render_addons(&metadata.addons),
);

Ok(map)
)]))
}

pub async fn render_addon_metadata(&self, metadata: Vec<AddonMetadata>) -> Result<String> {
Expand Down
9 changes: 4 additions & 5 deletions src/api/app/actions/script/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::path::Path;
use tokio::fs;

use anyhow::Result;

Expand All @@ -10,17 +11,15 @@ use crate::api::{

impl App {
async fn get_script_lines_for(&self, shell: &Shell, server: &Server) -> Result<Vec<String>> {
let mut lines = vec![];

lines.push(shell.comment(&format!("generated by mcman/{APP_VERSION}")));
let mut lines = vec![shell.comment(&format!("generated by mcman/{APP_VERSION}"))];

if *shell == Shell::Bat {
lines.push(format!("title {}", server.name));
}

lines.extend(server.launcher.prelaunch.clone());

let mut args = vec![];
let mut args = Vec::with_capacity(2);

let java = server.get_java().await;

Expand All @@ -42,7 +41,7 @@ impl App {
) -> Result<()> {
let script = shell.generate_script(&self.get_script_lines_for(&shell, server).await?);

tokio::fs::write(base.join(format!("start.{}", shell.file_ext())), script).await?;
fs::write(base.join(format!("start.{}", shell.file_ext())), script).await?;

Ok(())
}
Expand Down
2 changes: 1 addition & 1 deletion src/api/app/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ impl App {
if res
.headers()
.get("x-ratelimit-remaining")
.is_some_and(|x| String::from_utf8_lossy(x.as_bytes()) == "1")
.is_some_and(|x| x.as_bytes() == b"1")
{
log::info!("Hit ratelimit");

Expand Down
13 changes: 8 additions & 5 deletions src/api/app/step/cache_check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ use std::path::Path;

use anyhow::{Context, Result};
use futures::{StreamExt, TryStreamExt};
use tokio::{fs::File, io::BufWriter};
use tokio::{
fs::{self, File},
io::BufWriter,
};
use tokio_util::io::ReaderStream;

use crate::api::{
Expand Down Expand Up @@ -56,7 +59,7 @@ impl App {
// size mismatch
// TODO: print warning
println!("WARNING size mismatch: {}", metadata.filename);
tokio::fs::remove_file(&output_path)
fs::remove_file(&output_path)
.await
.with_context(|| format!("Deleting file: {}", output_path.display()))?;
//return Ok(StepResult::Continue);
Expand Down Expand Up @@ -87,7 +90,7 @@ impl App {
// hash mismatch
// TODO: print warning
println!("WARNING Hash mismatch: {}", metadata.filename);
tokio::fs::remove_file(&output_path)
fs::remove_file(&output_path)
.await
.context("hash mismatch remove file")?;
}

Check warning on line 96 in src/api/app/step/cache_check.rs

View workflow job for this annotation

GitHub Actions / clippy

redundant else block

warning: redundant else block --> src/api/app/step/cache_check.rs:89:28 | 89 | } else { | ____________________________^ 90 | | // hash mismatch 91 | | // TODO: print warning 92 | | println!("WARNING Hash mismatch: {}", metadata.filename); ... | 95 | | .context("hash mismatch remove file")?; 96 | | } | |_____________________^ | = help: remove the `else` block and move the contents out = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_else = note: `-W clippy::redundant-else` implied by `-W clippy::pedantic` = help: to override `-W clippy::pedantic` add `#[allow(clippy::redundant_else)]`
Expand Down Expand Up @@ -151,8 +154,8 @@ impl App {
if hash != content {
// TODO: print warning
println!("WARNING Hash Mismatch on CacheCopy: {}", metadata.filename);
tokio::fs::remove_file(&output_path).await?;
tokio::fs::remove_file(&cached_path).await?;
fs::remove_file(&output_path).await?;
fs::remove_file(&cached_path).await?;
return Ok(StepResult::Continue);
}
}
Expand Down
5 changes: 3 additions & 2 deletions src/api/app/step/download.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::path::Path;
use tokio::fs::{self, File};

use anyhow::{bail, Context, Result};
use futures::TryStreamExt;
Expand Down Expand Up @@ -41,7 +42,7 @@ impl App {
let target_destination = cache_destination.as_ref().unwrap_or(&output_destination);

create_parents(target_destination).await?;
let target_file = tokio::fs::File::create(&target_destination)
let target_file = File::create(&target_destination)
.await
.with_context(|| format!("Creating file: {}", target_destination.display()))?;
let mut target_writer = tokio::io::BufWriter::new(target_file);
Expand All @@ -64,7 +65,7 @@ impl App {

if let Some(cache_destination) = cache_destination {
create_parents(&output_destination).await?;
tokio::fs::copy(&cache_destination, &output_destination).await?;
fs::copy(&cache_destination, &output_destination).await?;
}

println!("Downloaded {}", metadata.filename);
Expand Down
3 changes: 2 additions & 1 deletion src/api/app/step/remove_file.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::path::Path;
use tokio::fs;

use anyhow::Result;

Expand All @@ -18,7 +19,7 @@ impl App {
let path = dir.join(&metadata.filename);

if path.exists() {
tokio::fs::remove_file(path).await?;
fs::remove_file(path).await?;
} else {
println!("{path:?} does not exist, cant delete");
}
Expand Down
17 changes: 7 additions & 10 deletions src/api/utils/accessor.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::{fmt, path::PathBuf};
use std::{fmt, fs::File, path::PathBuf};
use tokio::fs;

use anyhow::{anyhow, Result};
use reqwest::Url;
Expand All @@ -11,8 +12,8 @@ use crate::api::app::App;
pub enum Accessor {
Local(PathBuf),
Remote(reqwest::Url),
ZipLocal((PathBuf, ZipArchive<std::fs::File>)),
//ZipRemote(SomeSortOfTempFile, ZipArchive<std::fs::File>),
ZipLocal((PathBuf, ZipArchive<File>)),
//ZipRemote(SomeSortOfTempFile, ZipArchive<File>),
}

impl fmt::Display for Accessor {
Expand All @@ -31,7 +32,7 @@ impl Accessor {
if str.starts_with("http://") || str.starts_with("https://") {
Ok(Self::Remote(Url::parse(str)?))
} else if str.ends_with(".zip") || str.ends_with(".mrpack") {

Check warning on line 34 in src/api/utils/accessor.rs

View workflow job for this annotation

GitHub Actions / clippy

case-sensitive file extension comparison

warning: case-sensitive file extension comparison --> src/api/utils/accessor.rs:34:19 | 34 | } else if str.ends_with(".zip") || str.ends_with(".mrpack") { | ^^^^^^^^^^^^^^^^^^^^^ | = help: consider using a case-insensitive comparison instead = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#case_sensitive_file_extension_comparisons = note: `-W clippy::case-sensitive-file-extension-comparisons` implied by `-W clippy::pedantic` = help: to override `-W clippy::pedantic` add `#[allow(clippy::case_sensitive_file_extension_comparisons)]` help: use std::path::Path | 34 ~ } else if std::path::Path::new(str) 35 + .extension() 36 ~ .map_or(false, |ext| ext.eq_ignore_ascii_case("zip")) || str.ends_with(".mrpack") { |
let file = std::fs::File::open(str)?;
let file = File::open(str)?;
let archive = ZipArchive::new(file)?;
Ok(Self::ZipLocal((PathBuf::from(str), archive)))
} else {
Expand All @@ -56,9 +57,7 @@ impl Accessor {
/// Read a JSON file
pub async fn json<T: DeserializeOwned>(&mut self, app: &App, path: &str) -> Result<T> {
match self {
Self::Local(base) => Ok(serde_json::from_reader(std::fs::File::open(
base.join(path),
)?)?),
Self::Local(base) => Ok(serde_json::from_reader(File::open(base.join(path))?)?),
Self::ZipLocal((_, zip)) => Ok(serde_json::from_reader(zip.by_name(path)?)?),
Self::Remote(url) => Ok(app.http_get_json(url.join(path)?).await?),
}
Expand All @@ -67,9 +66,7 @@ impl Accessor {
/// Read a TOML file
pub async fn toml<T: DeserializeOwned>(&mut self, app: &App, path: &str) -> Result<T> {
match self {
Self::Local(base) => Ok(toml::from_str(
&tokio::fs::read_to_string(base.join(path)).await?,
)?),
Self::Local(base) => Ok(toml::from_str(&fs::read_to_string(base.join(path)).await?)?),
Self::ZipLocal((_, zip)) => {
let file = zip.by_name(path)?;

Expand Down
3 changes: 2 additions & 1 deletion src/api/utils/fs.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::{
ffi::OsStr,
fs,
path::{Path, PathBuf},
};

Expand All @@ -18,7 +19,7 @@ pub fn create_parents_sync(path: &Path) -> Result<()> {
let parent = path
.parent()
.ok_or(anyhow!("Getting parent of: {path:?}"))?;
std::fs::create_dir_all(parent).with_context(|| format!("Creating directory: {parent:?}"))
fs::create_dir_all(parent).with_context(|| format!("Creating directory: {parent:?}"))
}

pub fn some_if_exists<T: ?Sized + AsRef<OsStr>>(path: &T) -> Option<PathBuf> {
Expand Down

0 comments on commit 9c15577

Please sign in to comment.