Skip to content

Commit

Permalink
sources for network.toml
Browse files Browse the repository at this point in the history
  • Loading branch information
TheAlan404 committed Jul 25, 2024
1 parent 454c3c3 commit 77ae0b5
Show file tree
Hide file tree
Showing 10 changed files with 97 additions and 42 deletions.
17 changes: 1 addition & 16 deletions src/api/app/actions/build/bootstrap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,6 @@ impl App {
/// Collects a list of paths to boostrap from
/// and calls [`Self::action_bootstrap_recursive`] for each folder root
pub async fn action_bootstrap(self: Arc<Self>, base: &Path) -> Result<()> {
let mut list = vec![];

if let Some((server_path, server)) = &*self.server.read().await {
if let Some((network_path, network)) = &*self.network.read().await {
list.push(network_path.parent().unwrap().join("groups").join("global").join("config"));

if let Some(entry) = network.servers.get(&server.name) {
for group in &entry.groups {
list.push(network_path.parent().unwrap().join("groups").join(group).join("config"));
}
}
}

list.push(server_path.parent().unwrap().join("config"));
}

let mut changed_variables = HashSet::new();

for (k, v) in &self.existing_lockfile.read().await.as_ref().map(|lock| lock.vars.clone()).unwrap_or_default() {
Expand All @@ -34,6 +18,7 @@ impl App {
}
}

let list = self.collect_bootstrap_paths().await;
for entry in list {
self.clone().action_bootstrap_recursive(base, &entry, &changed_variables).await?;
}
Expand Down
58 changes: 53 additions & 5 deletions src/api/app/collect.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,37 @@
use std::path::PathBuf;

use anyhow::Result;

use crate::api::models::{Addon, Source};

use super::App;

impl App {
pub async fn collect_sources(&self) -> Result<Vec<Source>> {
pub async fn collect_sources(&self) -> Result<Vec<(PathBuf, Source)>> {
let mut sources = vec![];

if let Some((_, server)) = &*self.server.read().await {
sources.extend_from_slice(&server.sources);
if let Some((server_path, server)) = &*self.server.read().await {
if let Some((network_path, network)) = &*self.network.read().await {
if let Some(group) = network.groups.get("global") {
for source in &group.sources {
sources.push((network_path.clone(), source.clone()));
}
}

if let Some(entry) = network.servers.get(&server.name) {
for group_name in &entry.groups {
if let Some(group) = network.groups.get(group_name) {
for source in &group.sources {
sources.push((network_path.clone(), source.clone()));
}
}
}
}
}

for source in &server.sources {
sources.push((server_path.clone(), source.clone()));
}
}

Ok(sources)
Expand All @@ -18,10 +40,36 @@ impl App {
pub async fn collect_addons(&self) -> Result<Vec<Addon>> {
let mut addons = vec![];

for source in self.collect_sources().await? {
addons.extend_from_slice(&source.resolve_addons(&self).await?);
for (relative_to, source) in self.collect_sources().await? {
addons.extend_from_slice(&source.resolve_addons(&self, &relative_to).await?);

Check failure on line 44 in src/api/app/collect.rs

View workflow job for this annotation

GitHub Actions / clippy

this expression creates a reference which is immediately dereferenced by the compiler

error: this expression creates a reference which is immediately dereferenced by the compiler --> src/api/app/collect.rs:44:61 | 44 | addons.extend_from_slice(&source.resolve_addons(&self, &relative_to).await?); | ^^^^^ help: change this to: `self` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow
}

Ok(addons)
}

pub async fn collect_bootstrap_paths(&self) -> Vec<PathBuf> {
let mut list = vec![];

if let Some((server_path, server)) = &*self.server.read().await {
if let Some((network_path, network)) = &*self.network.read().await {
// - network.toml
// - groups/global/**
list.push(network_path.parent().unwrap().join("groups").join("global").join("config"));

if let Some(entry) = network.servers.get(&server.name) {
for group in &entry.groups {
// - network.toml
// - groups/<name>/**
list.push(network_path.parent().unwrap().join("groups").join(group).join("config"));
}
}
}

// - server.toml
// - config/**
list.push(server_path.parent().unwrap().join("config"));
}

list
}
}
Empty file removed src/api/models/legacy/hook.rs
Empty file.
2 changes: 0 additions & 2 deletions src/api/models/legacy/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ mod server_options;
mod server_type;
mod server_launcher;
mod network;
mod hook;

pub use downloadable::*;
pub use world::*;
Expand All @@ -18,5 +17,4 @@ pub use server_options::*;
pub use server_type::*;
pub use server_launcher::*;

Check warning on line 18 in src/api/models/legacy/mod.rs

View workflow job for this annotation

GitHub Actions / clippy

unused import: `server_launcher::*`

warning: unused import: `server_launcher::*` --> src/api/models/legacy/mod.rs:18:9 | 18 | pub use server_launcher::*; | ^^^^^^^^^^^^^^^^^^
pub use network::*;

Check warning on line 19 in src/api/models/legacy/mod.rs

View workflow job for this annotation

GitHub Actions / clippy

unused import: `network::*`

warning: unused import: `network::*` --> src/api/models/legacy/mod.rs:19:9 | 19 | pub use network::*; | ^^^^^^^^^^
pub use hook::*;

6 changes: 4 additions & 2 deletions src/api/models/modpack_source.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::path::Path;

use anyhow::Result;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
Expand All @@ -19,9 +21,9 @@ pub enum ModpackSource {
}

impl ModpackSource {
pub fn accessor(&self) -> Result<Accessor> {
pub fn accessor(&self, base: &Path) -> Result<Accessor> {
let str = match self {
Self::Local { path, .. } => path,
Self::Local { path, .. } => &base.join(path).to_string_lossy().into_owned(),
Self::Remote { url, .. } => url,
};

Expand Down
9 changes: 9 additions & 0 deletions src/api/models/network/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ use std::collections::HashMap;

use serde::{Deserialize, Serialize};

use super::Source;

pub const NETWORK_TOML: &str = "network.toml";

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
Expand All @@ -10,9 +12,16 @@ pub struct Network {
pub variables: HashMap<String, String>,

pub servers: HashMap<String, ServerEntry>,
pub groups: HashMap<String, NetworkGroup>,
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
pub struct ServerEntry {
pub groups: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
pub struct NetworkGroup {
#[serde(default = "Vec::<Source>::new")]
pub sources: Vec<Source>,
}
20 changes: 8 additions & 12 deletions src/api/models/source.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use std::path::PathBuf;
use std::path::Path;

use anyhow::{Context, Result};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use super::{mrpack::resolve_mrpack_addons, packwiz::resolve_packwiz_addons, Addon, AddonListFile, ModpackType};
use crate::api::{app::App, models::ModpackSource, utils::{accessor::Accessor, toml::read_toml}};
use crate::api::{app::App, models::ModpackSource, utils::{accessor::Accessor, fs::with_extension_if_none, toml::read_toml}};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
pub struct Source {
Expand Down Expand Up @@ -39,11 +39,11 @@ impl Source {
}
}

pub fn accessor(&self) -> Result<Accessor> {
pub fn accessor(&self, relative_to: &Path) -> Result<Accessor> {
match &self.source_type {
SourceType::File { path } => Ok(Accessor::Local(path.into())),
SourceType::Folder { path } => Ok(Accessor::Local(path.into())),

Check warning on line 45 in src/api/models/source.rs

View workflow job for this annotation

GitHub Actions / clippy

this match arm has an identical body to another arm

warning: this match arm has an identical body to another arm --> src/api/models/source.rs:45:13 | 45 | SourceType::Folder { path } => Ok(Accessor::Local(path.into())), | ---------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | help: try merging the arm patterns: `SourceType::Folder { path } | SourceType::File { path }` | = help: or try changing either arm body note: other arm here --> src/api/models/source.rs:44:13 | 44 | SourceType::File { path } => Ok(Accessor::Local(path.into())), | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#match_same_arms
SourceType::Modpack { modpack } => modpack.accessor(),
SourceType::Modpack { modpack } => modpack.accessor(relative_to),
}
}

Expand All @@ -54,26 +54,22 @@ impl Source {
}
}

pub async fn resolve_addons(&self, app: &App) -> Result<Vec<Addon>> {
pub async fn resolve_addons(&self, app: &App, relative_to: &Path) -> Result<Vec<Addon>> {
match &self.source_type {
SourceType::File { path } => {
let file: AddonListFile = read_toml(&PathBuf::from(if path.ends_with(".toml") {
path.clone()
} else {
format!("{path}.toml")
})).with_context(|| format!("Source: File => {path}"))?;
let file: AddonListFile = read_toml(&with_extension_if_none(&relative_to.join(path), "toml")).with_context(|| format!("Source: File => {path}"))?;
Ok(file.flatten())
},

SourceType::Folder { .. } => Ok(vec![]),

SourceType::Modpack { modpack } => {
let accessor = modpack.accessor()?;
let accessor = modpack.accessor(relative_to)?;
match modpack.modpack_type() {
ModpackType::MRPack => resolve_mrpack_addons(app, accessor).await,
ModpackType::Packwiz => resolve_packwiz_addons(app, accessor).await,
ModpackType::Unsup => todo!(),
}.with_context(|| format!("Source: Modpack/{} => {}", modpack.modpack_type().to_string(), modpack.accessor().unwrap().to_string()))
}.with_context(|| format!("Source: Modpack/{} => {}", modpack.modpack_type().to_string(), modpack.accessor(relative_to).unwrap().to_string()))
}
}
}
Expand Down
9 changes: 9 additions & 0 deletions src/api/utils/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,12 @@ pub fn some_if_exists<T: ?Sized + AsRef<OsStr>>(path: &T) -> Option<PathBuf> {
None
}
}

pub fn with_extension_if_none<T: ?Sized + AsRef<OsStr>>(path: &T, ext: &str) -> PathBuf {
let path = PathBuf::from(path);
if path.extension().is_some_and(|e| e == ext) {
path
} else {
path.with_extension(ext)
}
}
16 changes: 12 additions & 4 deletions src/commands/build.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,26 @@
use std::{path::Path, sync::Arc};
use std::{path::{Path, PathBuf}, sync::Arc};

Check warning on line 1 in src/commands/build.rs

View workflow job for this annotation

GitHub Actions / clippy

unused import: `Path`

warning: unused import: `Path` --> src/commands/build.rs:1:18 | 1 | use std::{path::{Path, PathBuf}, sync::Arc}; | ^^^^

use anyhow::Result;

use crate::api::app::App;

#[derive(clap::Args)]
pub struct Args {

#[arg(long, default_value = "output/server")]
pub output: PathBuf,
}

pub async fn run(app: Arc<App>, args: Args) -> Result<()> {
let base = Path::new("./output/server");
let Some(server_path) = app.server.read().await.as_ref().map(|(path, _)| path.parent().unwrap().to_owned()) else {
log::error!("No `server.toml` found to build server");
return Ok(())
};

let base = server_path.join(&args.output);

log::info!("Build output: {base:?}");

app.action_build(base).await?;
app.action_build(&base).await?;

Ok(())
}
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ enum Commands {

#[tokio::main]
async fn main() -> Result<()> {
init_logger();
init_logger()?;
let args = Cli::parse();
let app = Arc::new(App::new()?);

Expand Down

0 comments on commit 77ae0b5

Please sign in to comment.