Files
Unlucky-Launcher/crates/cli/tests/adopt_test/cli_surface.rs
T
AskaEth 347a3cc90d fix(game): 复审 r2 三项——Win32 尾点/尾空格别名 + 写面与游戏树重叠 + 更高祖先断链
r1 五项里 R4/R5 与 slug/大小写等直接案例已由 r2 复审独立通过;这三条是它补证出的**剩余边界**,
只做限定修复,不推翻重写:

r2.1(未存在认领路径的 Win32 尾点/尾空格别名):比较键新增 `fspaths::comparison_real()`——
已存在前缀用 `canonicalize`,**尚不存在的尾段按平台语义归一**:Windows 普通路径折叠尾 `.`/空格
(`Foo.` 与 `Foo ` 都是 `Foo`,Win32 建目录时就这么做),**verbatim 路径(`\?\…`)不折叠**
(那是另一个物理目录,合法)。原先 `dir_key` 只统一分隔符与大小写,于是一个尚未创建的
`custom` 认领 `Foo.` 与缺省派生 `Foo` 键不相等却被判定「不撞」,两个实例共用一个运行目录。

r2.2(`data`/`.ULL` 整体映射到受保护游戏树时仍静默外写):新增
`fspaths::ensure_surfaces_clear_of_game_tree()`——默认写盘面(`.ULL`、`config/`、
`config/instances/`、`profiles.json`、`data/`,以及缺省档的运行目录)**解析后不得落进游戏根**;
`plan`(dry-run 也报)与 `adopt`(写盘前)各核一次,重叠即 `adopt_write_surface_in_game_tree`
具名拒绝并提示把数据目录挪到游戏树之外。整体迁移到游戏树**之外**照旧允许(判据是落点不是链接)。
配置写面判据同时收窄职责:`ensure_config_write_surface` 只管「在 `.ULL` 内」,
不再带「`.ULL` 在游戏根里」的豁免特例——重叠由上面那条统一负责。

r2.3(游戏根更高祖先断链仍当空列表):`scan` 的 `NotFound` 分支改为沿祖先找**最近的已存在入口**,
它能 `lstat` 到但 `canonicalize` 不出来(断链的符号链接/目录联接、目标被搬走)⇒
`adopt_versions_unreadable`;一路到盘根都不存在才是「真正的新数据根」,空结果仍允许。
原先只查 `versions` 与游戏根两层,迁移联接在更高层断开时会误报空库。

新错误码:`adopt_write_surface_in_game_tree`(CLI hint 与 help 拒绝清单同步)。

验证(持久日志在 `target/m221-r2/`,git 忽略、不入库;上一轮 `target/m221-r1/` 证据未覆盖):
- `cargo fmt --all --check` 0;`cargo check -p unlucky-core -p unlucky-cli --all-targets` 0;
- `cargo test -p unlucky-core --test adopt` **43 passed / 0 failed**(另跑一次
  `ULL_ADOPT_TEST_SYMLINK_REQUIRE=1` 同样 43 passed);
- `cargo test -p unlucky-cli --test adopt_test` **13 passed / 0 failed**;
- `cargo clippy -p unlucky-core -p unlucky-cli --all-targets -- -D warnings` 0;
- 额外:`cargo test -p unlucky-core --lib` **778 passed**、`cargo test -p unlucky-cli` 全部目标通过;
- 三次**实现-only 变异**(不折叠 Win32 尾点尾空格 / 不核游戏树重叠 / NotFound 直接当空)
  全部以**断言红**收场(1 / 4 / 2 条失败,非编译错误、非环境错误),每次还原后与基线逐文件一致,
  收尾再跑 core+cli 双绿。

界限:只覆盖 core+cli 的定向目标(不等于 workspace 全量);没有启动真实 Minecraft;GUI 未接;
判据是检查那一刻的快照(TOCTOU 看不到);Win32 8.3 短名与非 junction 重解析点未覆盖。
2026-11-09 23:56:02 +08:00

