refactor: reorganize source and tests

This commit is contained in:
objz committed 2026-07-27 11:28:57 +02:00
1 parent 15d76c18a0
commit c6205a337c
139 files changed
+5532 -5548

No files matched your search

+2 -2
View File
@@ -5,9 +5,9 @@ use std::path::Path;
use serde::{Deserialize, Serialize};
use crate::feedback::progress::set_sub_action;
use crate::instance::loader::GameVersion;
use crate::net::{HttpClient, NetError, download_file};
use crate::tui::progress::set_sub_action;
const FABRIC_META_BASE: &str = "https://meta.fabricmc.net/v2";
@@ -163,7 +163,7 @@ pub async fn download_fabric_libraries(
);
for lib in &profile.libraries {
let maven_path = match crate::net::maven_coord_to_path(&lib.name) {
let maven_path = match crate::instance::loader::maven::maven_coord_to_path(&lib.name) {
Some(p) => p,
None => {
return Err(NetError::Parse(format!(
+5 -300
View File
@@ -7,9 +7,11 @@ use std::path::Path;
use serde::Deserialize;
use crate::instance::loader::{GameVersion, InstallError, InstallerError};
use crate::feedback::progress::set_action;
use crate::instance::loader::GameVersion;
use crate::net::{HttpClient, NetError, download_file};
use crate::tui::progress::{set_action, set_sub_action};
pub use crate::instance::loader::forge::run_forge_installer;
const FORGE_PROMOTIONS_URL: &str =
"https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json";
@@ -115,7 +117,7 @@ pub async fn download_forge_installer(
let url = format!("{}/{slug}/forge-{slug}-installer.jar", FORGE_MAVEN_BASE,);
tracing::debug!("Trying Forge installer slug '{}'", slug);
match download_file(client, &url, dest, |downloaded, total| {
crate::tui::progress::set_progress(downloaded, total);
crate::feedback::progress::set_progress(downloaded, total);
})
.await
{
@@ -136,300 +138,3 @@ pub async fn download_forge_installer(
))
}))
}
pub async fn run_forge_installer(
installer_path: &Path,
instance_dir: &Path,
java_path: &str,
) -> Result<(), InstallerError> {
use tokio::process::Command;
set_action("Running Forge installer...");
let output = match Command::new(java_path)
.arg("-jar")
.arg(installer_path)
.arg("--installClient")
.current_dir(instance_dir.join(crate::storage::MINECRAFT_DIR_NAME))
.output()
.await
{
Ok(o) => o,
Err(e) => {
tracing::debug!(
"Failed to spawn Forge installer {} with Java {}: {}",
installer_path.display(),
java_path,
e
);
return Err(InstallerError::Io(e));
}
};
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let detail = if stderr.trim().is_empty() {
format!("exit code {:?}", output.status.code())
} else {
stderr.lines().last().unwrap_or("unknown error").to_string()
};
tracing::debug!(
"Forge installer {} failed with status {:?}: {}",
installer_path.display(),
output.status.code(),
detail
);
return Err(InstallerError::ProcessFailed(detail));
}
tracing::debug!("Forge installer completed successfully");
Ok(())
}
// old forge installers have an install_profile.json with a "versionInfo" key
// containing everything needed. modern ones don't have this structure.
pub(crate) fn has_legacy_install_profile(installer_path: &Path) -> bool {
let file = match std::fs::File::open(installer_path) {
Ok(f) => f,
Err(_) => return false,
};
let mut archive = match zip::ZipArchive::new(file) {
Ok(a) => a,
Err(_) => return false,
};
let entry = match archive.by_name("install_profile.json") {
Ok(e) => e,
Err(_) => return false,
};
let value: serde_json::Value = match serde_json::from_reader(entry) {
Ok(v) => v,
Err(_) => return false,
};
value.get("versionInfo").is_some()
}
// handles old-style forge installation by extracting the universal jar and
// library info directly from the installer, bypassing the GUI-only installer
pub(crate) async fn install_forge_from_profile(
client: &HttpClient,
installer_path: &Path,
meta_dir: &Path,
profile_filename: &str,
) -> Result<(), InstallError> {
use std::io::Read;
set_action("Installing legacy Forge from profile...");
tracing::debug!(
"Installing legacy Forge from {} into {}",
installer_path.display(),
meta_dir.display()
);
let file = std::fs::File::open(installer_path)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
let mut archive = zip::ZipArchive::new(file).map_err(|e| {
InstallError::Installer(InstallerError::Profile(format!(
"Failed to open installer as ZIP: {e}"
)))
})?;
let profile_data: serde_json::Value = {
let entry = archive.by_name("install_profile.json").map_err(|e| {
InstallError::Installer(InstallerError::Profile(format!(
"install_profile.json not found in installer: {e}"
)))
})?;
serde_json::from_reader(entry).map_err(|e| {
InstallError::Installer(InstallerError::Profile(format!(
"Failed to parse install_profile.json: {e}"
)))
})?
};
let version_info = profile_data.get("versionInfo").ok_or_else(|| {
InstallError::Installer(InstallerError::Profile(
"install_profile.json missing versionInfo".into(),
))
})?;
let install_info = profile_data.get("install").ok_or_else(|| {
InstallError::Installer(InstallerError::Profile(
"install_profile.json missing install section".into(),
))
})?;
let libraries = version_info
.get("libraries")
.and_then(|v| v.as_array())
.ok_or_else(|| {
InstallError::Installer(InstallerError::Profile(
"missing versionInfo.libraries".into(),
))
})?;
let file_path = install_info
.get("filePath")
.and_then(|v| v.as_str())
.ok_or_else(|| {
InstallError::Installer(InstallerError::Profile("missing install.filePath".into()))
})?;
let install_path_coord = install_info
.get("path")
.and_then(|v| v.as_str())
.ok_or_else(|| {
InstallError::Installer(InstallerError::Profile("missing install.path".into()))
})?;
// extract the universal jar to the correct maven location
let universal_maven_path =
crate::net::maven_coord_to_path(install_path_coord).ok_or_else(|| {
InstallError::Installer(InstallerError::Profile(format!(
"Invalid maven coord in install.path: {install_path_coord}"
)))
})?;
set_sub_action("Extracting universal JAR...");
let universal_dest = crate::storage::MetadataPaths::new(meta_dir)
.libraries()
.join(&universal_maven_path);
if let Some(parent) = universal_dest.parent() {
std::fs::create_dir_all(parent)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
}
{
let mut entry = archive.by_name(file_path).map_err(|e| {
InstallError::Installer(InstallerError::Profile(format!(
"Universal JAR '{file_path}' not found in installer: {e}"
)))
})?;
let mut buf = Vec::new();
entry
.read_to_end(&mut buf)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
std::fs::write(&universal_dest, &buf)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
tracing::debug!(
"Extracted legacy Forge universal JAR to {} ({} bytes)",
universal_dest.display(),
buf.len()
);
}
// download libraries needed by this forge version. libs with a url field
// are forge-hosted, libs without one are typically from mojang's library
// server. old forge versions reference libs like launchwrapper that aren't
// in mojang's modern version metadata, so we fetch those too.
let libraries_dir = crate::storage::MetadataPaths::new(meta_dir).libraries();
for lib in libraries {
let name = lib.get("name").and_then(|v| v.as_str()).unwrap_or_default();
let maven_path = match crate::net::maven_coord_to_path(name) {
Some(p) => p,
None => {
return Err(InstallError::Installer(InstallerError::Profile(format!(
"Invalid Maven coordinate: {name}"
))));
}
};
let dest = libraries_dir.join(&maven_path);
if dest.exists() {
tracing::trace!("Legacy Forge library already cached: {}", name);
continue;
}
let base_url = lib
.get("url")
.and_then(|v| v.as_str())
.unwrap_or("https://libraries.minecraft.net/")
.trim_end_matches('/');
let download_url = format!("{base_url}/{maven_path}");
set_sub_action(name);
tracing::debug!("Downloading legacy Forge library {}", name);
download_file(client, &download_url, &dest, |_, _| {}).await?;
}
set_action("Saving Forge profile...");
// write the installer's versionInfo as compact JSON. it already has the
// mainClass, the full library list (with name + url for forge-hosted
// libs), and minecraftArguments (the legacy --tweakClass etc). the
// launch flow parses this as a LaunchProfile and - if there's no
// inheritsFrom field - implicitly inherits from the configured game
// version so vanilla libraries layer in via resolve().
//
// we use serde_json::to_vec (not the pretty-print variant via
// save_profile_json) so the written file is content-faithful: every
// field present in the installer's versionInfo round-trips. key order
// and whitespace may differ from the original installer JSON because
// the source is a serde_json::Value (which doesn't preserve order),
// but no field is silently dropped.
let serialized = serde_json::to_vec(version_info).map_err(|e| {
InstallError::Installer(InstallerError::Profile(format!(
"Failed to serialize Forge profile: {e}"
)))
})?;
crate::instance::loader::save_profile_bytes(meta_dir, profile_filename, &serialized)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
// builds an in-memory zip in a tempdir with the given json as
// install_profile.json. lets the legacy-install-profile detector be
// tested without an actual forge installer.
fn make_installer_zip(tmp: &std::path::Path, json: &serde_json::Value) -> std::path::PathBuf {
use std::io::Write;
let path = tmp.join("installer.jar");
let file = std::fs::File::create(&path).unwrap();
let mut zip = zip::ZipWriter::new(file);
let opts: zip::write::SimpleFileOptions = Default::default();
zip.start_file("install_profile.json", opts).unwrap();
zip.write_all(serde_json::to_string(json).unwrap().as_bytes())
.unwrap();
zip.finish().unwrap();
path
}
#[test]
fn has_legacy_install_profile_true_when_version_info_present() {
let tmp = tempfile::tempdir().unwrap();
let jar = make_installer_zip(
tmp.path(),
&serde_json::json!({
"install": {},
"versionInfo": {
"id": "1.7.10-Forge10.13.4.1614-1.7.10",
"mainClass": "net.minecraft.launchwrapper.Launch"
}
}),
);
assert!(has_legacy_install_profile(&jar));
}
#[test]
fn has_legacy_install_profile_false_when_version_info_absent() {
let tmp = tempfile::tempdir().unwrap();
let jar = make_installer_zip(
tmp.path(),
&serde_json::json!({
"spec": 1,
"minecraft": "1.20.1",
"data": {}
}),
);
assert!(!has_legacy_install_profile(&jar));
}
#[test]
fn has_legacy_install_profile_false_for_missing_jar() {
let tmp = tempfile::tempdir().unwrap();
assert!(!has_legacy_install_profile(
&tmp.path().join("missing-installer.jar")
));
}
}
+3 -92
View File
@@ -8,6 +8,9 @@ pub mod mojang;
pub mod neoforge;
pub mod quilt;
pub use crate::instance::java::detect_java_path;
pub use crate::instance::loader::maven::maven_coord_to_path;
use reqwest::Client;
use serde::Serialize;
use serde::de::DeserializeOwned;
@@ -277,95 +280,3 @@ fn is_retryable(err: &NetError) -> bool {
_ => false,
}
}
// tries JAVA_HOME first, then PATH, then just yolos "java" and hopes for the best
#[must_use]
pub fn detect_java_path() -> String {
if let Ok(java_home) = std::env::var("JAVA_HOME") {
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() {
tracing::trace!("Detected Java from JAVA_HOME: {}", bin.display());
return bin.to_string_lossy().to_string();
}
tracing::warn!(
"JAVA_HOME is set to {}, but {} does not exist",
java_home,
bin.display()
);
}
match which::which("java") {
Ok(path) => {
tracing::trace!("Detected Java from PATH: {}", path.display());
path.to_string_lossy().to_string()
}
Err(e) => {
tracing::warn!(
"Could not find java on PATH, falling back to literal 'java': {}",
e
);
"java".to_string()
}
}
}
// converts maven coordinates like "org.example:artifact:1.0" into a
// filesystem path like "org/example/artifact/1.0/artifact-1.0.jar".
// supports optional classifier as a 4th component.
#[must_use]
pub fn maven_coord_to_path(coord: &str) -> Option<String> {
let parts: Vec<&str> = coord.split(':').collect();
match parts.as_slice() {
[group, artifact, version] => {
let group_path = group.replace('.', "/");
Some(format!(
"{}/{}/{}/{}-{}.jar",
group_path, artifact, version, artifact, version
))
}
[group, artifact, version, classifier] => {
let group_path = group.replace('.', "/");
Some(format!(
"{}/{}/{}/{}-{}-{}.jar",
group_path, artifact, version, artifact, version, classifier
))
}
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn maven_3_part_coord() {
assert_eq!(
maven_coord_to_path("org.example:artifact:1.0"),
Some("org/example/artifact/1.0/artifact-1.0.jar".to_string())
);
}
#[test]
fn maven_4_part_coord_with_classifier() {
assert_eq!(
maven_coord_to_path("org.example:artifact:1.0:sources"),
Some("org/example/artifact/1.0/artifact-1.0-sources.jar".to_string())
);
}
#[test]
fn maven_nested_group() {
assert_eq!(
maven_coord_to_path("com.google.code.gson:gson:2.10"),
Some("com/google/code/gson/gson/2.10/gson-2.10.jar".to_string())
);
}
#[test]
fn maven_invalid_coordinates() {
for coordinate in ["org.example:artifact", "a:b:c:d:e", "just-a-string", ""] {
assert_eq!(maven_coord_to_path(coordinate), None);
}
}
}
+7 -204
View File
@@ -107,7 +107,7 @@ pub async fn search_discovery(
offset: usize,
limit: usize,
) -> Result<DiscoveryResults, crate::net::NetError> {
let progress = crate::tui::progress::ProgressTask::start(if query.trim().is_empty() {
let progress = crate::feedback::progress::ProgressTask::start(if query.trim().is_empty() {
"Loading Modrinth discovery".to_owned()
} else {
format!("Searching Modrinth for '{}'", query.trim())
@@ -235,7 +235,8 @@ pub async fn fetch_content_versions(
game_version: &str,
loader: ModLoader,
) -> Result<Vec<VersionInfo>, crate::net::NetError> {
let progress = crate::tui::progress::ProgressTask::start("Loading compatible project versions");
let progress =
crate::feedback::progress::ProgressTask::start("Loading compatible project versions");
let url = content_versions_url(API_BASE, project_id, kind, game_version, loader);
tracing::debug!(
"Fetching compatible Modrinth versions for '{}' ({}, {})",
@@ -320,7 +321,7 @@ pub async fn download_version_file(
tokio::fs::remove_file(&temporary).await?;
}
let progress =
crate::tui::progress::ProgressTask::start(format!("Downloading {}", file.filename));
crate::feedback::progress::ProgressTask::start(format!("Downloading {}", file.filename));
crate::net::download_file(client, &file.url, &temporary, |current, total| {
progress.set_progress(current, total);
})
@@ -363,7 +364,7 @@ pub async fn download_version_file_for_update(
}
let progress =
crate::tui::progress::ProgressTask::start(format!("Downloading {}", file.filename));
crate::feedback::progress::ProgressTask::start(format!("Downloading {}", file.filename));
crate::net::download_file(client, &file.url, &temporary, |current, total| {
progress.set_progress(current, total);
})
@@ -475,203 +476,5 @@ pub async fn download_mrpack(
}
#[cfg(test)]
mod tests {
use super::*;
fn version_with_files(files: Vec<VersionFile>) -> VersionInfo {
VersionInfo {
id: "version-id".to_owned(),
project_id: "project-id".to_owned(),
name: "Version 1".to_owned(),
version_number: "1.0.0".to_owned(),
game_versions: vec!["1.21.1".to_owned()],
loaders: vec!["fabric".to_owned()],
date_published: String::new(),
files,
}
}
#[test]
fn discovery_mod_facets_include_instance_compatibility() {
let facets = discovery_facets(ContentKind::Mod, "1.21.1", ModLoader::Fabric);
assert_eq!(
serde_json::from_str::<Vec<Vec<String>>>(&facets).unwrap(),
vec![
vec!["project_type:mod"],
vec!["versions:1.21.1"],
vec!["categories:fabric"],
]
);
}
#[test]
fn discovery_resource_pack_facets_do_not_require_loader() {
let facets = discovery_facets(ContentKind::ResourcePack, "1.20.1", ModLoader::Forge);
assert_eq!(
serde_json::from_str::<Vec<Vec<String>>>(&facets).unwrap(),
vec![vec!["project_type:resourcepack"], vec!["versions:1.20.1"]]
);
}
#[test]
fn compatible_mod_versions_filter_by_game_and_loader() {
let url = content_versions_url(
"https://example.test/v2",
"fabric-api",
ContentKind::Mod,
"1.21.1",
ModLoader::Fabric,
);
assert_eq!(
url,
"https://example.test/v2/project/fabric-api/version?include_changelog=false&game_versions=%5B%221.21.1%22%5D&loaders=%5B%22fabric%22%5D"
);
}
#[test]
fn compatible_resource_pack_versions_do_not_filter_by_loader() {
let url = content_versions_url(
"https://example.test/v2",
"stay-true",
ContentKind::ResourcePack,
"1.21.1",
ModLoader::Fabric,
);
assert_eq!(
url,
"https://example.test/v2/project/stay-true/version?include_changelog=false&game_versions=%5B%221.21.1%22%5D"
);
}
#[test]
fn primary_file_selection_falls_back_to_first_file() {
let version = version_with_files(vec![
VersionFile {
url: "https://example.test/first.jar".to_owned(),
filename: "first.jar".to_owned(),
size: 1,
primary: false,
hashes: HashMap::new(),
},
VersionFile {
url: "https://example.test/primary.jar".to_owned(),
filename: "primary.jar".to_owned(),
size: 1,
primary: true,
hashes: HashMap::new(),
},
]);
assert_eq!(
select_primary_file(&version).unwrap().filename,
"primary.jar"
);
let fallback = version_with_files(vec![VersionFile {
url: "https://example.test/first.jar".to_owned(),
filename: "first.jar".to_owned(),
size: 1,
primary: false,
hashes: HashMap::new(),
}]);
assert_eq!(
select_primary_file(&fallback).unwrap().filename,
"first.jar"
);
}
#[tokio::test]
async fn content_download_skips_an_existing_filename() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("example.jar");
std::fs::write(&path, b"existing").unwrap();
let version = version_with_files(vec![VersionFile {
url: "https://example.test/example.jar".to_owned(),
filename: "example.jar".to_owned(),
size: b"existing".len() as u64,
primary: true,
hashes: HashMap::new(),
}]);
let outcome =
download_version_file(&crate::net::HttpClient::new(), &version, directory.path())
.await
.unwrap();
assert_eq!(outcome, DownloadOutcome::SkippedExisting(path));
assert_eq!(
std::fs::read(directory.path().join("example.jar")).unwrap(),
b"existing"
);
}
#[tokio::test]
async fn staged_update_replaces_the_old_file_and_cleans_its_backup() {
let directory = tempfile::tempdir().unwrap();
let installed = directory.path().join("example.jar");
let temporary = directory.path().join(".example.jar.rmcl-download");
let backup = directory.path().join(".example.jar.rmcl-backup");
std::fs::write(&installed, b"old version").unwrap();
std::fs::write(&temporary, b"new version").unwrap();
replace_installed_file(&temporary, &installed, &installed, &backup)
.await
.unwrap();
assert_eq!(std::fs::read(installed).unwrap(), b"new version");
assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1);
}
#[test]
fn discovery_search_ignores_new_modrinth_enum_values() {
let response: DiscoverySearchResponse = serde_json::from_str(
r#"{
"hits": [{
"project_id": "project-id",
"slug": "example",
"title": "Example",
"description": "Example project",
"downloads": 42,
"icon_url": null,
"client_side": "unknown",
"server_side": "unknown"
}],
"total_hits": 1
}"#,
)
.unwrap();
assert_eq!(response.hits.len(), 1);
assert_eq!(response.hits[0].project_id, "project-id");
assert_eq!(response.total_hits, 1);
}
#[test]
fn discovery_search_treats_blank_icon_urls_as_missing() {
let hit: DiscoverySearchHit = serde_json::from_str(
r#"{
"project_id": "project-id",
"slug": "example",
"title": "Example",
"description": "Example project",
"icon_url": " "
}"#,
)
.unwrap();
assert!(DiscoveryProject::from(hit).icon_url.is_none());
}
// covers each branch of url_encode: unreserved bytes pass through; the
// reserved set + spaces + non-ascii bytes get percent-encoded. emoji
// exercises multi-byte UTF-8 since the encoder operates on bytes, not
// chars, so each byte of the codepoint encodes separately.
#[rstest::rstest]
#[case::ascii_unreserved("abcXYZ0-9_.~", "abcXYZ0-9_.~")]
#[case::space("hello world", "hello%20world")]
#[case::reserved("/?&=#", "%2F%3F%26%3D%23")]
#[case::utf8_emoji("\u{2603}", "%E2%98%83")]
#[case::empty("", "")]
fn url_encode_handles(#[case] input: &str, #[case] expected: &str) {
assert_eq!(url_encode(input), expected);
}
}
#[path = "tests/modrinth.rs"]
mod tests;
+1 -1
View File
@@ -15,7 +15,7 @@ use serde::{Deserialize, Serialize};
use tokio::task::JoinSet;
use super::{HttpClient, NetError, download_file};
use crate::tui::progress::{clear, set_action, set_progress, set_sub_action};
use crate::feedback::progress::{clear, set_action, set_progress, set_sub_action};
const MANIFEST_URL: &str = "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json";
const ASSETS_BASE_URL: &str = "https://resources.download.minecraft.net";
+6 -76
View File
@@ -7,10 +7,11 @@ use std::path::Path;
use serde::Deserialize;
use crate::feedback::progress::set_action;
use crate::instance::loader::GameVersion;
use crate::instance::loader::InstallerError;
use crate::net::{HttpClient, NetError, download_file};
use crate::tui::progress::set_action;
pub use crate::instance::loader::neoforge::run_neoforge_installer;
const NEOFORGE_MAVEN_BASE: &str = "https://maven.neoforged.net/releases/net/neoforged/neoforge";
const NEOFORGE_API_BASE: &str =
@@ -163,82 +164,11 @@ pub async fn download_neoforge_installer(
);
download_file(client, &url, dest, |downloaded, total| {
crate::tui::progress::set_progress(downloaded, total);
crate::feedback::progress::set_progress(downloaded, total);
})
.await
}
pub async fn run_neoforge_installer(
installer_path: &Path,
instance_dir: &Path,
java_path: &str,
) -> Result<(), InstallerError> {
use tokio::process::Command;
set_action("Running NeoForge installer...");
let output = match Command::new(java_path)
.arg(format!("-Duser.home={}", instance_dir.display()))
.arg("-jar")
.arg(installer_path)
.arg("--installClient")
.current_dir(instance_dir.join(crate::storage::MINECRAFT_DIR_NAME))
.output()
.await
{
Ok(o) => o,
Err(e) => {
tracing::debug!(
"Failed to spawn NeoForge installer {} with Java {}: {}",
installer_path.display(),
java_path,
e
);
return Err(InstallerError::Io(e));
}
};
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let detail = stderr.lines().last().unwrap_or("").trim();
tracing::debug!(
"NeoForge installer {} failed with status {:?}: {}",
installer_path.display(),
output.status.code(),
detail
);
return Err(InstallerError::ProcessFailed(format!(
"NeoForge installer exited with {:?}",
output.status.code()
)));
}
tracing::debug!("NeoForge installer completed successfully");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_game_version_to_neoforge_prefix() {
assert_eq!(
game_version_to_neoforge_prefix("1.21"),
Some("21.0.".to_string())
);
assert_eq!(
game_version_to_neoforge_prefix("1.20.4"),
Some("20.4.".to_string())
);
assert_eq!(
game_version_to_neoforge_prefix("1.21.1"),
Some("21.1.".to_string())
);
assert_eq!(
game_version_to_neoforge_prefix("26.1.2"),
Some("26.1.2.".to_string())
);
assert_eq!(game_version_to_neoforge_prefix("invalid"), None);
}
}
#[path = "tests/neoforge.rs"]
mod tests;
+2 -2
View File
@@ -5,9 +5,9 @@ use std::path::Path;
use serde::{Deserialize, Serialize};
use crate::feedback::progress::set_sub_action;
use crate::instance::loader::GameVersion;
use crate::net::{HttpClient, NetError, download_file};
use crate::tui::progress::set_sub_action;
const QUILT_META_BASE: &str = "https://meta.quiltmc.org/v3";
@@ -157,7 +157,7 @@ pub async fn download_quilt_libraries(
);
for lib in &profile.libraries {
let maven_path = match crate::net::maven_coord_to_path(&lib.name) {
let maven_path = match crate::instance::loader::maven::maven_coord_to_path(&lib.name) {
Some(p) => p,
None => {
return Err(NetError::Parse(format!(
+197
View File
@@ -0,0 +1,197 @@
use super::*;
fn version_with_files(files: Vec<VersionFile>) -> VersionInfo {
VersionInfo {
id: "version-id".to_owned(),
project_id: "project-id".to_owned(),
name: "Version 1".to_owned(),
version_number: "1.0.0".to_owned(),
game_versions: vec!["1.21.1".to_owned()],
loaders: vec!["fabric".to_owned()],
date_published: String::new(),
files,
}
}
#[test]
fn discovery_mod_facets_include_instance_compatibility() {
let facets = discovery_facets(ContentKind::Mod, "1.21.1", ModLoader::Fabric);
assert_eq!(
serde_json::from_str::<Vec<Vec<String>>>(&facets).unwrap(),
vec![
vec!["project_type:mod"],
vec!["versions:1.21.1"],
vec!["categories:fabric"],
]
);
}
#[test]
fn discovery_resource_pack_facets_do_not_require_loader() {
let facets = discovery_facets(ContentKind::ResourcePack, "1.20.1", ModLoader::Forge);
assert_eq!(
serde_json::from_str::<Vec<Vec<String>>>(&facets).unwrap(),
vec![vec!["project_type:resourcepack"], vec!["versions:1.20.1"]]
);
}
#[test]
fn compatible_mod_versions_filter_by_game_and_loader() {
let url = content_versions_url(
"https://example.test/v2",
"fabric-api",
ContentKind::Mod,
"1.21.1",
ModLoader::Fabric,
);
assert_eq!(
url,
"https://example.test/v2/project/fabric-api/version?include_changelog=false&game_versions=%5B%221.21.1%22%5D&loaders=%5B%22fabric%22%5D"
);
}
#[test]
fn compatible_resource_pack_versions_do_not_filter_by_loader() {
let url = content_versions_url(
"https://example.test/v2",
"stay-true",
ContentKind::ResourcePack,
"1.21.1",
ModLoader::Fabric,
);
assert_eq!(
url,
"https://example.test/v2/project/stay-true/version?include_changelog=false&game_versions=%5B%221.21.1%22%5D"
);
}
#[test]
fn primary_file_selection_falls_back_to_first_file() {
let version = version_with_files(vec![
VersionFile {
url: "https://example.test/first.jar".to_owned(),
filename: "first.jar".to_owned(),
size: 1,
primary: false,
hashes: HashMap::new(),
},
VersionFile {
url: "https://example.test/primary.jar".to_owned(),
filename: "primary.jar".to_owned(),
size: 1,
primary: true,
hashes: HashMap::new(),
},
]);
assert_eq!(
select_primary_file(&version).unwrap().filename,
"primary.jar"
);
let fallback = version_with_files(vec![VersionFile {
url: "https://example.test/first.jar".to_owned(),
filename: "first.jar".to_owned(),
size: 1,
primary: false,
hashes: HashMap::new(),
}]);
assert_eq!(
select_primary_file(&fallback).unwrap().filename,
"first.jar"
);
}
#[tokio::test]
async fn content_download_skips_an_existing_filename() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("example.jar");
std::fs::write(&path, b"existing").unwrap();
let version = version_with_files(vec![VersionFile {
url: "https://example.test/example.jar".to_owned(),
filename: "example.jar".to_owned(),
size: b"existing".len() as u64,
primary: true,
hashes: HashMap::new(),
}]);
let outcome = download_version_file(&crate::net::HttpClient::new(), &version, directory.path())
.await
.unwrap();
assert_eq!(outcome, DownloadOutcome::SkippedExisting(path));
assert_eq!(
std::fs::read(directory.path().join("example.jar")).unwrap(),
b"existing"
);
}
#[tokio::test]
async fn staged_update_replaces_the_old_file_and_cleans_its_backup() {
let directory = tempfile::tempdir().unwrap();
let installed = directory.path().join("example.jar");
let temporary = directory.path().join(".example.jar.rmcl-download");
let backup = directory.path().join(".example.jar.rmcl-backup");
std::fs::write(&installed, b"old version").unwrap();
std::fs::write(&temporary, b"new version").unwrap();
replace_installed_file(&temporary, &installed, &installed, &backup)
.await
.unwrap();
assert_eq!(std::fs::read(installed).unwrap(), b"new version");
assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1);
}
#[test]
fn discovery_search_ignores_new_modrinth_enum_values() {
let response: DiscoverySearchResponse = serde_json::from_str(
r#"{
"hits": [{
"project_id": "project-id",
"slug": "example",
"title": "Example",
"description": "Example project",
"downloads": 42,
"icon_url": null,
"client_side": "unknown",
"server_side": "unknown"
}],
"total_hits": 1
}"#,
)
.unwrap();
assert_eq!(response.hits.len(), 1);
assert_eq!(response.hits[0].project_id, "project-id");
assert_eq!(response.total_hits, 1);
}
#[test]
fn discovery_search_treats_blank_icon_urls_as_missing() {
let hit: DiscoverySearchHit = serde_json::from_str(
r#"{
"project_id": "project-id",
"slug": "example",
"title": "Example",
"description": "Example project",
"icon_url": " "
}"#,
)
.unwrap();
assert!(DiscoveryProject::from(hit).icon_url.is_none());
}
// covers each branch of url_encode: unreserved bytes pass through; the
// reserved set + spaces + non-ascii bytes get percent-encoded. emoji
// exercises multi-byte UTF-8 since the encoder operates on bytes, not
// chars, so each byte of the codepoint encodes separately.
#[rstest::rstest]
#[case::ascii_unreserved("abcXYZ0-9_.~", "abcXYZ0-9_.~")]
#[case::space("hello world", "hello%20world")]
#[case::reserved("/?&=#", "%2F%3F%26%3D%23")]
#[case::utf8_emoji("\u{2603}", "%E2%98%83")]
#[case::empty("", "")]
fn url_encode_handles(#[case] input: &str, #[case] expected: &str) {
assert_eq!(url_encode(input), expected);
}
+22
View File
@@ -0,0 +1,22 @@
use super::*;
#[test]
fn test_game_version_to_neoforge_prefix() {
assert_eq!(
game_version_to_neoforge_prefix("1.21"),
Some("21.0.".to_string())
);
assert_eq!(
game_version_to_neoforge_prefix("1.20.4"),
Some("20.4.".to_string())
);
assert_eq!(
game_version_to_neoforge_prefix("1.21.1"),
Some("21.1.".to_string())
);
assert_eq!(
game_version_to_neoforge_prefix("26.1.2"),
Some("26.1.2.".to_string())
);
assert_eq!(game_version_to_neoforge_prefix("invalid"), None);
}