Skip to content

Commit

Permalink
perf: make IndexMap key Cow str
Browse files Browse the repository at this point in the history
  • Loading branch information
null8626 committed Feb 1, 2024
1 parent 74a1fcd commit 83e10cf
Show file tree
Hide file tree
Showing 12 changed files with 252 additions and 250 deletions.
106 changes: 56 additions & 50 deletions src/app/feedback.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use core::fmt::Display;
use std::{borrow::Cow, env};
use std::{borrow::Cow, env, fmt::Display};

use anyhow::Result;
use console::{style, StyledObject};
Expand All @@ -19,16 +18,27 @@ pub enum ProgressPrefix {
Exporting,
}

macro_rules! enum_to_string {
($input:ident,$($value:ident,)*) => {
match $input {
$(
Self::$value => $stringify($value),
)*
}
};
}

impl From<ProgressPrefix> for Cow<'static, str> {
fn from(val: ProgressPrefix) -> Self {
Cow::Borrowed(match val {
ProgressPrefix::Resolving => "Resolving",
ProgressPrefix::Checking => "Checking",
ProgressPrefix::Downloading => "Downloading",
ProgressPrefix::Copying => "Copying",
ProgressPrefix::Fetching => "Fetching",
ProgressPrefix::Exporting => "Exporting",
})
Cow::Borrowed(enum_to_string!(
val,
Resolving,
Checking,
Downloading,
Copying,
Fetching,
Exporting
))
}
}

Expand All @@ -53,46 +63,46 @@ pub enum Prefix {
}

impl Prefix {
pub fn as_str(self) -> &'static str {
pub const fn as_str(self) -> &'static str {
match self {
Prefix::Copied => " Copied",
Prefix::Skipped => " Skipped",
Prefix::SkippedWarning => " ! Skipped",
Prefix::Downloaded => " Downloaded",

Prefix::Imported => " Imported",
Prefix::Exported => " Exported",
Prefix::Rendered => " Rendered",
Prefix::Unpacked => " Unpacked",
Prefix::Packed => " Packed",

Prefix::Error => " ⚠ Error",
Prefix::Warning => " ⚠ Warn",
Prefix::Info => " 🛈 Info",
Prefix::Debug => " debug",
Self::Copied => " Copied",
Self::Skipped => " Skipped",
Self::SkippedWarning => " ! Skipped",
Self::Downloaded => " Downloaded",

Self::Imported => " Imported",
Self::Exported => " Exported",
Self::Rendered => " Rendered",
Self::Unpacked => " Unpacked",
Self::Packed => " Packed",

Self::Error => " ⚠ Error",
Self::Warning => " ⚠ Warn",
Self::Info => " 🛈 Info",
Self::Debug => " debug",
}
}

pub fn styled(self) -> StyledObject<&'static str> {
match self {
Prefix::Downloaded
| Prefix::Imported
| Prefix::Exported
| Prefix::Rendered
| Prefix::Packed
| Prefix::Unpacked => style(self.as_str()).green().bold(),
Prefix::Copied | Prefix::Skipped => style(self.as_str()).green(),
Prefix::Error => style(self.as_str()).red().bold(),
Prefix::Warning | Prefix::SkippedWarning => style(self.as_str()).yellow().bold(),
Prefix::Info => style(self.as_str()).bold(),
Prefix::Debug => style(self.as_str()).dim(),
Self::Downloaded
| Self::Imported
| Self::Exported
| Self::Rendered
| Self::Packed
| Self::Unpacked => style(self.as_str()).green().bold(),
Self::Copied | Self::Skipped => style(self.as_str()).green(),
Self::Error => style(self.as_str()).red().bold(),
Self::Warning | Self::SkippedWarning => style(self.as_str()).yellow().bold(),
Self::Info => style(self.as_str()).bold(),
Self::Debug => style(self.as_str()).dim(),
}
}
}

impl From<Prefix> for Cow<'static, str> {
fn from(val: Prefix) -> Self {
Cow::Borrowed(val.as_str().trim())
Cow::Borrowed(val.as_str().trim_start())
}
}

Expand Down Expand Up @@ -134,7 +144,10 @@ impl App {
}

