refactor: upgrade crates and restructure project

This commit is contained in:
objz committed 2026-04-18 16:59:27 +02:00
1 parent ea093c044f
commit 47dad69321
80 files changed
+6094 -6125

No files matched your search

+6 -96
View File
@@ -43,27 +43,7 @@ pub struct FabricLibrary {
pub async fn fetch_fabric_game_versions(client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
let url = format!("{}/versions/game", FABRIC_META_BASE);
let response = match client.inner().get(&url).send().await {
Ok(r) => r,
Err(e) => {
tracing::error!("Fabric game versions GET {} failed: {}", url, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("HTTP {} for {}", status, url);
return Err(NetError::StatusError { status, url });
}
let versions: Vec<FabricGameVersion> = match response.json().await {
Ok(v) => v,
Err(e) => {
tracing::error!("Failed to parse Fabric game versions: {}", e);
return Err(NetError::Http(e));
}
};
let versions: Vec<FabricGameVersion> = client.get_json(&url).await?;
Ok(versions
.into_iter()
@@ -79,33 +59,7 @@ pub async fn fetch_fabric_versions(
game_version: &str,
) -> Result<Vec<FabricLoaderVersion>, NetError> {
let url = format!("{}/versions/loader/{}", FABRIC_META_BASE, game_version);
let response = match client.inner().get(&url).send().await {
Ok(r) => r,
Err(e) => {
tracing::error!("Fabric meta GET {} failed: {}", url, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("Fabric meta HTTP {} for {}", status, url);
return Err(NetError::StatusError {
status,
url: url.clone(),
});
}
let versions: Vec<FabricLoaderVersion> = match response.json().await {
Ok(v) => v,
Err(e) => {
tracing::error!("Failed to parse Fabric loader versions: {}", e);
return Err(NetError::Http(e));
}
};
Ok(versions)
client.get_json(&url).await
}
pub async fn fetch_fabric_profile(
@@ -117,33 +71,7 @@ pub async fn fetch_fabric_profile(
"{}/versions/loader/{}/{}/profile/json",
FABRIC_META_BASE, game_version, loader_version
);
let response = match client.inner().get(&url).send().await {
Ok(r) => r,
Err(e) => {
tracing::error!("Fabric profile GET {} failed: {}", url, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("Fabric profile HTTP {} for {}", status, url);
return Err(NetError::StatusError {
status,
url: url.clone(),
});
}
let profile: FabricProfile = match response.json().await {
Ok(p) => p,
Err(e) => {
tracing::error!("Failed to parse Fabric profile: {}", e);
return Err(NetError::Http(e));
}
};
Ok(profile)
client.get_json(&url).await
}
pub async fn download_fabric_libraries(
@@ -157,7 +85,6 @@ pub async fn download_fabric_libraries(
let maven_path = match crate::net::maven_coord_to_path(&lib.name) {
Some(p) => p,
None => {
tracing::error!("Invalid Maven coordinate in Fabric profile: {}", lib.name);
return Err(NetError::Parse(format!(
"Invalid Maven coordinate: {}",
lib.name
@@ -178,13 +105,7 @@ pub async fn download_fabric_libraries(
set_sub_action(&lib.name);
tracing::info!("Downloading Fabric library: {}", lib.name);
match download_file(client, &download_url, &dest, |_, _| {}).await {
Ok(()) => {}
Err(e) => {
tracing::error!("Failed to download Fabric library {}: {}", lib.name, e);
return Err(e);
}
}
download_file(client, &download_url, &dest, |_, _| {}).await?;
}
Ok(())
@@ -196,6 +117,7 @@ mod tests {
use crate::net::HttpClient;
#[tokio::test]
#[ignore = "hits live Fabric API"]
async fn test_fetch_versions() {
let client = HttpClient::new();
match fetch_fabric_versions(&client, "1.20.1").await {
@@ -214,6 +136,7 @@ mod tests {
}
#[tokio::test]
#[ignore = "hits live Fabric API"]
async fn test_fetch_game_versions() {
let client = HttpClient::new();
match fetch_fabric_game_versions(&client).await {
@@ -225,17 +148,4 @@ mod tests {
}
}
#[test]
fn test_maven_coord_to_path() {
assert_eq!(
crate::net::maven_coord_to_path("net.fabricmc:fabric-loader:0.16.0"),
Some("net/fabricmc/fabric-loader/0.16.0/fabric-loader-0.16.0.jar".to_string())
);
assert_eq!(
crate::net::maven_coord_to_path("org.ow2.asm:asm:9.6"),
Some("org/ow2/asm/asm/9.6/asm-9.6.jar".to_string())
);
assert_eq!(crate::net::maven_coord_to_path("invalid"), None);
assert_eq!(crate::net::maven_coord_to_path("only:two"), None);
}
}
+6 -66
View File
@@ -24,30 +24,7 @@ pub async fn fetch_forge_versions(
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
let response = match client.inner().get(FORGE_PROMOTIONS_URL).send().await {
Ok(r) => r,
Err(e) => {
tracing::error!("GET {} failed: {}", FORGE_PROMOTIONS_URL, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("HTTP {} for {}", status, FORGE_PROMOTIONS_URL);
return Err(NetError::StatusError {
status,
url: FORGE_PROMOTIONS_URL.to_string(),
});
}
let promotions: ForgePromotions = match response.json().await {
Ok(p) => p,
Err(e) => {
tracing::error!("Failed to parse Forge promotions JSON: {}", e);
return Err(NetError::Http(e));
}
};
let promotions: ForgePromotions = client.get_json(FORGE_PROMOTIONS_URL).await?;
let prefix = format!("{}-", game_version);
let mut versions: Vec<String> = promotions
@@ -63,30 +40,7 @@ pub async fn fetch_forge_versions(
}
pub async fn fetch_forge_game_versions(client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
let response = match client.inner().get(FORGE_PROMOTIONS_URL).send().await {
Ok(r) => r,
Err(e) => {
tracing::error!("GET {} failed: {}", FORGE_PROMOTIONS_URL, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("HTTP {} for {}", status, FORGE_PROMOTIONS_URL);
return Err(NetError::StatusError {
status,
url: FORGE_PROMOTIONS_URL.to_string(),
});
}
let promos: ForgePromotions = match response.json().await {
Ok(p) => p,
Err(e) => {
tracing::error!("Failed to parse Forge promotions: {}", e);
return Err(NetError::Http(e));
}
};
let promos: ForgePromotions = client.get_json(FORGE_PROMOTIONS_URL).await?;
let mut game_versions: Vec<String> = promos
.promos
@@ -127,17 +81,10 @@ pub async fn download_forge_installer(
game_version, forge_version
));
match download_file(client, &url, dest, |downloaded, total| {
download_file(client, &url, dest, |downloaded, total| {
crate::tui::progress::set_progress(downloaded, total);
})
.await
{
Ok(()) => Ok(()),
Err(e) => {
tracing::error!("Failed to download Forge installer from {}: {}", url, e);
Err(e)
}
}
}
/// Run the Forge installer JAR to install Forge into the instance directory.
@@ -163,21 +110,12 @@ pub async fn run_forge_installer(
{
Ok(o) => o,
Err(e) => {
tracing::error!("Failed to launch Forge installer: {}", e);
return Err(NetError::Io(e));
}
};
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
tracing::error!(
"Forge installer failed (exit {:?}): {} {}",
output.status.code(),
stderr,
stdout
);
return Err(NetError::Parse(format!(
return Err(NetError::InstallerFailed(format!(
"Forge installer exited with {:?}",
output.status.code()
)));
@@ -192,6 +130,7 @@ mod tests {
use crate::net::HttpClient;
#[tokio::test]
#[ignore = "hits live Forge API"]
async fn test_fetch_versions() {
let client = HttpClient::new();
match fetch_forge_versions(&client, "1.20.1").await {
@@ -206,6 +145,7 @@ mod tests {
}
#[tokio::test]
#[ignore = "hits live Forge API"]
async fn test_fetch_game_versions() {
let client = HttpClient::new();
match fetch_forge_game_versions(&client).await {
+40 -66
View File
@@ -6,6 +6,7 @@ pub mod modrinth;
pub mod quilt;
use reqwest::Client;
use serde::de::DeserializeOwned;
use std::path::Path;
use thiserror::Error;
@@ -19,6 +20,10 @@ pub enum NetError {
Parse(String),
#[error("Server returned error status {status}: {url}")]
StatusError { status: u16, url: String },
#[error("Installer process failed: {0}")]
InstallerFailed(String),
#[error("Task failed: {0}")]
TaskFailed(String),
}
#[derive(Clone)]
@@ -34,24 +39,32 @@ impl Default for HttpClient {
impl HttpClient {
pub fn new() -> Self {
match Client::builder()
.user_agent("mcl/0.1.0 (Minecraft Launcher)")
let client = Client::builder()
.user_agent(format!("mcl/{} (Minecraft Launcher)", env!("CARGO_PKG_VERSION")))
.timeout(std::time::Duration::from_secs(30))
.build()
{
Ok(client) => HttpClient { inner: client },
Err(e) => {
tracing::error!("Failed to build HTTP client: {}", e);
HttpClient {
inner: Client::new(),
}
}
}
.unwrap_or_else(|_| Client::new());
Self { inner: client }
}
pub fn inner(&self) -> &Client {
&self.inner
}
pub async fn get(&self, url: &str) -> Result<reqwest::Response, NetError> {
let response = self.inner.get(url).send().await?;
if !response.status().is_success() {
return Err(NetError::StatusError {
status: response.status().as_u16(),
url: url.to_string(),
});
}
Ok(response)
}
pub async fn get_json<T: DeserializeOwned>(&self, url: &str) -> Result<T, NetError> {
Ok(self.get(url).await?.json().await?)
}
}
/// Download a file from `url` to `dest`, calling `progress_cb(bytes_downloaded, total_bytes)` as chunks arrive.
@@ -64,80 +77,41 @@ pub async fn download_file(
) -> Result<(), NetError> {
use tokio::io::AsyncWriteExt;
let response = match client.inner().get(url).send().await {
Ok(r) => r,
Err(e) => {
tracing::error!("GET {} failed: {}", url, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("HTTP {} for {}", status, url);
return Err(NetError::StatusError {
status,
url: url.to_string(),
});
}
let response = client.get(url).await?;
let total = response.content_length().unwrap_or(0);
if let Some(parent) = dest.parent() {
match tokio::fs::create_dir_all(parent).await {
Ok(_) => {}
Err(e) => {
tracing::error!("Failed to create directory {}: {}", parent.display(), e);
return Err(NetError::Io(e));
}
}
tokio::fs::create_dir_all(parent).await?;
}
let mut file = match tokio::fs::File::create(dest).await {
Ok(f) => f,
Err(e) => {
tracing::error!("Failed to create file {}: {}", dest.display(), e);
return Err(NetError::Io(e));
}
};
let mut file = tokio::fs::File::create(dest).await?;
let mut downloaded: u64 = 0;
let mut stream = response;
loop {
match stream.chunk().await {
Ok(Some(chunk)) => {
match file.write_all(&chunk).await {
Ok(_) => {}
Err(e) => {
tracing::error!("Failed to write chunk to {}: {}", dest.display(), e);
return Err(NetError::Io(e));
}
}
downloaded += chunk.len() as u64;
progress_cb(downloaded, total);
}
Ok(None) => break,
Err(e) => {
tracing::error!("Failed to read response chunk from {}: {}", url, e);
return Err(NetError::Http(e));
}
}
while let Some(chunk) = stream.chunk().await? {
file.write_all(&chunk).await?;
downloaded += chunk.len() as u64;
progress_cb(downloaded, total);
}
Ok(())
}
#[must_use]
pub fn detect_java_path() -> String {
if let Ok(java_home) = std::env::var("JAVA_HOME") {
let path = std::path::Path::new(&java_home).join("bin").join("java");
if path.exists() {
return path.to_string_lossy().to_string();
let java_name = if cfg!(windows) { "java.exe" } else { "java" };
let bin = std::path::Path::new(&java_home).join("bin").join(java_name);
if bin.exists() {
return bin.to_string_lossy().to_string();
}
}
"java".to_string()
which::which("java")
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|_| "java".to_string())
}
#[must_use]
pub fn maven_coord_to_path(coord: &str) -> Option<String> {
let parts: Vec<&str> = coord.split(':').collect();
match parts.as_slice() {
+24 -39
View File
@@ -106,23 +106,28 @@ pub fn game_version_from_dependencies(deps: &HashMap<String, String>) -> Option<
const API_BASE: &str = "https://api.modrinth.com/v2";
fn url_encode(s: &str) -> String {
use std::fmt::Write;
let mut encoded = String::with_capacity(s.len());
for byte in s.bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
encoded.push(byte as char);
}
_ => {
write!(encoded, "%{byte:02X}").unwrap();
}
}
}
encoded
}
pub async fn fetch_project(
client: &crate::net::HttpClient,
slug_or_id: &str,
) -> Result<ProjectInfo, crate::net::NetError> {
let url = format!("{}/project/{}", API_BASE, slug_or_id);
let resp = client
.inner()
.get(&url)
.send()
.await?;
if !resp.status().is_success() {
return Err(crate::net::NetError::StatusError {
status: resp.status().as_u16(),
url,
});
}
resp.json().await.map_err(crate::net::NetError::Http)
let url = format!("{}/project/{}", API_BASE, url_encode(slug_or_id));
client.get_json(&url).await
}
pub async fn fetch_versions(
@@ -131,39 +136,17 @@ pub async fn fetch_versions(
) -> Result<Vec<VersionInfo>, crate::net::NetError> {
let url = format!(
"{}/project/{}/version?loaders=[\"fabric\",\"forge\",\"neoforge\",\"quilt\"]",
API_BASE, slug_or_id
API_BASE, url_encode(slug_or_id)
);
let resp = client
.inner()
.get(&url)
.send()
.await?;
if !resp.status().is_success() {
return Err(crate::net::NetError::StatusError {
status: resp.status().as_u16(),
url,
});
}
resp.json().await.map_err(crate::net::NetError::Http)
client.get_json(&url).await
}
pub async fn fetch_version(
client: &crate::net::HttpClient,
version_id: &str,
) -> Result<VersionInfo, crate::net::NetError> {
let url = format!("{}/version/{}", API_BASE, version_id);
let resp = client
.inner()
.get(&url)
.send()
.await?;
if !resp.status().is_success() {
return Err(crate::net::NetError::StatusError {
status: resp.status().as_u16(),
url,
});
}
resp.json().await.map_err(crate::net::NetError::Http)
let url = format!("{}/version/{}", API_BASE, url_encode(version_id));
client.get_json(&url).await
}
pub async fn download_mrpack(
@@ -315,6 +298,7 @@ mod tests {
}
#[tokio::test]
#[ignore = "hits live Modrinth API"]
async fn test_fetch_project() {
let client = crate::net::HttpClient::new();
let project = fetch_project(&client, "fabulously-optimized").await;
@@ -328,6 +312,7 @@ mod tests {
}
#[tokio::test]
#[ignore = "hits live Modrinth API"]
async fn test_fetch_versions() {
let client = crate::net::HttpClient::new();
let versions = fetch_versions(&client, "fabulously-optimized").await;
+8 -46
View File
@@ -117,14 +117,14 @@ pub struct AssetObject {
}
pub async fn fetch_version_manifest(client: &HttpClient) -> Result<VersionManifest, NetError> {
fetch_json(client, MANIFEST_URL).await
client.get_json(MANIFEST_URL).await
}
pub async fn fetch_version_meta(
client: &HttpClient,
entry: &VersionEntry,
) -> Result<VersionMeta, NetError> {
fetch_json(client, &entry.url).await
client.get_json(&entry.url).await
}
pub async fn download_client_jar(
@@ -203,7 +203,7 @@ pub async fn download_assets(
) -> Result<(), NetError> {
set_action("Downloading assets...");
let asset_index = match fetch_json::<AssetIndexContent>(client, &meta.asset_index.url).await {
let asset_index: AssetIndexContent = match client.get_json(&meta.asset_index.url).await {
Ok(index) => index,
Err(e) => {
clear();
@@ -242,10 +242,8 @@ pub async fn download_assets(
let mut downloads = Vec::new();
for object in asset_index.objects.values() {
if object.hash.len() < 2 {
let message = format!("Invalid asset hash: {}", object.hash);
tracing::error!("{}", message);
clear();
return Err(NetError::Parse(message));
return Err(NetError::Parse(format!("Invalid asset hash: {}", object.hash)));
}
let prefix = &object.hash[..2];
@@ -274,36 +272,6 @@ pub async fn download_assets(
result
}
async fn fetch_json<T>(client: &HttpClient, url: &str) -> Result<T, NetError>
where
T: for<'de> Deserialize<'de>,
{
let response = match client.inner().get(url).send().await {
Ok(response) => response,
Err(e) => {
tracing::error!("Failed to fetch {}: {}", url, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("HTTP {} from {}", status, url);
return Err(NetError::StatusError {
status,
url: url.to_string(),
});
}
match response.json::<T>().await {
Ok(data) => Ok(data),
Err(e) => {
tracing::error!("Failed to parse JSON from {}: {}", url, e);
Err(NetError::Http(e))
}
}
}
fn library_allowed_for_current_os(library: &Library) -> bool {
let rules = match &library.rules {
Some(rules) => rules,
@@ -384,7 +352,7 @@ async fn run_parallel_downloads(
Err(e) => {
tracing::error!("Task panicked: {}", e);
if first_error.is_none() {
first_error = Some(NetError::Parse(format!("Join error: {}", e)));
first_error = Some(NetError::TaskFailed(format!("Join error: {}", e)));
}
}
}
@@ -409,18 +377,11 @@ fn spawn_download_task(
job: (String, PathBuf, String),
) {
let (url, destination, label) = job;
let task_client = HttpClient {
inner: client.inner().clone(),
};
let task_client = client.clone();
set.spawn(async move {
let label_for_progress = label.clone();
let result = download_file(&task_client, &url, &destination, |_current, _total| {}).await;
match result {
Ok(()) => Ok(label_for_progress),
Err(e) => Err(e),
}
result.map(|()| label)
});
}
@@ -430,6 +391,7 @@ mod tests {
use crate::net::HttpClient;
#[tokio::test]
#[ignore = "hits live Mojang API"]
async fn test_fetch_manifest_contains_1_20_1() {
let client = HttpClient::new();
match fetch_version_manifest(&client).await {
+6 -72
View File
@@ -26,8 +26,6 @@ fn game_version_to_neoforge_prefix(game_version: &str) -> Option<String> {
["1", minor] => Some(format!("{}.0.", minor)),
// "1.20.4" → prefix "20.4."
["1", minor, patch] => Some(format!("{}.{}.", minor, patch)),
[major, minor] => Some(format!("{}.{}.", major, minor)),
[major, minor, _patch] => Some(format!("{}.{}.", major, minor)),
_ => None,
}
}
@@ -39,10 +37,6 @@ pub async fn fetch_neoforge_versions(
let prefix = match game_version_to_neoforge_prefix(game_version) {
Some(p) => p,
None => {
tracing::error!(
"Cannot map game version '{}' to NeoForge version prefix",
game_version
);
return Err(NetError::Parse(format!(
"Invalid game version for NeoForge: {}",
game_version
@@ -50,30 +44,7 @@ pub async fn fetch_neoforge_versions(
}
};
let response = match client.inner().get(NEOFORGE_API_BASE).send().await {
Ok(r) => r,
Err(e) => {
tracing::error!("GET {} failed: {}", NEOFORGE_API_BASE, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("HTTP {} for {}", status, NEOFORGE_API_BASE);
return Err(NetError::StatusError {
status,
url: NEOFORGE_API_BASE.to_string(),
});
}
let maven_versions: NeoForgeMavenVersions = match response.json().await {
Ok(v) => v,
Err(e) => {
tracing::error!("Failed to parse NeoForge maven versions: {}", e);
return Err(NetError::Http(e));
}
};
let maven_versions: NeoForgeMavenVersions = client.get_json(NEOFORGE_API_BASE).await?;
let versions: Vec<String> = maven_versions
.versions
@@ -87,30 +58,7 @@ pub async fn fetch_neoforge_versions(
pub async fn fetch_neoforge_game_versions(
client: &HttpClient,
) -> Result<Vec<GameVersion>, NetError> {
let response = match client.inner().get(NEOFORGE_API_BASE).send().await {
Ok(r) => r,
Err(e) => {
tracing::error!("GET {} failed: {}", NEOFORGE_API_BASE, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("HTTP {} for {}", status, NEOFORGE_API_BASE);
return Err(NetError::StatusError {
status,
url: NEOFORGE_API_BASE.to_string(),
});
}
let maven: NeoForgeMavenVersions = match response.json().await {
Ok(m) => m,
Err(e) => {
tracing::error!("Failed to parse NeoForge versions: {}", e);
return Err(NetError::Http(e));
}
};
let maven: NeoForgeMavenVersions = client.get_json(NEOFORGE_API_BASE).await?;
let mut game_versions: Vec<String> = Vec::new();
for version in &maven.versions {
@@ -152,17 +100,10 @@ pub async fn download_neoforge_installer(
set_action(format!("Downloading NeoForge {}...", neoforge_version));
match download_file(client, &url, dest, |downloaded, total| {
download_file(client, &url, dest, |downloaded, total| {
crate::tui::progress::set_progress(downloaded, total);
})
.await
{
Ok(()) => Ok(()),
Err(e) => {
tracing::error!("Failed to download NeoForge installer from {}: {}", url, e);
Err(e)
}
}
}
pub async fn run_neoforge_installer(
@@ -184,21 +125,12 @@ pub async fn run_neoforge_installer(
{
Ok(o) => o,
Err(e) => {
tracing::error!("Failed to launch NeoForge installer: {}", e);
return Err(NetError::Io(e));
}
};
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
tracing::error!(
"NeoForge installer failed (exit {:?}): {} {}",
output.status.code(),
stderr,
stdout
);
return Err(NetError::Parse(format!(
return Err(NetError::InstallerFailed(format!(
"NeoForge installer exited with {:?}",
output.status.code()
)));
@@ -213,6 +145,7 @@ mod tests {
use crate::net::HttpClient;
#[tokio::test]
#[ignore = "hits live NeoForge API"]
async fn test_fetch_versions() {
let client = HttpClient::new();
match fetch_neoforge_versions(&client, "1.21").await {
@@ -227,6 +160,7 @@ mod tests {
}
#[tokio::test]
#[ignore = "hits live NeoForge API"]
async fn test_fetch_game_versions() {
let client = HttpClient::new();
match fetch_neoforge_game_versions(&client).await {
+6 -93
View File
@@ -40,28 +40,7 @@ pub struct QuiltLibrary {
pub async fn fetch_quilt_game_versions(client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
let url = format!("{}/versions/game", QUILT_META_BASE);
let response = match client.inner().get(&url).send().await {
Ok(r) => r,
Err(e) => {
tracing::error!("Quilt game versions GET {} failed: {}", url, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("HTTP {} for {}", status, url);
return Err(NetError::StatusError { status, url });
}
let versions: Vec<QuiltGameVersion> = match response.json().await {
Ok(v) => v,
Err(e) => {
tracing::error!("Failed to parse Quilt game versions: {}", e);
return Err(NetError::Http(e));
}
};
let versions: Vec<QuiltGameVersion> = client.get_json(&url).await?;
Ok(versions
.into_iter()
@@ -77,33 +56,7 @@ pub async fn fetch_quilt_versions(
game_version: &str,
) -> Result<Vec<QuiltLoaderVersion>, NetError> {
let url = format!("{}/versions/loader/{}", QUILT_META_BASE, game_version);
let response = match client.inner().get(&url).send().await {
Ok(r) => r,
Err(e) => {
tracing::error!("Quilt meta GET {} failed: {}", url, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("Quilt meta HTTP {} for {}", status, url);
return Err(NetError::StatusError {
status,
url: url.clone(),
});
}
let versions: Vec<QuiltLoaderVersion> = match response.json().await {
Ok(v) => v,
Err(e) => {
tracing::error!("Failed to parse Quilt loader versions: {}", e);
return Err(NetError::Http(e));
}
};
Ok(versions)
client.get_json(&url).await
}
pub async fn fetch_quilt_profile(
@@ -115,33 +68,7 @@ pub async fn fetch_quilt_profile(
"{}/versions/loader/{}/{}/profile/json",
QUILT_META_BASE, game_version, loader_version
);
let response = match client.inner().get(&url).send().await {
Ok(r) => r,
Err(e) => {
tracing::error!("Quilt profile GET {} failed: {}", url, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("Quilt profile HTTP {} for {}", status, url);
return Err(NetError::StatusError {
status,
url: url.clone(),
});
}
let profile: QuiltProfile = match response.json().await {
Ok(p) => p,
Err(e) => {
tracing::error!("Failed to parse Quilt profile: {}", e);
return Err(NetError::Http(e));
}
};
Ok(profile)
client.get_json(&url).await
}
pub async fn download_quilt_libraries(
@@ -155,7 +82,6 @@ pub async fn download_quilt_libraries(
let maven_path = match crate::net::maven_coord_to_path(&lib.name) {
Some(p) => p,
None => {
tracing::error!("Invalid Maven coordinate in Quilt profile: {}", lib.name);
return Err(NetError::Parse(format!(
"Invalid Maven coordinate: {}",
lib.name
@@ -176,13 +102,7 @@ pub async fn download_quilt_libraries(
set_sub_action(&lib.name);
tracing::info!("Downloading Quilt library: {}", lib.name);
match download_file(client, &download_url, &dest, |_, _| {}).await {
Ok(()) => {}
Err(e) => {
tracing::error!("Failed to download Quilt library {}: {}", lib.name, e);
return Err(e);
}
}
download_file(client, &download_url, &dest, |_, _| {}).await?;
}
Ok(())
@@ -194,6 +114,7 @@ mod tests {
use crate::net::HttpClient;
#[tokio::test]
#[ignore = "hits live Quilt API"]
async fn test_fetch_versions() {
let client = HttpClient::new();
match fetch_quilt_versions(&client, "1.20.1").await {
@@ -208,6 +129,7 @@ mod tests {
}
#[tokio::test]
#[ignore = "hits live Quilt API"]
async fn test_fetch_game_versions() {
let client = HttpClient::new();
match fetch_quilt_game_versions(&client).await {
@@ -219,13 +141,4 @@ mod tests {
}
}
#[test]
fn test_maven_coord_to_path() {
assert_eq!(
crate::net::maven_coord_to_path("org.quiltmc:quilt-loader:0.20.0"),
Some("org/quiltmc/quilt-loader/0.20.0/quilt-loader-0.20.0.jar".to_string())
);
assert_eq!(crate::net::maven_coord_to_path("invalid"), None);
assert_eq!(crate::net::maven_coord_to_path("only:two"), None);
}
}