Skip to content

Commit

Permalink
logger util and 'add' cmd datapack support
Browse files Browse the repository at this point in the history
  • Loading branch information
TheAlan404 committed Aug 24, 2023
1 parent 7525f76 commit ac61ee9
Show file tree
Hide file tree
Showing 13 changed files with 355 additions and 79 deletions.
18 changes: 18 additions & 0 deletions examples/datapacks/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# datapacks

[![mcman badge](https://img.shields.io/badge/uses-mcman-purple?logo=github)](https://github.com/ParadigmMC/mcman)

<!-- run 'mcman md' to update! -->

<!--start:mcman-server-->
| Version | Type |
| ------- | ------- |
| 1.20.1 | Vanilla |
<!--end:mcman-server-->

## Plugins

<!--start:mcman-addons-->
| |
| |
<!--end:mcman-addons-->
2 changes: 2 additions & 0 deletions examples/datapacks/config/server.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
server-port=${PORT:25565}
motd=${SERVER_NAME:A Minecraft Server}
23 changes: 23 additions & 0 deletions examples/datapacks/server.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name = "datapacks"
mc_version = "1.20.1"

[jar]
type = "vanilla"

[variables]
PORT = "25565"

[launcher]
aikars_flags = true
proxy_flags = false
nogui = true
eula_args = true

[[plugins]]
type = "modrinth"
id = "vanilla-refresh"
version = "c1SnJlLJ"

[markdown]
files = ["README.md"]
auto_update = false
36 changes: 35 additions & 1 deletion src/commands/add/modrinth.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use anyhow::{Context, Result, bail};
use clap::{arg, ArgMatches, Command};
use console::style;
use dialoguer::{theme::ColorfulTheme, Input, Select};

use crate::{
Expand Down Expand Up @@ -76,7 +77,23 @@ pub async fn run(matches: &ArgMatches) -> Result<()> {

let version = versions[selection].clone();

match project.project_type.as_str() {
match if version.loaders.contains(&"datapack".to_owned()) {
if version.loaders.len() > 1 {
match Select::with_theme(&ColorfulTheme::default())
.with_prompt("Import as...")
.default(0)
.items(&["Datapack", "Mod/Plugin"])
.interact()? {
0 => "datapack",
1 => "mod",
_ => unreachable!(),
}
} else {
"datapack"
}
} else {
project.project_type.as_str()
} {
"modpack" => {
todo!("Modpack importing currently unsupported")
}
Expand Down Expand Up @@ -108,6 +125,23 @@ pub async fn run(matches: &ArgMatches) -> Result<()> {

println!(" > Added {} from modrinth", project.title);
}
"datapack" => {
let addon = Downloadable::Modrinth { id: project.slug.clone(), version: version.id.clone() };

let world_name = server.add_datapack(addon)?;

server.save()?;

server.refresh_markdown(&http_client).await?;

println!(
" > {} {} {} {world_name}{}",
style("Datapack ").green(),
project.title,
style("added to").green(),
style("!").green()
);
}
ty => bail!("Unsupported modrinth project type: '{ty}'"),
}

Expand Down
45 changes: 3 additions & 42 deletions src/commands/import/datapack.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
use anyhow::{Context, Result};
use clap::{arg, ArgMatches, Command};
use console::style;
use dialoguer::{theme::ColorfulTheme, Input, Select};
use dialoguer::Input;

use crate::{
create_http_client,
model::{Downloadable, Server, World},
util::SelectItem,
model::{Downloadable, Server},
};

pub fn cli() -> Command {
Expand All @@ -27,45 +26,7 @@ pub async fn run(matches: &ArgMatches) -> Result<()> {

let dl = Downloadable::from_url_interactive(&http_client, &server, &urlstr, true).await?;

let selected_world_name = if server.worlds.is_empty() {
"*".to_owned()
} else {
let mut items: Vec<SelectItem<String>> = server
.worlds
.keys()
.map(|k| SelectItem(k.clone(), k.clone()))
.collect();

items.push(SelectItem("*".to_owned(), "* New world entry".to_owned()));

let idx = Select::with_theme(&ColorfulTheme::default())
.with_prompt("Which world to add to?")
.items(&items)
.default(items.len() - 1)
.interact()?;

items[idx].0.clone()
};

let world_name = if selected_world_name == "*" {
Input::with_theme(&ColorfulTheme::default())
.with_prompt("World name?")
.default("world".to_owned())
.interact_text()?
} else {
selected_world_name
};

if !server.worlds.contains_key(&world_name) {
server.worlds.insert(world_name.clone(), World::default());
}

server
.worlds
.get_mut(&world_name)
.expect("world shouldve already been inserted")
.datapacks
.push(dl.clone());
let world_name = server.add_datapack(dl.clone())?;

server.save()?;

Expand Down
4 changes: 3 additions & 1 deletion src/core/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use tokio::fs::{self, File};

use crate::{
model::{Server, StartupMethod},
util, Source,
util::{self, logger::Logger}, Source,
};

pub mod addons;
Expand All @@ -19,6 +19,7 @@ pub mod worlds;

#[derive(Debug)]
pub struct BuildContext {
pub logger: Logger,
pub server: Server,
pub http_client: reqwest::Client,
pub output_dir: PathBuf,
Expand All @@ -33,6 +34,7 @@ pub struct BuildContext {
impl Default for BuildContext {
fn default() -> Self {
Self {
logger: Logger::new(),
server: Server::default(),
force: false,
http_client: reqwest::Client::default(),
Expand Down
93 changes: 60 additions & 33 deletions src/core/worlds.rs
Original file line number Diff line number Diff line change
@@ -1,51 +1,78 @@
use anyhow::{Context, Result};
use console::style;

use crate::{util::logger::Logger, model::World};

use super::{BuildContext, ReportBackState};

impl BuildContext {
pub async fn process_worlds(&self) -> Result<()> {
let world_count = self.server.worlds.len();
let wc_len = world_count.to_string().len();
let world_logger = Logger::List {
indent: 10,
len: self.server.worlds.len(),
};

for (idx, (name, world)) in self.server.worlds.iter().enumerate() {
println!(
" ({:wc_len$}/{world_count}) {} {name}",
idx + 1,
style("World:").bold()
);
world_logger.item(idx, &format!("{} {name}", style("World:").bold()));

self.process_world(
&world_logger,
name,
world
).await.context(format!("Processing world: {name}"))?;
}

Ok(())
}

pub async fn process_world(
&self,
world_logger: &Logger,
name: &str,
world: &World,
) -> Result<()> {
if !world.datapacks.is_empty() {
std::fs::create_dir_all(self.output_dir.join(name).join("datapacks"))
.context(format!("Failed to create {name}/datapacks directory"))?;

let datapack_count = world.datapacks.len();
let dp_len = datapack_count.to_string().len();
let pad_len = wc_len * 2 + 4;

for (idx, dp) in world.datapacks.iter().enumerate() {
let path = format!("{name}/datapacks");
self.downloadable(dp, Some(&path), |state, file_name| match state {
ReportBackState::Skipped => {
println!(
" {:pad_len$}({:dp_len$}/{datapack_count}) Skipping : {}",
idx + 1,
"",
style(file_name).dim()
);
}
ReportBackState::Downloaded => {
println!(
" {:pad_len$}({:dp_len$}/{datapack_count}) {} : {}",
idx + 1,
"",
self.process_datapacks(
world_logger,
name,
world
).await.context(format!("Processing datapacks"))?;
}

Ok(())
}

pub async fn process_datapacks(
&self,
world_logger: &Logger,
name: &str,
world: &World,
) -> Result<()> {
let datapacks_logger = world_logger.list(world.datapacks.len());

for (idx, dp) in world.datapacks.iter().enumerate() {
let path = format!("{name}/datapacks");
self.downloadable(dp, Some(&path), |state, file_name| match state {
ReportBackState::Skipped => {
datapacks_logger
.item(idx, &format!("Skipping : {}", style(file_name).dim()));
}
ReportBackState::Downloaded => {
datapacks_logger.item(
idx,
&format!(
"{} : {}",
style("Downloaded").green().bold(),
style(file_name).dim()
);
}
ReportBackState::Downloading => {}
})
.await?;
}
),
);
}
ReportBackState::Downloading => {}
})
.await?;
}

Ok(())
Expand Down
6 changes: 4 additions & 2 deletions src/model/mod.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
mod clientsidemod;
mod downloadable;
mod server;
mod servertoml;
mod serverlauncher;
mod servertype;
mod world;
mod network;

pub use clientsidemod::*;
pub use downloadable::*;
pub use server::*;
pub use servertoml::*;
pub use serverlauncher::*;
pub use servertype::*;
pub use world::*;
pub use network::*;
Loading

0 comments on commit ac61ee9

Please sign in to comment.