legacympt-rs/mpt/src/util.rs
2021-08-29 15:14:10 +02:00

83 lines
2.2 KiB
Rust

use addonscript::manifest::{Manifest, Repository};
use std::path::Path;
use thiserror::Error;
use url::Url;
use crate::config::Config;
pub async fn parse_config() -> anyhow::Result<Config> {
let conf = tokio::fs::read("modpacktoolsconfig.toml").await?;
Ok(toml::from_slice(&conf)?)
}
pub async fn parse_config_and_manifest() -> anyhow::Result<(Config, Manifest)> {
let config = parse_config().await?;
let src = Path::new(&config.locations.src);
let path = if src.join("modpack.json5").exists() {
src.join("modpack.json5")
} else {
src.join("modpack.json")
};
let data = tokio::fs::read(path).await?;
let data = std::str::from_utf8(&data)?;
let manifest = json5::from_str::<Manifest>(data)?;
Ok((config, manifest))
}
#[derive(Debug, Error)]
pub enum MvnArtifactUrlError {
#[error("Maven Artifact specifier has invalid format!")]
InvalidFormat,
#[error("Url parse error while processing maven artifact: {0}")]
UrlParseError(#[from] url::ParseError),
}
pub fn mvn_artifact_to_url(art: &str, repo: &Repository) -> Result<Url, MvnArtifactUrlError> {
let mut splits = art.split(':');
let group_id = splits.next().ok_or(MvnArtifactUrlError::InvalidFormat)?;
let artifact_id = splits.next().ok_or(MvnArtifactUrlError::InvalidFormat)?;
let version = splits.next().ok_or(MvnArtifactUrlError::InvalidFormat)?;
let mut url = repo.url.clone();
if !url.path().ends_with('/') {
url.set_path(&format!("{}/", repo.url.path()));
}
let url = url.join(&format!(
"{gid}/{aid}/{v}/{aid}-{v}.jar",
gid = group_id.replace('.', "/"),
aid = artifact_id,
v = version
))?;
Ok(url)
}
#[cfg(test)]
mod tests {
use addonscript::manifest::RepositoryType;
use super::*;
fn repo() -> Repository {
Repository {
id: "test".into(),
repo_type: RepositoryType::Maven,
url: Url::parse("https://example.com/maven").unwrap(),
}
}
#[test]
fn artifact_to_url_valid() {
let res = mvn_artifact_to_url("de.mzte:test:0.1", &repo()).unwrap();
assert_eq!(
res,
Url::parse("https://example.com/maven/de/mzte/test/0.1/test-0.1.jar").unwrap()
);
}
}