Skip to content

Commit

Permalink
this should build
Browse files Browse the repository at this point in the history
  • Loading branch information
TheAlan404 committed Aug 4, 2024
1 parent 3767d8e commit 69fac3b
Show file tree
Hide file tree
Showing 11 changed files with 116 additions and 56 deletions.
8 changes: 5 additions & 3 deletions src/api/app/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@ use crate::api::{models::{lockfile::Lockfile, network::{Network, NETWORK_TOML},
use super::App;

impl App {
pub fn try_read_files(&mut self) -> Result<()> {
pub async fn try_read_files(&self) -> Result<()> {
let server = try_find_toml_upwards::<Server>(SERVER_TOML)?;
let network = try_find_toml_upwards::<Network>(NETWORK_TOML)?;

self.server = Arc::new(RwLock::new(server));
self.network = Arc::new(RwLock::new(network));
let mut swg = self.server.write().await;
*swg = server;
let mut nwg = self.network.write().await;
*nwg = network;

Ok(())
}
Expand Down
4 changes: 0 additions & 4 deletions src/api/app/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,6 @@ impl App {
ci,
};

if let Err(e) = app.try_read_files() {
println!("Error while reading files: {e:?}");
}

Ok(app)
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/api/models/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
mod env;
mod modpack_source;
mod modpack_type;
mod source;

pub mod addon;
Expand All @@ -19,4 +20,5 @@ pub mod hooks;
pub use addon::*;
pub use env::*;
pub use modpack_source::*;
pub use modpack_type::*;
pub use source::*;
44 changes: 15 additions & 29 deletions src/api/models/modpack_source.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::path::Path;
use std::{path::Path, str::FromStr};

use anyhow::Result;
use schemars::JsonSchema;
Expand All @@ -10,48 +10,34 @@ use crate::api::utils::accessor::Accessor;
#[serde(untagged)]
pub enum ModpackSource {
Local {
modpack_type: ModpackType,
path: String,
},

Remote {
modpack_type: ModpackType,
url: String,
},
}

impl FromStr for ModpackSource {
type Err = anyhow::Error;

fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
if s.starts_with("http") {
Ok(ModpackSource::Remote { url: s.into() })
} else {
Ok(ModpackSource::Local { path: s.into() })
}
}
}

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

Ok(Accessor::from(str)?)

Check failure on line 40 in src/api/models/modpack_source.rs

View workflow job for this annotation

GitHub Actions / clippy

question mark operator is useless here

error: question mark operator is useless here --> src/api/models/modpack_source.rs:40:9 | 40 | Ok(Accessor::from(str)?) | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try removing question mark and `Ok()`: `Accessor::from(str)` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_question_mark
}

pub fn modpack_type(&self) -> ModpackType {
match self {
Self::Local { modpack_type, .. } => *modpack_type,
Self::Remote { modpack_type, .. } => *modpack_type,
}
}
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum ModpackType {
Packwiz,
MRPack,
Unsup,
}

impl ToString for ModpackType {
fn to_string(&self) -> String {
match self {
ModpackType::Packwiz => String::from("Packwiz"),
ModpackType::MRPack => String::from("MRPack"),
ModpackType::Unsup => String::from("Unsup"),
}
}
}
20 changes: 20 additions & 0 deletions src/api/models/modpack_type.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum ModpackType {
Packwiz,
MRPack,
Unsup,
}

impl ToString for ModpackType {
fn to_string(&self) -> String {
match self {
ModpackType::Packwiz => String::from("Packwiz"),
ModpackType::MRPack => String::from("MRPack"),
ModpackType::Unsup => String::from("Unsup"),
}
}
}

Check failure on line 20 in src/api/models/modpack_type.rs

View workflow job for this annotation

GitHub Actions / clippy

direct implementation of `ToString`

error: direct implementation of `ToString` --> src/api/models/modpack_type.rs:12:1 | 12 | / impl ToString for ModpackType { 13 | | fn to_string(&self) -> String { 14 | | match self { 15 | | ModpackType::Packwiz => String::from("Packwiz"), ... | 19 | | } 20 | | } | |_^ | = help: prefer implementing `Display` instead = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#to_string_trait_impl
2 changes: 2 additions & 0 deletions src/api/models/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ pub const SERVER_TOML: &str = "server.toml";
pub struct Server {
pub name: String,
pub port: Option<i32>,
pub version: Option<String>,

pub jar: Option<ServerJar>,

Expand All @@ -42,6 +43,7 @@ impl Default for Server {
Self {
name: String::from("server"),
port: None,
version: None,

jar: Some(ServerJar {
mc_version: String::from("1.20.4"),
Expand Down
32 changes: 24 additions & 8 deletions src/api/models/source.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::path::Path;
use std::{path::Path, str::FromStr};

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

Expand All @@ -26,10 +26,26 @@ pub enum SourceType {

Modpack {
#[serde(flatten)]
modpack: ModpackSource,
modpack: ModpackSource,
modpack_type: ModpackType,
},
}

impl FromStr for SourceType {
type Err = anyhow::Error;

fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
let (ty, val) = s.split_once(':').ok_or(anyhow!("Source identifier are in the format of '<type>:<path or url>'"))?;

Ok(match ty {
"file" | "f" => SourceType::File { path: val.into() },
"packwiz" | "pw" => SourceType::Modpack { modpack: ModpackSource::from_str(val)?, modpack_type: ModpackType::Packwiz },
"mrpack" => SourceType::Modpack { modpack: ModpackSource::from_str(val)?, modpack_type: ModpackType::MRPack },
_ => bail!("Unknown source identifier type: {ty}"),
})
}
}

impl Source {
pub fn source_name(&self) -> &'static str {
match self.source_type {
Expand All @@ -43,13 +59,13 @@ impl Source {
match &self.source_type {
SourceType::File { path } => Ok(Accessor::Local(path.into())),
SourceType::Folder { path } => Ok(Accessor::Local(path.into())),

Check warning on line 61 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:61:13 | 61 | SourceType::Folder { path } => Ok(Accessor::Local(path.into())), | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: try changing either arm body = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#match_same_arms = note: `-W clippy::match-same-arms` implied by `-W clippy::pedantic` = help: to override `-W clippy::pedantic` add `#[allow(clippy::match_same_arms)]` help: or try merging the arm patterns | 61 | SourceType::Folder { path } | SourceType::File { path } => Ok(Accessor::Local(path.into())), | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ help: and remove this obsolete arm | 60 - SourceType::File { path } => Ok(Accessor::Local(path.into())), |
SourceType::Modpack { modpack } => modpack.accessor(relative_to),
SourceType::Modpack { modpack, .. } => modpack.accessor(relative_to),
}
}

pub fn modpack_type(&self) -> Option<ModpackType> {
match &self.source_type {
SourceType::Modpack { modpack } => Some(modpack.modpack_type()),
SourceType::Modpack { modpack_type, .. } => Some(modpack_type.clone()),

Check failure on line 68 in src/api/models/source.rs

View workflow job for this annotation

GitHub Actions / clippy

using `clone` on type `ModpackType` which implements the `Copy` trait

error: using `clone` on type `ModpackType` which implements the `Copy` trait --> src/api/models/source.rs:68:62 | 68 | SourceType::Modpack { modpack_type, .. } => Some(modpack_type.clone()), | ^^^^^^^^^^^^^^^^^^^^ help: try dereferencing it: `*modpack_type` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#clone_on_copy = note: `-D clippy::clone-on-copy` implied by `-D clippy::all` = help: to override `-D clippy::all` add `#[allow(clippy::clone_on_copy)]`
_ => None,
}
}
Expand All @@ -65,13 +81,13 @@ impl Source {

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

SourceType::Modpack { modpack } => {
SourceType::Modpack { modpack, modpack_type } => {
let accessor = modpack.accessor(relative_to)?;
match modpack.modpack_type() {
match 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(relative_to).unwrap().to_string()))
}.with_context(|| format!("Source: Modpack/{} => {}", modpack_type.to_string(), modpack.accessor(relative_to).unwrap().to_string()))
}
}
}
Expand Down
5 changes: 5 additions & 0 deletions src/api/tools/java/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ impl JavaProcess {
});
}

pub async fn kill(&mut self) -> Result<()> {
self.child.kill().await?;
Ok(())
}

pub async fn wait(&mut self) -> Result<ExitStatus> {
Ok(self.child.wait().await?)
}
Expand Down
1 change: 1 addition & 0 deletions src/commands/migrate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ pub async fn migrate_server() -> Result<()> {
let server = Server {
name: legacy_server.name,
port: None,
version: legacy_server.variables.get("MODPACK_VERSION").cloned(),
launcher: legacy_server.launcher,
markdown: MarkdownOptions {
files: legacy_server.markdown.files,
Expand Down
31 changes: 21 additions & 10 deletions src/commands/run.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{path::PathBuf, sync::Arc};

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

View workflow job for this annotation

GitHub Actions / clippy

unused import: `path::PathBuf`

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

use anyhow::{Context, Result};
use anyhow::{bail, Context, Result};

Check warning on line 3 in src/commands/run.rs

View workflow job for this annotation

GitHub Actions / clippy

unused imports: `Context` and `bail`

warning: unused imports: `Context` and `bail` --> src/commands/run.rs:3:14 | 3 | use anyhow::{bail, Context, Result}; | ^^^^ ^^^^^^^

use crate::api::{app::App, tools::java::{get_java_installation_for, JavaProcess}, ws::WebsocketServer};

Check warning on line 5 in src/commands/run.rs

View workflow job for this annotation

GitHub Actions / clippy

unused imports: `get_java_installation_for` and `ws::WebsocketServer`

warning: unused imports: `get_java_installation_for` and `ws::WebsocketServer` --> src/commands/run.rs:5:42 | 5 | use crate::api::{app::App, tools::java::{get_java_installation_for, JavaProcess}, ws::WebsocketServer}; | ^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^

Expand All @@ -14,12 +14,15 @@ pub async fn run(app: Arc<App>, args: RunArgs) -> Result<()> {
let base = args.build_args.get_base_dir(&app).await?;

super::build::run(app.clone(), args.build_args).await?;

let rg = app.server.read().await;
let (_, server) = rg.as_ref().unwrap();
let java = server.get_java().await;
let args = server.get_arguments();
drop(rg);

let (java, args) = if let Some((_, server)) = &*app.server.read().await {
(
server.get_java().await,
server.get_arguments()
)
} else {
unreachable!();
};

log::info!("Starting process...");

Expand All @@ -29,9 +32,17 @@ pub async fn run(app: Arc<App>, args: RunArgs) -> Result<()> {
println!("| {line}");
});

let e = process.wait().await?;

println!("{e:#?}");
let exit_status = tokio::select! {
_ = tokio::signal::ctrl_c() => None,
Ok(e) = process.wait() => Some(e),
};

if let Some(e) = exit_status {
println!("{e:#?}");
} else {
process.kill().await?;
println!("Killed process");
}

Ok(())
}
Expand Down
23 changes: 21 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::sync::Arc;

use anyhow::Result;
use api::{app::App, utils::logger::init_logger};
use api::{app::App, models::{server::{Server, SERVER_TOML}, Source, SourceType}, utils::logger::init_logger};
use clap::Parser;

mod api;
Expand All @@ -16,6 +16,9 @@ mod commands;
struct Cli {
#[command(subcommand)]
command: Commands,

#[arg(global = true, long)]
src: Vec<SourceType>,
}

#[derive(clap::Subcommand)]
Expand All @@ -38,6 +41,23 @@ async fn main() -> Result<()> {
let args = Cli::parse();
let app = Arc::new(App::new()?);

if let Err(e) = app.try_read_files().await {
println!("Error while reading files: {e:?}");
}

if !args.src.is_empty() {
let mut wg = app.server.write().await;
let (_, server) = wg.get_or_insert_with(|| (
std::env::current_dir().unwrap().join(SERVER_TOML),
Server::default()
));
for source_type in args.src {
server.sources.push(Source {
source_type
});
}
}

match args.command {
Commands::Init(args) => commands::init::run(app, args).await,
Commands::Sources(args) => commands::sources::run(app, args).await,
Expand All @@ -46,6 +66,5 @@ async fn main() -> Result<()> {
Commands::Java(args) => commands::java::run(app, args).await,
Commands::Markdown(args) => commands::markdown::run(app, args).await,
Commands::Migrate(args) => commands::migrate::run(app, args).await,

}
}

0 comments on commit 69fac3b

Please sign in to comment.