pub fn dbg<S: Display>(&self, message: S) {
if env::var("MCMAN_DEBUG") == Ok("true".to_owned()) {
if env::var("MCMAN_DEBUG")
.map(|s| s.as_str() == "true")
.unwrap_or_default()
{
self.notify(Prefix::Debug, message);
}
}
Expand All @@ -151,7 +164,9 @@ impl App {

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

pub fn ci(&self, cmd: &str) {
Expand Down Expand Up @@ -197,16 +212,7 @@ impl App {
}

pub fn select<T: Clone>(&self, prompt: &str, items: &[SelectItem<T>]) -> Result<T> {
let item = &items[self.multi_progress.suspend(|| {
Select::with_theme(&ColorfulTheme::default())
.items(items)
.with_prompt(prompt)
.default(0)
.max_length(5)
.interact()
})?];

Ok(item.0.clone())
self.select_with_default(prompt, items, 0)
}

pub fn select_with_default<T: Clone>(
Expand Down
3 changes: 1 addition & 2 deletions src/app/hashing.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
use anyhow::{Context, Result};
use core::marker::Unpin;
use digest::{Digest, DynDigest};
use indicatif::ProgressBar;
use sha2::Sha256;
use std::{collections::HashMap, path::PathBuf};
use std::{collections::HashMap, marker::Unpin, path::PathBuf};
use tokio::{
fs::File,
io::{AsyncRead, AsyncWrite},
Expand Down
25 changes: 14 additions & 11 deletions src/app/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ pub use resolvable::*;
use crate::model::{AppConfig, Downloadable, Network, Server};
use crate::sources;

use std::{fmt::{self, Display, Formatter}, env};
use std::{
env,
fmt::{self, Display, Formatter},
};

pub const APP_USER_AGENT: &str = concat!(
env!("CARGO_PKG_NAME"),
Expand Down Expand Up @@ -246,25 +249,25 @@ impl App {
"denizs_gf" => Some("ily may".to_owned()),

_ => None,
}.or_else(|| {
}
.or_else(|| {
if let Ok(v) = std::env::var(k) {
Some(v)
} else if k.starts_with("NW_") {
if let Some(nw) = &self.network {
if k.starts_with("NW_SERVER_") {
let (name, ty) =
k.strip_prefix("NW_SERVER_").unwrap().split_once('_')?;
let (name, ty) = k.strip_prefix("NW_SERVER_").unwrap().split_once('_')?;

let serv = nw.servers.get(&name.to_lowercase())?;

let ip = env::var(format!("IP_{name}"))
.ok()
.or(serv.ip_address.clone())
.unwrap_or("127.0.0.1".to_owned());
let ip = env::var(format!("IP_{name}"))
.ok()
.or(serv.ip_address.clone())
.unwrap_or("127.0.0.1".to_owned());

let port = env::var(format!("PORT_{name}"))
.ok()
.unwrap_or(serv.port.to_string());
let port = env::var(format!("PORT_{name}"))
.ok()
.unwrap_or(serv.port.to_string());

match ty.to_lowercase().as_str() {
"ip" => Some(ip),
Expand Down
34 changes: 15 additions & 19 deletions src/core/bootstrap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,30 +37,26 @@ impl<'a> BuildContext<'a> {

// wtf i have to clone it sorry null
if let Some(nw) = self.app.network.clone() {
self.bootstrap_folder(
nw.path.join("groups").join("global").join("config")
).await?;
self.bootstrap_folder(nw.path.join("groups").join("global").join("config"))
.await?;

if self.app.server.name == nw.proxy {
for group_name in &nw.proxy_groups {
self.bootstrap_folder(
nw.path.join("groups").join(group_name).join("config")
).await?;
self.bootstrap_folder(nw.path.join("groups").join(group_name).join("config"))
.await?;
}
}

if let Some(entry) = nw.servers.get(&self.app.server.name) {
for group_name in &entry.groups {
self.bootstrap_folder(
nw.path.join("groups").join(group_name).join("config")
).await?;
self.bootstrap_folder(nw.path.join("groups").join(group_name).join("config"))
.await?;
}
}
}

self.bootstrap_folder(
self.app.server.path.join("config")
).await?;
self.bootstrap_folder(self.app.server.path.join("config"))
.await?;

pb.disable_steady_tick();
pb.finish_and_clear();
Expand All @@ -71,12 +67,12 @@ impl<'a> BuildContext<'a> {
Ok(())
}

pub async fn bootstrap_folder(
&mut self,
from_path: PathBuf,
) -> Result<()> {
pub async fn bootstrap_folder(&mut self, from_path: PathBuf) -> Result<()> {
if !from_path.exists() {
self.app.dbg(format!("skipped bootstrapping {} because it doesnt exist", from_path.display()));
self.app.dbg(format!(
"skipped bootstrapping {} because it doesnt exist",
from_path.display()
));
return Ok(());
}

Expand All @@ -93,8 +89,8 @@ impl<'a> BuildContext<'a> {
}

let source = entry.path();
let diffed_paths = diff_paths(source, &from_path)
.ok_or(anyhow!("Cannot diff paths"))?;
let diffed_paths =
diff_paths(source, &from_path).ok_or(anyhow!("Cannot diff paths"))?;

//pb.set_message(diffed_paths.to_string_lossy().to_string());

Expand Down
3 changes: 1 addition & 2 deletions src/core/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,7 @@ impl<'a> BuildContext<'a> {
let server_jar = self.download_server_jar().await?;
self.app.ci("::endgroup::");

if !self.skip_stages.contains(&"plugins".to_owned())
{
if !self.skip_stages.contains(&"plugins".to_owned()) {
self.download_addons(AddonType::Plugin).await?;
}

Expand Down
2 changes: 1 addition & 1 deletion src/hot_reload/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub enum HotReloadAction {
impl TryFrom<String> for HotReloadAction {
type Error = anyhow::Error;

fn try_from(value: String) -> core::result::Result<Self, Self::Error> {
fn try_from(value: String) -> std::result::Result<Self, Self::Error> {
if value.starts_with('/') {
Ok(Self::RunCommand(
value.strip_prefix('/').unwrap().to_string(),
Expand Down
34 changes: 26 additions & 8 deletions src/hot_reload/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
use std::{
collections::HashSet, env, ffi::OsStr, path::{Component, PathBuf}, process, process::{ExitStatus, Stdio}, sync::{Arc, Mutex}, time::Duration
collections::HashSet,
env,
ffi::OsStr,
path::{Component, PathBuf},
process,
process::{ExitStatus, Stdio},
sync::{Arc, Mutex},
time::Duration,
};

use anyhow::{anyhow, bail, Context, Result};
Expand Down Expand Up @@ -603,7 +610,8 @@ impl<'a> DevSession<'a> {
continue;
}

let g_rel_path = diff_paths(&path, &groups_path).expect("Cannot diff paths");
let g_rel_path =
diff_paths(&path, &groups_path).expect("Cannot diff paths");

let mut comps = g_rel_path.components();

Expand All @@ -617,8 +625,12 @@ impl<'a> DevSession<'a> {

let rel_path = comps.collect::<PathBuf>();

tx.blocking_send(Command::BootstrapGroup(group_name.to_string_lossy().into_owned(), path.clone(), rel_path.clone()))
.unwrap();
tx.blocking_send(Command::BootstrapGroup(
group_name.to_string_lossy().into_owned(),
path.clone(),
rel_path.clone(),
))
.unwrap();

let guard = config.lock().unwrap();
let Some(file) = guard
Expand Down Expand Up @@ -694,10 +706,12 @@ impl<'a> DevSession<'a> {
let mut network_groups_watcher = Self::create_network_groups_watcher(
cfg_mutex_w.clone(),
tx.clone(),
self.builder.app.network
self.builder
.app
.network
.as_ref()
.map(|nw| nw.path.join("groups"))
.unwrap_or_default()
.unwrap_or_default(),
)?;

if self.hot_reload.is_some() {
Expand All @@ -723,8 +737,12 @@ impl<'a> DevSession<'a> {
)?;

if let Some(nw) = &self.builder.app.network {
self.builder.app.log_dev("Watching [network.toml] groups/*/config/**");
network_groups_watcher.watcher().watch(&nw.path.join("groups"), RecursiveMode::Recursive)?;
self.builder
.app
.log_dev("Watching [network.toml] groups/*/config/**");
network_groups_watcher
.watcher()
.watch(&nw.path.join("groups"), RecursiveMode::Recursive)?;
networktoml_watcher.watcher().watch(
nw.path.join("network.toml").as_path(),
RecursiveMode::NonRecursive,
Expand Down
Loading

0 comments on commit 83e10cf

Please sign in to comment.