157 lines
5.9 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 命令面:help 文案、用法错误、错误码——不碰数据或者只碰「拒绝」那条路。
//!
//! 从 `tests/adopt_test.rs` 拆出来只为守 400 行硬线;搬动是纯搬,断言未变。
use crate::support::{parse_json, run_cli, TempDir};
use crate::fixture::foreign_data_root;
/// 运行目录选项的用法错误:一律退出码 1 + `code=usage`(不是内部错误)。
///
/// 抓得住:`--isolation custom` 少 `--game-dir` 被默默当成缺省、`shared` 同时给 `--game-dir`
/// 被静默忽略、未知词被当缺省。
/// 抓不住:提示文案的措辞(只断言 code 与关键字)。
#[test]
fn isolation_option_misuse_is_a_usage_error() {
let dir = TempDir::new("adopt-usage");
foreign_data_root(dir.path());
let cases: Vec<Vec<&str>> = vec![
vec!["--isolation", "custom"],
vec!["--isolation", "shared", "--game-dir", "C:/tmp/x"],
vec!["--isolation", "nope"],
vec!["--game-dir", "relative/dir"],
];
for extra in cases {
let mut args = vec!["instances", "adopt", "1.20.1", "--json", "--data-dir"];
let dir_arg = dir.arg();
args.push(&dir_arg);
args.extend(extra.iter().copied());
let (code, stdout, stderr) = run_cli(&args);
assert_eq!(code, 1, "args={args:?}\nstdout={stdout}\nstderr={stderr}");
let value = parse_json(&stdout);
assert_eq!(
value["error"]["code"], "usage",
"args={args:?} 应是用法错误:{stdout}"
);
}
}
/// 不存在的版本 ⇒ `adopt_version_not_found`(不联网、不偷偷装一个)。
///
/// 抓得住:不存在的 id 被登记成功。
/// 抓不住:`versions/` 整个不存在时 `scan` 的空结果(core 侧用例覆盖)。
#[test]
fn unknown_version_reports_not_found() {
let dir = TempDir::new("adopt-unknown");
foreign_data_root(dir.path());
let (code, stdout, _) = run_cli(&[
"instances",
"adopt",
"9.9.9",
"--json",
"--data-dir",
&dir.arg(),
]);
assert_eq!(code, 1, "{stdout}");
assert_eq!(
parse_json(&stdout)["error"]["code"],
"adopt_version_not_found"
);
}
/// help 里必须有这两条命令(新命令不留「有实现没文档」的状态),且旧命令仍在。
///
/// 抓得住:help 漏列 `instances scan` / `instances adopt`(子串断言),或把旧的
/// `instances launch-args` / `pack import` 弄丢。
/// 抓不住:帮助文案与真实行为是否一致(那要靠上面的行为用例 + 人读)。
#[test]
fn help_lists_the_new_subcommands_next_to_the_old_ones() {
let general = unlucky_cli::cli::help::general();
for needle in [
"instances scan",
"instances adopt",
"instances list",
"install <version>",
] {
assert!(general.contains(needle), "总帮助缺 `{needle}`:\n{general}");
}
let topic = unlucky_cli::cli::help::topic("instances").expect("help instances 存在");
for needle in [
"instances scan",
"instances adopt",
"缺省不沿用全局 isolated",
"一个字节都不写",
] {
assert!(topic.contains(needle), "help instances 缺 `{needle}`");
}
// 旧的 `per_version` 字面量只在 core 的 `Isolation::parse` 里被兼容,CLI 词表不接受它。
let bogus = std::env::temp_dir().join("ull-adopt-help-nonexistent");
let bogus = bogus.display().to_string();
let args = [
"instances",
"adopt",
"1.20.1",
"--isolation",
"per_version",
"--json",
"--data-dir",
bogus.as_str(),
];
let (code, stdout, _) = run_cli(&args);
assert_eq!(code, 1, "`per_version` 不是 CLI 词表:{stdout}");
}
/// **更高祖先断链**(r2 R2.3 的 CLI 面):`--data-dir` 指到迁移联接下面的 nested 目录,
/// 联接目标被搬走后 `instances scan` 必须非零 + 结构化错误,不能 `ok:true / total:0`。
///
/// 抓得住:只判 `versions`/游戏根两层(更高层断链会漏,这里会看到 exit0 与 total 0)。
///
/// 抓不住:真正的权限不足(EACCES)那一支。
#[cfg(windows)]
#[test]
fn a_dangling_ancestor_is_a_structured_scan_error() {
let dir = TempDir::new("scan-ancestor-dangling");
let outer = TempDir::new("scan-ancestor-target");
let real = outer.path();
let game = real.join("nested").join(".minecraft");
std::fs::create_dir_all(game.join("versions").join("1.20.1")).expect("建完整版本树");
std::fs::write(
game.join("versions/1.20.1/1.20.1.json"),
br#"{"id":"1.20.1","type":"release","mainClass":"x","libraries":[]}"#,
)
.expect("写清单");
let link = dir.path().join("game-parent-link");
let ok = std::process::Command::new("cmd")
.args(["/c", "mklink", "/J"])
.arg(&link)
.arg(real)
.output()
.is_ok_and(|out| out.status.success());
if !ok {
eprintln!("[link-guard] 建不出目录联接,跳过祖先断链 CLI 用例");
return;
}
let data_arg = link.join("nested").display().to_string();
// 断开之前:能扫到 1 个候选。
let (code, stdout, stderr) = run_cli(&["instances", "scan", "--json", "--data-dir", &data_arg]);
assert_eq!(code, 0, "stdout={stdout} stderr={stderr}");
assert_eq!(parse_json(&stdout)["data"]["counts"]["total"], 1);
// 断开:联接目标改名(入口还在,versions 与游戏根都 NotFound)。
let moved = dir.path().join("moved-target");
std::fs::rename(real, &moved).expect("移走联接目标");
let (code, stdout, stderr) = run_cli(&["instances", "scan", "--json", "--data-dir", &data_arg]);
assert_eq!(
code, 1,
"祖先断链必须非零退出:stdout={stdout} stderr={stderr}"
);
let value = parse_json(&stdout);
assert_eq!(value["ok"], false, "{stdout}");
assert_eq!(
value["error"]["code"], "adopt_versions_unreadable",
"{stdout}"
);
}