feat(game): 从其他启动器只读登记已有版本(ull instances scan|adopt)+ 登记可一并定隔离档(M221)
盘上已经铺好的版本(多半是 PCL/HMCL 装的)今天在 ULL 里看不见,用户只能重装一遍。这个 commit 把它们登记成实例,**只读外部、只写自己的配置**:不搬文件、不补清单、不改任何外部 文件的 mtime(versions/ libraries/ assets/ 一个字节都不写)。 core(`game::adopt`,新模块): - `scan` / `inspect`:只读扫描 + 逐项检查,坏 JSON(带行列号)/ 缺 id / id 与目录名不一致 / 缺父 / 成环 / 读不出来 / 越界 / 同名冲突一律**结构化**报错(稳定 `code`),不吞成空列表; `versions/` 不存在才是空结果,读不了就是错误; - 越界判据用 canonicalize 后的前缀比较,同时覆盖**符号链接、Windows 目录联接(junction)与 祖先链接**(junction 不需要管理员权限,是最常见的「把别人版本目录挂进来」);越界条目在 边界检查就停手,一个字节都不去读; - `plan`(零写盘,喂 dry-run 与后续 GUI 预检)/ `adopt`(plan + 只写自己的配置): **缺省运行目录落 ULL 数据区 `<data>/instances/<实例目录名>`(custom 档),绝不沿用全局 `isolated`**——那条缺省的运行目录正是 `versions/<versionId>/`,会在他人的版本目录里长出 mods/saves/config;`shared` / `isolated` 必须显式选,且 `target_notes()` 给出后果话术; - 缺省运行目录已存在且非空 ⇒ 拒绝(不覆盖、不猜「合并进已有实例」);数据区里已有的祖先 若解析到数据根之外(符号链接/联接)⇒ 拒绝,不沿它写盘; - 登记与隔离档一次写清:`install/instance` 拆出 `register` 子模块,新增 `register_with(InstanceSettings)`;写盘顺序改成「先实例设置、后 profiles」(中断只留孤立 设置文件,不会留下按全局档启动的实例),profiles 写失败会撤掉刚写的设置。`register` 签名与行为不变(`register` = `register_with(inherit)`;同版本同名的幂等复用照旧)。 CLI: - `ull instances scan`(只读列出候选与原因)、`ull instances adopt <version-id> [--name N] [--isolation shared|isolated|custom] [--game-dir DIR] [--dry-run]`;`--game-dir` 单独给即 custom,相对路径在解析期就报用法错误; - 人读/`--json`/help 三条出口齐备(`error.detail.problems` 逐条可分流),已有命令未改。 测试(真磁盘夹具,`cargo test -p unlucky-core --test adopt` 22 passed / `cargo test -p unlucky-cli --test adopt_test` 10 passed): - 一份「别的启动器铺好的」`.minecraft`(versions/libraries/assets/mods/saves/config + launcher_profiles.json),扫描与登记前后做「路径集合 + 字节数 + 内容哈希 + mtime」全等断言; - 正常 / 缺清单 / 坏 JSON / 缺父 / 成环 / id 不匹配 / 非法 id / 符号链接越界 / 根内符号链接 放行 / **junction 越界** / 数据区 junction 写盘边界 / 缺省非 isolated / shared 与 isolated 的话术 / 重名 / 重复 / 非空目录 / 空目录复用 / dry-run 零写盘; - CLI 侧验 `launch --dry-run` 的 `--gameDir` 指向选定运行目录(argv 已脱敏,比尾段; `data.game_dir` 全等); - 变异核对(只改实现、跑完即回滚):缺省档改 `VersionDir` ⇒ 红;边界判据摘掉 ⇒ 符号链接与 junction 两条红;写盘边界摘掉 ⇒ 数据区 junction 那条红;缺父当链终点 ⇒ 两条红。 界限:没有启动真实 Minecraft;GUI(presenter/app-iced)接线另派;D20 单游戏根模型未改 (不扫第二个 `.minecraft`)。
This commit is contained in:
1 parent
0577ee87a3
commit
9f5c001387
25 files changed
+3460
-73
No files matched your search
@@ -0,0 +1,292 @@
|
||||
//! 真实磁盘夹具:一份「别的启动器铺好的」`.minecraft` + 全量快照工具。
|
||||
//!
|
||||
//! # 为什么必须是真盘
|
||||
//!
|
||||
//! 本 mission 的核心判据是**「登记前后外部文件一个字节都不变」**。内存里的假目录证明不了这件事
|
||||
//! ——mtime、目录项、符号链接都只有真文件系统才存在。所以每个用例都在 `std::env::temp_dir()`
|
||||
//! 下建一棵真目录树,`Drop` 时整棵删掉。
|
||||
//!
|
||||
//! # 夹具里放了什么(逐项都有用意)
|
||||
//!
|
||||
//! | 路径 | 用意 |
|
||||
//! | --- | --- |
|
||||
//! | `versions/1.20.1/` | 正常版本(清单 + jar) |
|
||||
//! | `versions/1.20.1-fabric-0.15.0/` | 正常版本,`inheritsFrom` 指向 1.20.1(父链闭合) |
|
||||
//! | `versions/1.20.1-broken/` | 清单不是合法 JSON |
|
||||
//! | `versions/1.20.1-orphan/` | `inheritsFrom` 指向不存在的父 |
|
||||
//! | `versions/cycle-a/` `versions/cycle-b/` | 互相继承(成环) |
|
||||
//! | `versions/1.20.1-nomanifest/` | 只有目录、没有同名清单 |
|
||||
//! | `libraries/` `assets/` | 恒共享层(登记不该碰) |
|
||||
//! | `mods/` `saves/` `config/` | 玩家数据(登记不该碰) |
|
||||
//! | `launcher_profiles.json` | 别的启动器的元数据(连读都不该读,更不该写) |
|
||||
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::collections::BTreeMap;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use unlucky_core::game::adopt::{AdoptRequest, AdoptTarget};
|
||||
use unlucky_core::game::GameLayout;
|
||||
use unlucky_core::platform::layout::LauncherLayout;
|
||||
|
||||
/// 唯一临时目录守卫(`drop` 时递归删除)。
|
||||
pub struct TempRoot {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TempRoot {
|
||||
/// 建一个唯一临时根。
|
||||
pub fn new(tag: &str) -> Self {
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
let nanos = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_nanos());
|
||||
let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"ull-adopt-{tag}-{}-{nanos}-{seq}",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::create_dir_all(&path).expect("临时根应可创建");
|
||||
Self { path }
|
||||
}
|
||||
|
||||
/// 临时根路径。
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
|
||||
/// `.minecraft`(游戏根)。
|
||||
pub fn game_root(&self) -> PathBuf {
|
||||
self.path.join(".minecraft")
|
||||
}
|
||||
|
||||
/// 游戏布局。
|
||||
pub fn game(&self) -> GameLayout {
|
||||
GameLayout::new(self.game_root())
|
||||
}
|
||||
|
||||
/// 启动器数据布局(`<root>/.ULL`)。
|
||||
pub fn launcher(&self) -> LauncherLayout {
|
||||
LauncherLayout::new(self.path.join(".ULL"))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempRoot {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
/// 造一份「别的启动器已经铺好的」`.minecraft`(见模块文档的表)。
|
||||
pub fn foreign_minecraft(root: &Path) {
|
||||
let versions = root.join("versions");
|
||||
// 正常版本:清单 + jar。
|
||||
version_with(&versions, "1.20.1", MANIFEST_VANILLA, true);
|
||||
// 正常版本:带父链(fabric 形态:只有清单、没有自己的 jar)。
|
||||
version_with(&versions, "1.20.1-fabric-0.15.0", MANIFEST_FABRIC, false);
|
||||
// 清单坏掉。
|
||||
let broken = versions.join("1.20.1-broken");
|
||||
std::fs::create_dir_all(&broken).expect("建坏清单目录");
|
||||
std::fs::write(broken.join("1.20.1-broken.json"), b"{ this is not json").expect("写坏清单");
|
||||
// 缺父版本。
|
||||
version_with(&versions, "1.20.1-orphan", MANIFEST_ORPHAN, true);
|
||||
// 成环。
|
||||
version_with(&versions, "cycle-a", MANIFEST_CYCLE_A, true);
|
||||
version_with(&versions, "cycle-b", MANIFEST_CYCLE_B, true);
|
||||
// 只有目录、没有清单。
|
||||
std::fs::create_dir_all(versions.join("1.20.1-nomanifest")).expect("建无清单目录");
|
||||
|
||||
// 恒共享层:库与资源(登记一个字节都不该动)。
|
||||
write_file(
|
||||
&root.join("libraries/com/mojang/brigadier/1.0.18/brigadier-1.0.18.jar"),
|
||||
b"library-bytes",
|
||||
);
|
||||
write_file(&root.join("assets/indexes/5.json"), b"{\"objects\":{}}");
|
||||
write_file(
|
||||
&root.join("assets/objects/ab/abcdef0123456789abcdef0123456789abcdef01"),
|
||||
b"asset-bytes",
|
||||
);
|
||||
// 玩家数据。
|
||||
write_file(&root.join("mods/jei.jar"), b"mod-bytes");
|
||||
write_file(&root.join("saves/World/level.dat"), b"save-bytes");
|
||||
write_file(&root.join("config/example.toml"), b"config = 1\n");
|
||||
// 别的启动器的元数据(登记不该读、更不该写)。
|
||||
write_file(
|
||||
&root.join("launcher_profiles.json"),
|
||||
br#"{"profiles":{"1.20.1":{"name":"1.20.1","lastVersionId":"1.20.1"}}}"#,
|
||||
);
|
||||
}
|
||||
|
||||
/// 一层文件的**全量**快照:相对路径 → (字节数, mtime 纳秒, 内容哈希)。
|
||||
///
|
||||
/// 三个维度都要:只看路径集合抓不住「内容被重写但文件名没变」,只看内容抓不住「mtime 被改写」
|
||||
/// (M216 的「相同内容一个字节都不写」正是用 mtime 判的)。
|
||||
pub fn snapshot(dir: &Path) -> BTreeMap<String, (u64, u128, u64)> {
|
||||
let mut out = BTreeMap::new();
|
||||
walk(dir, dir, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
fn walk(root: &Path, dir: &Path, out: &mut BTreeMap<String, (u64, u128, u64)>) {
|
||||
let entries = std::fs::read_dir(dir).expect("目录应可读");
|
||||
for entry in entries {
|
||||
let entry = entry.expect("目录项应可读");
|
||||
let path = entry.path();
|
||||
let meta = std::fs::symlink_metadata(&path).expect("元数据应可读");
|
||||
if meta.is_dir() {
|
||||
walk(root, &path, out);
|
||||
continue;
|
||||
}
|
||||
let relative = path
|
||||
.strip_prefix(root)
|
||||
.expect("相对路径")
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
let bytes = std::fs::read(&path).expect("文件应可读");
|
||||
let mtime = meta
|
||||
.modified()
|
||||
.ok()
|
||||
.and_then(|time| time.duration_since(UNIX_EPOCH).ok())
|
||||
.map_or(0, |duration| duration.as_nanos());
|
||||
out.insert(relative, (bytes.len() as u64, mtime, hash(&bytes)));
|
||||
}
|
||||
}
|
||||
|
||||
/// 内容哈希(只要稳定、不需要密码学强度)。
|
||||
fn hash(bytes: &[u8]) -> u64 {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
bytes.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
/// 断言两次快照**完全一致**:路径集合、每个文件的字节数、内容哈希、mtime 全都不许变。
|
||||
///
|
||||
/// 抓得住:登记过程中写了/删了/改了任何外部文件(含「内容相同但重写了一遍」——mtime 会变)。
|
||||
/// 抓不住:只读打开(不产生可观测痕迹)以及目录顺序之类查不到的东西。
|
||||
pub fn assert_unchanged(
|
||||
before: &BTreeMap<String, (u64, u128, u64)>,
|
||||
after: &BTreeMap<String, (u64, u128, u64)>,
|
||||
what: &str,
|
||||
) {
|
||||
assert_eq!(
|
||||
before.keys().collect::<Vec<_>>(),
|
||||
after.keys().collect::<Vec<_>>(),
|
||||
"{what}:路径集合变了"
|
||||
);
|
||||
for (path, before) in before {
|
||||
let after = after.get(path).expect("同一路径");
|
||||
assert_eq!(before, after, "{what}:文件被改动 -> {path}");
|
||||
}
|
||||
}
|
||||
|
||||
fn version_with(versions: &Path, id: &str, manifest: &str, jar: bool) {
|
||||
let dir = versions.join(id);
|
||||
std::fs::create_dir_all(&dir).expect("建版本目录");
|
||||
std::fs::write(dir.join(format!("{id}.json")), manifest.as_bytes()).expect("写清单");
|
||||
if jar {
|
||||
std::fs::write(dir.join(format!("{id}.jar")), b"jar-bytes").expect("写 jar");
|
||||
}
|
||||
}
|
||||
|
||||
fn write_file(path: &Path, bytes: &[u8]) {
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).expect("建父目录");
|
||||
}
|
||||
std::fs::write(path, bytes).expect("写文件");
|
||||
}
|
||||
|
||||
/// 原版形态的最小清单(`downloads.client` 有值、无继承)。
|
||||
const MANIFEST_VANILLA: &str = r#"{
|
||||
"id": "1.20.1",
|
||||
"type": "release",
|
||||
"mainClass": "net.minecraft.client.main.Main",
|
||||
"assets": "5",
|
||||
"assetIndex": { "id": "5" },
|
||||
"arguments": {
|
||||
"game": ["--username", "${auth_player_name}", "--version", "${version_name}",
|
||||
"--gameDir", "${game_directory}"],
|
||||
"jvm": ["-Djava.library.path=${natives_directory}", "-cp", "${classpath}"]
|
||||
},
|
||||
"libraries": [],
|
||||
"downloads": { "client": { "size": 9, "url": "http://example.invalid/client.jar" } }
|
||||
}"#;
|
||||
|
||||
/// Fabric 形态:`inheritsFrom` 指 1.20.1(父链闭合)。
|
||||
const MANIFEST_FABRIC: &str = r#"{
|
||||
"id": "1.20.1-fabric-0.15.0",
|
||||
"type": "release",
|
||||
"inheritsFrom": "1.20.1",
|
||||
"mainClass": "net.fabricmc.loader.impl.launch.knot.KnotClient",
|
||||
"libraries": []
|
||||
}"#;
|
||||
|
||||
/// 缺父版本(父 id 在盘上不存在)。
|
||||
const MANIFEST_ORPHAN: &str = r#"{
|
||||
"id": "1.20.1-orphan",
|
||||
"type": "release",
|
||||
"inheritsFrom": "1.20.1-not-on-disk",
|
||||
"mainClass": "net.minecraft.client.main.Main",
|
||||
"libraries": []
|
||||
}"#;
|
||||
|
||||
/// 环的一侧。
|
||||
const MANIFEST_CYCLE_A: &str = r#"{
|
||||
"id": "cycle-a",
|
||||
"type": "release",
|
||||
"inheritsFrom": "cycle-b",
|
||||
"mainClass": "net.minecraft.client.main.Main",
|
||||
"libraries": []
|
||||
}"#;
|
||||
|
||||
/// 环的另一侧。
|
||||
const MANIFEST_CYCLE_B: &str = r#"{
|
||||
"id": "cycle-b",
|
||||
"type": "release",
|
||||
"inheritsFrom": "cycle-a",
|
||||
"mainClass": "net.minecraft.client.main.Main",
|
||||
"libraries": []
|
||||
}"#;
|
||||
|
||||
/// 用 `mklink /J` 建目录联接(junction 不需要管理员权限;建不出来返回 `false`)。
|
||||
///
|
||||
/// 只在 Windows 上有意义:junction 不是 `is_symlink`,是把别人版本目录挂进 `versions/` 最常见的形态,
|
||||
/// 所以越界判据必须能看见它——这条夹具就是用来证明这点的。
|
||||
#[cfg(windows)]
|
||||
pub fn try_junction(target: &Path, link: &Path) -> bool {
|
||||
// `cmd /c mklink /J <link> <target>`:三个参数分开传,别拼成一整条(拼成一串会被 cmd 当语法错)。
|
||||
let output = std::process::Command::new("cmd")
|
||||
.args(["/c", "mklink", "/J"])
|
||||
.arg(link)
|
||||
.arg(target)
|
||||
.output();
|
||||
match output {
|
||||
Ok(output) if output.status.success() && link.is_dir() => true,
|
||||
Ok(output) => {
|
||||
eprintln!(
|
||||
"[junction] mklink /J {} {} 失败({:?}):{}{}",
|
||||
link.display(),
|
||||
target.display(),
|
||||
output.status.code(),
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
false
|
||||
}
|
||||
Err(error) => {
|
||||
eprintln!("[junction] 调不起 cmd:{error}");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 一次登记请求(测试用:固定 `created_at`,名字缺省 = 版本 id)。
|
||||
pub fn request(version_id: &str, target: AdoptTarget) -> AdoptRequest {
|
||||
AdoptRequest {
|
||||
version_id: version_id.to_string(),
|
||||
name: None,
|
||||
target,
|
||||
created_at: Some("2026-11-09T00:00:00.000Z".to_string()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
//! M221 core 侧集成测试入口:从**别人的** `.minecraft` 只读登记版本(adopt)。
|
||||
//!
|
||||
//! 分工:
|
||||
//! - `fixture`:临时真实磁盘目录 + 一份「别的启动器铺好的」`.minecraft` + 全量快照工具;
|
||||
//! - `scan_cases`:`scan` / `inspect` 的判据(正常 / 坏 JSON / 缺父 / 成环 / 缺清单 / 越界符号链接);
|
||||
//! - `plan_cases`:还没登记时的**只读**判据与拒绝理由(dry-run 零写盘 / 缺父 / 不存在 / 非法目标);
|
||||
//! - `register_cases`:`adopt` 的落点与写盘面(缺省独立目录 / shared / isolated / custom /
|
||||
//! 重名 / 重复 / 非空目录 / 数据区联接 / 外部文件哈希与路径集合不变)。
|
||||
//!
|
||||
//! 这些用例**不启动真实 Minecraft**:验的是「登记这一步做了什么、没做什么」,启动链路由
|
||||
//! `tests/game/*` 与 CLI 的 `launch --dry-run` 各自覆盖。
|
||||
|
||||
mod fixture;
|
||||
mod plan_cases;
|
||||
mod register_cases;
|
||||
mod scan_cases;
|
||||
@@ -0,0 +1,112 @@
|
||||
//! `plan` / `inspect` 的**只读**判据与拒绝理由:零写盘、缺父/不存在/非法目标的报错形状。
|
||||
//!
|
||||
//! 与 `register_cases` 的分工:那边验「登记写出了什么」,这边验「还没登记时算出了什么、拒绝得对不对」。
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use unlucky_core::game::adopt::{self, AdoptError, AdoptTarget};
|
||||
use unlucky_core::game::install::instance::Isolation;
|
||||
|
||||
use crate::fixture::{assert_unchanged, foreign_minecraft, request, snapshot, TempRoot};
|
||||
|
||||
/// 缺省档位本身就是「数据区独立目录」,而且**不是** `isolated`(判据的单一真相源)。
|
||||
///
|
||||
/// 抓得住:把 `#[default]` 挪到 `VersionDir`/`Shared`(第一条断言红),或让缺省档映射到
|
||||
/// `Isolated`(第二条断言红)——后者正是「导入别人的版本后第一次启动就在他的 `versions/<id>/`
|
||||
/// 里长 mods/saves」的那个坑。
|
||||
/// 抓不住:CLI 是否真的用 `AdoptTarget::default()`(那条由 cli/adopt_test 的行为断言钉着)。
|
||||
#[test]
|
||||
fn the_default_target_is_an_own_dir_not_the_global_isolated_mode() {
|
||||
let target = AdoptTarget::default();
|
||||
assert_eq!(target, AdoptTarget::InstanceDir);
|
||||
assert_eq!(target.as_str(), "instance_dir");
|
||||
assert_eq!(target.isolation(), Isolation::Custom);
|
||||
assert_ne!(target.isolation(), Isolation::Isolated);
|
||||
}
|
||||
|
||||
/// `--isolation custom --game-dir <相对路径>` ⇒ 明确报错(不猜、不悄悄改成绝对路径)。
|
||||
///
|
||||
/// 抓得住:相对路径被默默接受(`TargetInvalid` 变成成功)。
|
||||
/// 抓不住:Windows 上 `C:foo` 这种「带盘符但非绝对」的形状,只看 `is_absolute`。
|
||||
#[test]
|
||||
fn custom_target_requires_an_absolute_directory() {
|
||||
let root = TempRoot::new("custom-rel");
|
||||
foreign_minecraft(&root.game_root());
|
||||
let error = adopt::adopt(
|
||||
&root.game(),
|
||||
&root.launcher(),
|
||||
&request("1.20.1", AdoptTarget::Custom(PathBuf::from("relative/dir"))),
|
||||
)
|
||||
.expect_err("相对路径应被拒");
|
||||
assert_eq!(error.code(), "adopt_target_invalid");
|
||||
assert!(error.to_string().contains("绝对路径"), "{error}");
|
||||
}
|
||||
|
||||
/// `--dry-run` 的 core 形态(`plan`):一个文件都不写、目录也不建。
|
||||
///
|
||||
/// 抓得住:`plan` 顺手建了运行目录或写了档案(两种断言都会红)。
|
||||
/// 抓不住:CLI 的 `--dry-run` 是否真的只调 `plan`(那条在 cli 侧用例里)。
|
||||
#[test]
|
||||
fn plan_writes_nothing_at_all() {
|
||||
let root = TempRoot::new("plan");
|
||||
foreign_minecraft(&root.game_root());
|
||||
let before = snapshot(root.path());
|
||||
|
||||
let plan = adopt::plan(
|
||||
&root.game(),
|
||||
&root.launcher(),
|
||||
&request("1.20.1", AdoptTarget::InstanceDir),
|
||||
)
|
||||
.expect("计划应成功");
|
||||
let after = snapshot(root.path());
|
||||
assert_unchanged(&before, &after, "plan 之后(含 .ULL)");
|
||||
|
||||
assert!(plan.candidate.adoptable());
|
||||
assert!(!plan.run_dir.exists(), "plan 不该建目录");
|
||||
assert!(!root.path().join(".ULL").exists(), "plan 不该建配置目录");
|
||||
}
|
||||
|
||||
/// 不可登记的版本(缺父)⇒ 一条都不登记,问题清单原样带出。
|
||||
///
|
||||
/// 抓得住:缺父的版本被登记(启动必失败却显示「导入成功」)、问题被折叠成一句空话。
|
||||
/// 抓不住:用户在原来的启动器里修好之后重试(那条由重试路径自然覆盖)。
|
||||
#[test]
|
||||
fn not_adoptable_versions_are_refused_with_their_reasons() {
|
||||
let root = TempRoot::new("refuse");
|
||||
foreign_minecraft(&root.game_root());
|
||||
let error = adopt::adopt(
|
||||
&root.game(),
|
||||
&root.launcher(),
|
||||
&request("1.20.1-orphan", AdoptTarget::InstanceDir),
|
||||
)
|
||||
.expect_err("缺父版本应被拒");
|
||||
assert_eq!(error.code(), "adopt_not_adoptable");
|
||||
let codes: Vec<&str> = error
|
||||
.problems()
|
||||
.iter()
|
||||
.map(|problem| problem.code())
|
||||
.collect();
|
||||
assert_eq!(codes, vec!["missing_parent"]);
|
||||
assert!(
|
||||
!root.path().join(".ULL/config/profiles.json").exists(),
|
||||
"拒绝时不许留档案"
|
||||
);
|
||||
}
|
||||
|
||||
/// 不存在的版本 ⇒ `adopt_version_not_found`(不是「帮你在网上下一个」)。
|
||||
///
|
||||
/// 抓得住:不存在的 id 被当成可登记(档案指向空版本)。
|
||||
/// 抓不住:`versions/` 整个不存在的情形(上一条扫描用例覆盖)。
|
||||
#[test]
|
||||
fn an_unknown_version_is_reported_as_not_found() {
|
||||
let root = TempRoot::new("unknown");
|
||||
foreign_minecraft(&root.game_root());
|
||||
let error = adopt::adopt(
|
||||
&root.game(),
|
||||
&root.launcher(),
|
||||
&request("9.9.9", AdoptTarget::InstanceDir),
|
||||
)
|
||||
.expect_err("不存在的版本应报错");
|
||||
assert!(matches!(error, AdoptError::UnknownVersion { .. }));
|
||||
assert_eq!(error.code(), "adopt_version_not_found");
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
//! `plan` / `adopt` 的落点与写盘面:登记只写自己的配置,外部 `.minecraft` 一个字节都不动。
|
||||
//!
|
||||
//! 每条用例都带「抓得住 / 抓不住」,并且**外部快照断言**是每条的核心:`versions/`
|
||||
//! `libraries/` `assets/` `mods/` `saves/` `config/` `launcher_profiles.json` 的路径集合、
|
||||
//! 字节数、内容哈希、mtime 全都不许变(`fixture::assert_unchanged`)。
|
||||
|
||||
use unlucky_core::game::adopt::{self, AdoptTarget};
|
||||
use unlucky_core::game::install::instance::{read_instance_config, read_profiles, Isolation};
|
||||
use unlucky_core::game::isolation::{derive_game_dir, IsolationMode};
|
||||
|
||||
use crate::fixture::{assert_unchanged, foreign_minecraft, request, snapshot, TempRoot};
|
||||
|
||||
/// 缺省(不给 `--isolation`):运行目录落 ULL 数据区的独立目录,隔离档写 `custom`。
|
||||
///
|
||||
/// 抓得住:缺省沿用全局 `isolated`(那样 `run_dir` 会变成 `versions/1.20.1`)、
|
||||
/// `gameDir` 没落盘、外部文件被写(哈希/mtime 断言)、profiles 没登记。
|
||||
/// 抓不住:真实启动是否真的把 `--gameDir` 用上(core 侧只验派生结果,CLI 侧用 `launch --dry-run` 验)。
|
||||
#[test]
|
||||
fn default_target_lands_in_the_launcher_data_area() {
|
||||
let root = TempRoot::new("default");
|
||||
foreign_minecraft(&root.game_root());
|
||||
let before = snapshot(&root.game_root());
|
||||
|
||||
let outcome = adopt::adopt(
|
||||
&root.game(),
|
||||
&root.launcher(),
|
||||
&request("1.20.1", AdoptTarget::InstanceDir),
|
||||
)
|
||||
.expect("登记应成功");
|
||||
let after = snapshot(&root.game_root());
|
||||
assert_unchanged(&before, &after, "缺省登记之后");
|
||||
|
||||
assert_eq!(outcome.isolation, Isolation::Custom);
|
||||
assert!(outcome.created);
|
||||
assert!(outcome.dir_created, "缺省目录应被新建");
|
||||
let instances_dir = root.path().join(".ULL/data/instances");
|
||||
assert!(
|
||||
outcome.run_dir.starts_with(&instances_dir),
|
||||
"运行目录必须在 ULL 数据区:{}",
|
||||
outcome.run_dir.display()
|
||||
);
|
||||
assert!(outcome.run_dir.is_dir());
|
||||
assert!(
|
||||
!outcome.run_dir.starts_with(root.game_root()),
|
||||
"缺省运行目录不许落在别人的 .minecraft 里"
|
||||
);
|
||||
|
||||
// 落盘的三样东西:profiles.json、实例设置、新建的空运行目录。
|
||||
let profiles = read_profiles(&root.launcher()).expect("读档案");
|
||||
assert_eq!(profiles.profiles.len(), 1);
|
||||
assert_eq!(profiles.profiles[0].name, "1.20.1");
|
||||
assert_eq!(profiles.profiles[0].version_id, "1.20.1");
|
||||
let config = read_instance_config(&root.launcher(), &outcome.instance_id)
|
||||
.expect("读设置")
|
||||
.expect("设置文件存在");
|
||||
assert_eq!(config.isolation, Some(Isolation::Custom));
|
||||
assert_eq!(config.game_dir.as_deref(), Some(outcome.run_dir.as_path()));
|
||||
|
||||
// 启动时 `--gameDir` 真的会取这个目录(D20 覆盖链的权威求值)。
|
||||
let derivation = derive_game_dir(
|
||||
&root.game(),
|
||||
"1.20.1",
|
||||
IsolationMode::Isolated,
|
||||
Some(&config),
|
||||
None,
|
||||
)
|
||||
.expect("派生运行目录");
|
||||
assert_eq!(derivation.game_dir, outcome.run_dir);
|
||||
assert_eq!(derivation.isolation, Isolation::Custom);
|
||||
}
|
||||
|
||||
/// `--isolation shared`:运行目录 = 别人的游戏根,且**人读提示必须说出后果**。
|
||||
///
|
||||
/// 抓得住:shared 档被当成 custom 写 `game_dir`、提示里没提「共用/别人的 .minecraft」、
|
||||
/// 登记过程往游戏根写了东西(哈希断言)。
|
||||
/// 抓不住:用户是否真的读到了这句提示(那属于 UI 验收)。
|
||||
#[test]
|
||||
fn shared_target_points_at_the_game_root_and_says_what_it_means() {
|
||||
let root = TempRoot::new("shared");
|
||||
foreign_minecraft(&root.game_root());
|
||||
let before = snapshot(&root.game_root());
|
||||
|
||||
let outcome = adopt::adopt(
|
||||
&root.game(),
|
||||
&root.launcher(),
|
||||
&request("1.20.1", AdoptTarget::Shared),
|
||||
)
|
||||
.expect("登记应成功");
|
||||
let after = snapshot(&root.game_root());
|
||||
assert_unchanged(&before, &after, "shared 登记之后");
|
||||
|
||||
assert_eq!(outcome.isolation, Isolation::Shared);
|
||||
assert_eq!(outcome.run_dir, root.game_root());
|
||||
assert!(
|
||||
outcome.notes.iter().any(|note| note.contains("共用")),
|
||||
"必须告知「共用别人的 .minecraft」:{:?}",
|
||||
outcome.notes
|
||||
);
|
||||
let config = read_instance_config(&root.launcher(), &outcome.instance_id)
|
||||
.expect("读设置")
|
||||
.expect("设置文件存在");
|
||||
assert_eq!(config.isolation, Some(Isolation::Shared));
|
||||
assert_eq!(config.game_dir, None, "shared 档不该固化成 custom");
|
||||
}
|
||||
|
||||
/// `--isolation isolated`:运行目录 = `versions/<id>`,**登记这一刻仍不往那里写任何东西**。
|
||||
///
|
||||
/// 抓得住:`VersionDir` 被漏做(`isolation` 不是 `Isolated`)、提示里没提「会新增玩家数据」、
|
||||
/// 登记当场就在版本目录里建了 `mods/`(下面的目录内容断言会红)。
|
||||
/// 抓不住:首次启动之后游戏自己往里写(那是启动链路的事,本 mission 不跑真游戏)。
|
||||
#[test]
|
||||
fn version_dir_target_is_explicit_and_writes_nothing_yet() {
|
||||
let root = TempRoot::new("isolated");
|
||||
foreign_minecraft(&root.game_root());
|
||||
let before = snapshot(&root.game_root());
|
||||
|
||||
let outcome = adopt::adopt(
|
||||
&root.game(),
|
||||
&root.launcher(),
|
||||
&request("1.20.1", AdoptTarget::VersionDir),
|
||||
)
|
||||
.expect("登记应成功");
|
||||
let after = snapshot(&root.game_root());
|
||||
assert_unchanged(&before, &after, "isolated 登记之后");
|
||||
|
||||
assert_eq!(outcome.isolation, Isolation::Isolated);
|
||||
assert_eq!(outcome.run_dir, root.game_root().join("versions/1.20.1"));
|
||||
assert!(
|
||||
outcome.notes.iter().any(|note| note.contains("新增")),
|
||||
"必须告知「第一次启动会在这里新增玩家数据」:{:?}",
|
||||
outcome.notes
|
||||
);
|
||||
assert!(!outcome.dir_created, "版本目录已存在,不该新建");
|
||||
let mut entries: Vec<String> = std::fs::read_dir(&outcome.run_dir)
|
||||
.expect("读版本目录")
|
||||
.filter_map(|entry| Some(entry.ok()?.file_name().to_string_lossy().into_owned()))
|
||||
.collect();
|
||||
entries.sort();
|
||||
assert_eq!(
|
||||
entries,
|
||||
vec!["1.20.1.jar".to_string(), "1.20.1.json".to_string()],
|
||||
"版本目录里不该多出任何东西"
|
||||
);
|
||||
}
|
||||
|
||||
/// 展示名已被别的实例占用 ⇒ 显式报错,不改任何档案(不静默复用别的版本)。
|
||||
///
|
||||
/// 抓得住:`register` 的幂等复用路径被当成「导入成功」(那样第二个版本会指向第一个实例的档案)。
|
||||
/// 抓不住:CLI 的 hint 文案(那条在 cli 侧用例里)。
|
||||
#[test]
|
||||
fn a_taken_name_is_an_explicit_error() {
|
||||
let root = TempRoot::new("dupname");
|
||||
foreign_minecraft(&root.game_root());
|
||||
adopt::adopt(
|
||||
&root.game(),
|
||||
&root.launcher(),
|
||||
&request("1.20.1", AdoptTarget::InstanceDir),
|
||||
)
|
||||
.expect("第一个登记成功");
|
||||
let profiles_before =
|
||||
std::fs::read(root.path().join(".ULL/config/profiles.json")).expect("读档案");
|
||||
|
||||
let mut second = request("1.20.1-fabric-0.15.0", AdoptTarget::InstanceDir);
|
||||
second.name = Some("1.20.1".to_string());
|
||||
let error = adopt::adopt(&root.game(), &root.launcher(), &second).expect_err("重名应被拒");
|
||||
assert_eq!(error.code(), "adopt_duplicate_name");
|
||||
let profiles_after =
|
||||
std::fs::read(root.path().join(".ULL/config/profiles.json")).expect("读档案");
|
||||
assert_eq!(profiles_before, profiles_after, "失败不许改档案");
|
||||
}
|
||||
|
||||
/// 同一个版本重复登记 ⇒ 无副作用失败(`adopt_already_registered`),档案逐字节不变。
|
||||
///
|
||||
/// 抓得住:重复登记变成「静默成功」(第二条断言会红),或失败时仍改写了档案。
|
||||
/// 抓不住:并发两次 adopt 的竞态(没有锁;本命令不是并发入口,如实记在这里)。
|
||||
#[test]
|
||||
fn repeating_the_same_adopt_fails_without_side_effects() {
|
||||
let root = TempRoot::new("repeat");
|
||||
foreign_minecraft(&root.game_root());
|
||||
adopt::adopt(
|
||||
&root.game(),
|
||||
&root.launcher(),
|
||||
&request("1.20.1", AdoptTarget::InstanceDir),
|
||||
)
|
||||
.expect("第一次登记成功");
|
||||
let config_dir = root.path().join(".ULL/config");
|
||||
let before = snapshot(&config_dir);
|
||||
|
||||
let error = adopt::adopt(
|
||||
&root.game(),
|
||||
&root.launcher(),
|
||||
&request("1.20.1", AdoptTarget::InstanceDir),
|
||||
)
|
||||
.expect_err("重复登记应报错");
|
||||
assert_eq!(error.code(), "adopt_already_registered");
|
||||
let after = snapshot(&config_dir);
|
||||
assert_unchanged(&before, &after, "重复登记失败之后");
|
||||
}
|
||||
|
||||
/// 缺省运行目录已存在且非空 ⇒ 拒绝(不猜「合并进已有实例」,不覆盖用户内容)。
|
||||
///
|
||||
/// 抓得住:非空目录被复用(内容被游戏写进去只是时间问题)、拒绝时仍写了档案。
|
||||
/// 抓不住:空目录复用那条正向路径(见下一条用例)。
|
||||
#[test]
|
||||
fn a_non_empty_default_run_dir_is_refused() {
|
||||
let root = TempRoot::new("occupied");
|
||||
foreign_minecraft(&root.game_root());
|
||||
let plan = adopt::plan(
|
||||
&root.game(),
|
||||
&root.launcher(),
|
||||
&request("1.20.1", AdoptTarget::InstanceDir),
|
||||
)
|
||||
.expect("先算一次落点");
|
||||
std::fs::create_dir_all(&plan.run_dir).expect("建目录");
|
||||
std::fs::write(plan.run_dir.join("someone-elses-file.txt"), b"keep me").expect("写文件");
|
||||
|
||||
let error = adopt::adopt(
|
||||
&root.game(),
|
||||
&root.launcher(),
|
||||
&request("1.20.1", AdoptTarget::InstanceDir),
|
||||
)
|
||||
.expect_err("非空目录应被拒");
|
||||
assert_eq!(error.code(), "adopt_target_not_empty");
|
||||
assert_eq!(
|
||||
std::fs::read(plan.run_dir.join("someone-elses-file.txt")).expect("读文件"),
|
||||
b"keep me"
|
||||
);
|
||||
assert!(
|
||||
!root.path().join(".ULL/config/profiles.json").exists(),
|
||||
"拒绝时不许留档案"
|
||||
);
|
||||
}
|
||||
|
||||
/// 缺省运行目录存在但**为空** ⇒ 复用(上次失败的残留不该让用户永远重试不了)。
|
||||
///
|
||||
/// 抓得住:空目录也被拒(那就把「先建目录再登记」这条路堵死了)。
|
||||
/// 抓不住:目录里的隐藏文件(`read_dir` 能看见,但平台差异在这里没覆盖)。
|
||||
#[test]
|
||||
fn an_empty_default_run_dir_is_reused() {
|
||||
let root = TempRoot::new("empty-dir");
|
||||
foreign_minecraft(&root.game_root());
|
||||
let plan = adopt::plan(
|
||||
&root.game(),
|
||||
&root.launcher(),
|
||||
&request("1.20.1", AdoptTarget::InstanceDir),
|
||||
)
|
||||
.expect("先算一次落点");
|
||||
std::fs::create_dir_all(&plan.run_dir).expect("建空目录");
|
||||
|
||||
let outcome = adopt::adopt(
|
||||
&root.game(),
|
||||
&root.launcher(),
|
||||
&request("1.20.1", AdoptTarget::InstanceDir),
|
||||
)
|
||||
.expect("空目录可复用");
|
||||
assert!(!outcome.dir_created, "已存在的空目录不算新建");
|
||||
assert_eq!(outcome.run_dir, plan.run_dir);
|
||||
}
|
||||
|
||||
/// 数据区里预先放了指向外部的目录联接 ⇒ 缺省运行目录拒绝沿它写盘。
|
||||
///
|
||||
/// 抓得住:`create_dir_all` 直接沿联接在数据根之外建目录(外部会多出条目,最后一条断言红),
|
||||
/// 或错误码不是 `adopt_target_invalid`。
|
||||
/// 抓不住:数据根**自己**是链接的情形——那是用户的数据目录迁移手法,允许(判据是落点仍在
|
||||
/// 解析后的数据根内);也抓不住检查与建目录之间的 TOCTOU。
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_junction_inside_the_data_area_does_not_get_written_through() {
|
||||
let root = TempRoot::new("datajunction");
|
||||
foreign_minecraft(&root.game_root());
|
||||
let outside = root.path().join("outside-instances");
|
||||
std::fs::create_dir_all(&outside).expect("建外部目录");
|
||||
// 逐段 join:`mklink` 把正斜杠当开关,拼成一串带 `/` 的路径会被判「无效参数」。
|
||||
let data_instances = root.path().join(".ULL").join("data").join("instances");
|
||||
std::fs::create_dir_all(data_instances.parent().expect("父目录")).expect("建 data 目录");
|
||||
if !crate::fixture::try_junction(&outside, &data_instances) {
|
||||
assert_eq!(
|
||||
std::env::var("ULL_ADOPT_TEST_SYMLINK_REQUIRE").as_deref(),
|
||||
Ok("1"),
|
||||
"[symlink-guard] 本机建不出目录联接(mklink /J 失败),这条用例没有跑"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let error = adopt::adopt(
|
||||
&root.game(),
|
||||
&root.launcher(),
|
||||
&request("1.20.1", AdoptTarget::InstanceDir),
|
||||
)
|
||||
.expect_err("数据区里的联接必须被拒");
|
||||
assert_eq!(error.code(), "adopt_target_invalid", "{error}");
|
||||
let entries: Vec<String> = std::fs::read_dir(&outside)
|
||||
.expect("读外部目录")
|
||||
.filter_map(|entry| Some(entry.ok()?.file_name().to_string_lossy().into_owned()))
|
||||
.collect();
|
||||
assert!(
|
||||
entries.is_empty(),
|
||||
"不许沿联接在数据根之外建目录:{entries:?}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
//! `scan` / `inspect` 的判据:正常版本能不能过、坏东西是不是**逐条**说清楚。
|
||||
//!
|
||||
//! 每条断言下面都标了「抓得住 / 抓不住」:抓得住的是变异实现会变红的具体结论,
|
||||
//! 抓不住的是只能靠人读的东西(措辞、是否还有别的静默吞掉路径)。
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use unlucky_core::game::adopt::{self, AdoptCandidate};
|
||||
|
||||
use crate::fixture::{assert_unchanged, foreign_minecraft, snapshot, TempRoot};
|
||||
|
||||
/// 扫一次并按 id 取候选(`inspect` 对不合格候选返回 `Err`,扫描则逐项列出,断言更好写)。
|
||||
fn candidate_of(root: &TempRoot, version_id: &str) -> AdoptCandidate {
|
||||
let scan = adopt::scan(&root.game(), &root.launcher()).expect("扫描应成功");
|
||||
scan.candidates
|
||||
.into_iter()
|
||||
.find(|candidate| candidate.version_id == version_id)
|
||||
.unwrap_or_else(|| panic!("扫描里没有 {version_id}"))
|
||||
}
|
||||
|
||||
/// 正常 / 缺清单 / 坏 JSON / 缺父 / 成环:一次扫描把每个候选的结论都说出来。
|
||||
///
|
||||
/// 抓得住:`scan` 把坏东西当空列表(`candidates` 少项就红)、漏掉父链(`inherits` 长度变)、
|
||||
/// 缺父被当成可登记(`adoptable` 变真)、成环没被检出(`cycle-*` 会变可登记)。
|
||||
/// 抓不住:问题文案的措辞,以及 `versions/` 之外的地方有没有被读写(由下面的哈希断言覆盖)。
|
||||
#[test]
|
||||
fn scan_reports_every_version_with_its_reason() {
|
||||
let root = TempRoot::new("scan");
|
||||
foreign_minecraft(&root.game_root());
|
||||
let before = snapshot(root.path());
|
||||
|
||||
let scan = adopt::scan(&root.game(), &root.launcher()).expect("扫描应成功");
|
||||
let after = snapshot(root.path());
|
||||
assert_unchanged(&before, &after, "scan 之后");
|
||||
|
||||
let ids: Vec<&str> = scan
|
||||
.candidates
|
||||
.iter()
|
||||
.map(|candidate| candidate.version_id.as_str())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
ids,
|
||||
vec![
|
||||
"1.20.1",
|
||||
"1.20.1-broken",
|
||||
"1.20.1-fabric-0.15.0",
|
||||
"1.20.1-nomanifest",
|
||||
"1.20.1-orphan",
|
||||
"cycle-a",
|
||||
"cycle-b",
|
||||
],
|
||||
"扫描必须列出每一个目录(含不可登记的),不能少一行"
|
||||
);
|
||||
|
||||
let by_id = |id: &str| {
|
||||
scan.candidates
|
||||
.iter()
|
||||
.find(|candidate| candidate.version_id == id)
|
||||
.unwrap_or_else(|| panic!("缺候选 {id}"))
|
||||
};
|
||||
|
||||
let vanilla = by_id("1.20.1");
|
||||
assert!(
|
||||
vanilla.adoptable(),
|
||||
"正常版本应可登记:{:?}",
|
||||
vanilla.problems
|
||||
);
|
||||
assert!(vanilla.jar_present);
|
||||
assert_eq!(vanilla.inherits, vec!["1.20.1"]);
|
||||
assert!(!vanilla.is_registered());
|
||||
|
||||
let fabric = by_id("1.20.1-fabric-0.15.0");
|
||||
assert!(fabric.adoptable(), "{:?}", fabric.problems);
|
||||
assert!(!fabric.jar_present, "fabric 版本自己没有 jar");
|
||||
assert_eq!(
|
||||
fabric.inherits,
|
||||
vec!["1.20.1-fabric-0.15.0", "1.20.1"],
|
||||
"父链必须走到底"
|
||||
);
|
||||
|
||||
let codes = |id: &str| -> Vec<&'static str> {
|
||||
by_id(id)
|
||||
.problems
|
||||
.iter()
|
||||
.map(|problem| problem.code())
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(codes("1.20.1-broken"), vec!["manifest_invalid_json"]);
|
||||
assert_eq!(codes("1.20.1-nomanifest"), vec!["manifest_missing"]);
|
||||
assert_eq!(codes("1.20.1-orphan"), vec!["missing_parent"]);
|
||||
assert_eq!(codes("cycle-a"), vec!["circular_inheritance"]);
|
||||
assert_eq!(codes("cycle-b"), vec!["circular_inheritance"]);
|
||||
for id in ["1.20.1-broken", "1.20.1-orphan", "cycle-a"] {
|
||||
assert!(!by_id(id).adoptable(), "{id} 不该被判成可登记");
|
||||
}
|
||||
}
|
||||
|
||||
/// 缺父要说清**缺哪个**、成环要说清**环长什么样**(不是一句「继承有问题」)。
|
||||
///
|
||||
/// 抓得住:`MissingParent` 丢了 `parent` 字段、环链只剩最后一个 id(两个都会被下面的 contains 抓到)。
|
||||
/// 抓不住:错误码是否被 CLI 原样透出(那条在 cli/tests/adopt_test 里)。
|
||||
#[test]
|
||||
fn missing_parent_and_cycle_name_what_is_wrong() {
|
||||
let root = TempRoot::new("chain");
|
||||
foreign_minecraft(&root.game_root());
|
||||
let scan = adopt::scan(&root.game(), &root.launcher()).expect("扫描应成功");
|
||||
let problems = |id: &str| {
|
||||
scan.candidates
|
||||
.iter()
|
||||
.find(|candidate| candidate.version_id == id)
|
||||
.expect("有候选")
|
||||
.problems
|
||||
.clone()
|
||||
};
|
||||
|
||||
let orphan = problems("1.20.1-orphan");
|
||||
let message = orphan.first().expect("一条问题").to_string();
|
||||
assert!(message.contains("1.20.1-not-on-disk"), "{message}");
|
||||
assert!(message.contains("1.20.1-orphan"), "{message}");
|
||||
|
||||
let cycle = problems("cycle-a");
|
||||
let message = cycle.first().expect("一条问题").to_string();
|
||||
assert!(message.contains("cycle-a"), "{message}");
|
||||
assert!(message.contains("cycle-b"), "{message}");
|
||||
}
|
||||
|
||||
/// 坏 JSON 要带**行列号**(用户才知道去改哪一行)。
|
||||
///
|
||||
/// 抓得住:把 serde 的错误文本换成一句「解析失败」(`line` 就没了)。
|
||||
/// 抓不住:具体行列号对不对(不同 serde_json 版本的措辞会变,只断言关键字)。
|
||||
#[test]
|
||||
fn broken_json_message_carries_a_line_number() {
|
||||
let root = TempRoot::new("badjson");
|
||||
foreign_minecraft(&root.game_root());
|
||||
let candidate = candidate_of(&root, "1.20.1-broken");
|
||||
let message = candidate.problems.first().expect("一条问题").to_string();
|
||||
assert!(message.contains("line"), "{message}");
|
||||
assert!(message.contains("1.20.1-broken"), "{message}");
|
||||
}
|
||||
|
||||
/// 清单 `id` 与目录名不一致 ⇒ 拒绝(启动时会按清单 id 找 jar,必然找不到)。
|
||||
///
|
||||
/// 抓得住:去掉 `ManifestIdMismatch` 这条判据后,这个版本会变成「可登记」。
|
||||
/// 抓不住:真实启动是否真的失败(那需要真跑游戏,本 mission 不做)。
|
||||
#[test]
|
||||
fn manifest_id_must_match_the_directory_name() {
|
||||
let root = TempRoot::new("idmismatch");
|
||||
foreign_minecraft(&root.game_root());
|
||||
let dir = root.game_root().join("versions/1.20.1-copy");
|
||||
std::fs::create_dir_all(&dir).expect("建目录");
|
||||
std::fs::write(
|
||||
dir.join("1.20.1-copy.json"),
|
||||
br#"{"id":"1.20.1","type":"release","mainClass":"x","libraries":[]}"#,
|
||||
)
|
||||
.expect("写清单");
|
||||
std::fs::write(dir.join("1.20.1-copy.jar"), b"jar").expect("写 jar");
|
||||
|
||||
let candidate = candidate_of(&root, "1.20.1-copy");
|
||||
let codes: Vec<&str> = candidate
|
||||
.problems
|
||||
.iter()
|
||||
.map(|problem| problem.code())
|
||||
.collect();
|
||||
assert_eq!(codes, vec!["manifest_id_mismatch"]);
|
||||
}
|
||||
|
||||
/// 版本 id 不能当路径用(`../` / 盘符 / 结尾点号)⇒ 一条结构化问题,不去碰盘。
|
||||
///
|
||||
/// 抓得住:删掉 id 校验后 `inspect("../escape")` 会去读游戏根之外的路径(下面断言问题码)。
|
||||
/// 抓不住:Windows 大小写不敏感之类的平台细节(与判据无关)。
|
||||
#[test]
|
||||
fn version_ids_that_cannot_be_paths_are_rejected() {
|
||||
let root = TempRoot::new("badid");
|
||||
foreign_minecraft(&root.game_root());
|
||||
let escape = root.path().join("outside");
|
||||
std::fs::create_dir_all(escape.join("1.20.1")).expect("建外部同名目录");
|
||||
std::fs::write(
|
||||
escape.join("1.20.1/1.20.1.json"),
|
||||
br#"{"id":"1.20.1","type":"release","mainClass":"x","libraries":[]}"#,
|
||||
)
|
||||
.expect("写外部清单");
|
||||
|
||||
// `versions/../../outside/1.20.1` 这种形状:目录真的存在(能解析出去),但 id 里含分隔符。
|
||||
let error = adopt::inspect(&root.game(), &root.launcher(), "../../outside/1.20.1")
|
||||
.expect_err("非法 id 应报错,而不是去读游戏根之外的目录");
|
||||
assert_eq!(error.code(), "adopt_not_adoptable");
|
||||
let codes: Vec<&str> = error
|
||||
.problems()
|
||||
.iter()
|
||||
.map(|problem| problem.code())
|
||||
.collect();
|
||||
assert_eq!(codes, vec!["version_id_invalid"], "{error}");
|
||||
|
||||
for bad in ["1.20.1.", "1.20.1 ", "C:", "a/b"] {
|
||||
let error =
|
||||
adopt::inspect(&root.game(), &root.launcher(), bad).expect_err("非法 id 应报错");
|
||||
assert!(
|
||||
error
|
||||
.problems()
|
||||
.iter()
|
||||
.any(|problem| problem.code() == "version_id_invalid"),
|
||||
"{bad:?} 应被当成非法 id:{error}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 版本目录是指向游戏根**之外**的符号链接 ⇒ 拒绝不跟随(也不读它)。
|
||||
///
|
||||
/// 抓得住:`ensure_inside` 不比较解析后的真实路径(那样 `1.20.1-link` 会变成「可登记」)。
|
||||
/// 抓不住 / 已知局限:
|
||||
/// - 本机不允许建符号链接(Windows 未开开发者模式、或非管理员)时这条会打印 `[symlink-guard]`
|
||||
/// 并**跳过**——显式记录而不是静静通过;设 `ULL_ADOPT_TEST_SYMLINK_REQUIRE=1` 可让它必跑(建不出来即红);
|
||||
/// - 目录联接(junction)由下面单独那条用例覆盖(不需要管理员权限,是更常见的形态)。
|
||||
#[test]
|
||||
fn a_symlinked_version_pointing_outside_the_game_root_is_rejected() {
|
||||
let root = TempRoot::new("symlink");
|
||||
foreign_minecraft(&root.game_root());
|
||||
let outside = root.path().join("other-launcher");
|
||||
std::fs::create_dir_all(outside.join("1.20.1")).expect("建外部版本目录");
|
||||
std::fs::write(
|
||||
outside.join("1.20.1/1.20.1.json"),
|
||||
br#"{"id":"1.20.1","type":"release","mainClass":"x","libraries":[]}"#,
|
||||
)
|
||||
.expect("写外部清单");
|
||||
let link = root.game_root().join("versions/1.20.1-link");
|
||||
if !try_symlink_dir(&outside.join("1.20.1"), &link) {
|
||||
// 显式记录 + 环境变量可强制:不允许「什么都没跑还说绿」。
|
||||
assert_eq!(
|
||||
std::env::var("ULL_ADOPT_TEST_SYMLINK_REQUIRE").as_deref(),
|
||||
Ok("1"),
|
||||
"[symlink-guard] 本机不允许建符号链接,这条用例没有跑:\
|
||||
要强制它必跑设 ULL_ADOPT_TEST_SYMLINK_REQUIRE=1(建不出来即红)"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let candidate = candidate_of(&root, "1.20.1-link");
|
||||
let codes: Vec<&str> = candidate
|
||||
.problems
|
||||
.iter()
|
||||
.map(|problem| problem.code())
|
||||
.collect();
|
||||
assert!(
|
||||
codes.contains(&"outside_game_root"),
|
||||
"越界链接必须被点名:{codes:?}"
|
||||
);
|
||||
assert!(!candidate.adoptable(), "越界链接的版本不许登记");
|
||||
}
|
||||
|
||||
/// 游戏根内的符号链接(指向同一棵树里的真实版本目录)**不**拒绝:那是合法的省盘做法。
|
||||
///
|
||||
/// 抓得住:`check_symlink` 一刀切拒绝所有符号链接(这条会红)。
|
||||
/// 抓不住:本机建不出链接时同上跳过(打印 `[symlink-guard]`)。
|
||||
#[test]
|
||||
fn a_symlink_inside_the_game_root_is_allowed() {
|
||||
let root = TempRoot::new("symlink-in");
|
||||
foreign_minecraft(&root.game_root());
|
||||
// 真实版本目录放在根内的 `hidden/` 下(清单 id 与目录名一致),再在 `versions/` 里挂一条链接。
|
||||
let real = root.game_root().join("hidden/1.20.1-thin");
|
||||
std::fs::create_dir_all(&real).expect("建真实版本目录");
|
||||
std::fs::write(
|
||||
real.join("1.20.1-thin.json"),
|
||||
br#"{"id":"1.20.1-thin","type":"release","mainClass":"x","libraries":[]}"#,
|
||||
)
|
||||
.expect("写清单");
|
||||
let link = root.game_root().join("versions/1.20.1-thin");
|
||||
if !try_symlink_dir(&real, &link) {
|
||||
assert_eq!(
|
||||
std::env::var("ULL_ADOPT_TEST_SYMLINK_REQUIRE").as_deref(),
|
||||
Ok("1"),
|
||||
"[symlink-guard] 本机不允许建符号链接,这条用例没有跑"
|
||||
);
|
||||
return;
|
||||
}
|
||||
let candidate = candidate_of(&root, "1.20.1-thin");
|
||||
assert!(
|
||||
candidate.adoptable(),
|
||||
"根内链接不该被拒:{:?}",
|
||||
candidate.problems
|
||||
);
|
||||
}
|
||||
|
||||
/// 建目录符号链接(`true` = 建成;`false` = 本机没权限/不支持)。
|
||||
fn try_symlink_dir(target: &Path, link: &Path) -> bool {
|
||||
#[cfg(unix)]
|
||||
let created = std::os::unix::fs::symlink(target, link).is_ok();
|
||||
#[cfg(windows)]
|
||||
let created = std::os::windows::fs::symlink_dir(target, link).is_ok();
|
||||
created
|
||||
}
|
||||
|
||||
/// `versions/` 不存在 = 空结果(新数据根不是错误),但**不存在的游戏根不会被建出来**。
|
||||
///
|
||||
/// 抓得住:`scan` 顺手 `create_dir_all(versions)`(下面的断言会红),或把「不存在」当错误。
|
||||
/// 抓不住:读目录失败(ENOTDIR/EACCES)那条分支——真造一个不可读目录在 Windows 上不可靠,
|
||||
/// 那一条由代码审读把关。
|
||||
#[test]
|
||||
fn a_missing_versions_dir_is_empty_not_an_error() {
|
||||
let root = TempRoot::new("noversions");
|
||||
let scan = adopt::scan(&root.game(), &root.launcher()).expect("应成功");
|
||||
assert!(scan.candidates.is_empty());
|
||||
assert!(
|
||||
!root.game_root().exists(),
|
||||
"扫描不该顺手建游戏根目录:{}",
|
||||
root.game_root().display()
|
||||
);
|
||||
}
|
||||
|
||||
/// Windows 目录联接(junction)指向根外 ⇒ **同样**拒绝,而且不去读那个目录。
|
||||
///
|
||||
/// 为什么要单列:junction 不是 `is_symlink`,只看链接类型的实现会放行它——而 junction
|
||||
/// **不需要管理员权限**就能建,是把别人版本目录挂进 `versions/` 最常见的形态。
|
||||
///
|
||||
/// 抓得住:
|
||||
/// - 判据退回 `is_symlink`(除 Windows junction 外全都看不到,此时候选会变成「可登记」,第一条断言红);
|
||||
/// - 判据排到**解析清单之后**:根外那份清单是合法 JSON 且 id 与目录名一致,一旦走到解析,
|
||||
/// `manifest_id` 就会被填上(第二条断言红)——所以它至少能证明「没解析过根外清单」;
|
||||
/// - 库里没有 `mklink` 时打印 `[symlink-guard]` 并跳过(设 `ULL_ADOPT_TEST_SYMLINK_REQUIRE=1` 必跑)。
|
||||
///
|
||||
/// 抓不住(证据边界,别把它读大):**只 stat/只 open 不解析**的读取这里看不出来
|
||||
/// (`manifest_id` 为 `None` 只说明没解析过,不说明没碰过文件);「边界检查排在
|
||||
/// `read_manifest` 之前」这条由 `inspect.rs::check` 的代码顺序保证,靠人读。
|
||||
/// 也抓不住检查与读取之间的 TOCTOU(本模块不是并发/对抗入口)。
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_junction_pointing_outside_is_rejected_without_reading_it() {
|
||||
let root = TempRoot::new("junction");
|
||||
foreign_minecraft(&root.game_root());
|
||||
// 逐段 join:`cmd` / `mklink` 会把正斜杠当开关,拼成一串带 `/` 的路径会被判「无效参数」。
|
||||
let outside = root.path().join("other-launcher").join("1.20.1-junction");
|
||||
std::fs::create_dir_all(&outside).expect("建外部版本目录");
|
||||
std::fs::write(
|
||||
outside.join("1.20.1-junction.json"),
|
||||
br#"{"id":"1.20.1-junction","type":"release","mainClass":"x","libraries":[]}"#,
|
||||
)
|
||||
.expect("写外部清单");
|
||||
let link = root.game_root().join("versions").join("1.20.1-junction");
|
||||
if !crate::fixture::try_junction(&outside, &link) {
|
||||
assert_eq!(
|
||||
std::env::var("ULL_ADOPT_TEST_SYMLINK_REQUIRE").as_deref(),
|
||||
Ok("1"),
|
||||
"[symlink-guard] 本机建不出目录联接(mklink /J 失败),这条用例没有跑"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let candidate = candidate_of(&root, "1.20.1-junction");
|
||||
let codes: Vec<&str> = candidate
|
||||
.problems
|
||||
.iter()
|
||||
.map(|problem| problem.code())
|
||||
.collect();
|
||||
assert!(
|
||||
codes.contains(&"outside_game_root"),
|
||||
"联接越界必须被点名:{codes:?} / {:?}",
|
||||
candidate.problems
|
||||
);
|
||||
assert!(!candidate.adoptable(), "越界联接的版本不许登记");
|
||||
assert!(
|
||||
candidate.manifest_id.is_none() && candidate.inherits.is_empty(),
|
||||
"拒绝之后不许再读根外那份清单:{:?}",
|
||||
candidate.manifest_id
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user