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
@@ -17,6 +17,10 @@ pub const fn general() -> &'static str {
|
||||
instances launch-args <instance> [--jvm T] [--game T] [--memory MB] [--java P]
|
||||
[--backend default|opengl|vulkan] [--clear]
|
||||
读/写实例级启动参数(不带选项 = 只读;--clear = 全部回跟随全局)
|
||||
instances scan 列出 versions/ 里已铺好的版本(含别的启动器装的):能不能登记 + 原因
|
||||
instances adopt <version-id> [--name N] [--isolation shared|isolated|custom] [--game-dir DIR]
|
||||
[--dry-run] 把已铺好的版本登记成实例(只读外部、不搬文件;缺省运行目录
|
||||
落 ULL 数据区的独立目录;--dry-run 只检查不写盘)
|
||||
install <version> [--loader X] [--loader-version V] [--name N] [--dry-run]
|
||||
下载并安装版本本体(--loader fabric|quilt|neoforge|forge
|
||||
时再叠一层加载器)→ 登记实例;--dry-run 只出计划
|
||||
@@ -91,7 +95,38 @@ pub fn topic(name: &str) -> Option<&'static str> {
|
||||
每一项都是「实例 → 全局 → 默认」的独立回落,只填一项不会顶掉别的项。
|
||||
值以 `--` 开头时(多数游戏参数都是)写成 `--game=--fullscreen`:单独一个 `--fullscreen`
|
||||
会被当成下一个选项(缺少取值),这是全项目 CLI 的既有解析口径。
|
||||
--json 输出 {\"data\":{\"launch\":{…实例层…},\"effective\":{…回落后的生效值…}, …}}",
|
||||
--json 输出 {\"data\":{\"launch\":{…实例层…},\"effective\":{…回落后的生效值…}, …}}
|
||||
|
||||
%prog% instances scan
|
||||
|
||||
列出当前游戏根 versions/ 里已经铺好的版本(可能是别的启动器装的),逐项给结论:
|
||||
✓ 可登记 / 已登记(附父链);✗ 不可登记 + 每条原因(带稳定 code:manifest_missing /
|
||||
manifest_invalid_json / missing_parent / circular_inheritance / outside_game_root …)。
|
||||
只读:不写文件、不改 mtime。versions/ 不存在 = 空结果;versions/ 读不了 = 报错(不当空列表)。
|
||||
--json 输出 {\"data\":{\"game_root\":…,\"versions_dir\":…,\"counts\":{…},\"candidates\":[…]}}
|
||||
每个 candidate 带 {\"version_id\",\"jar_present\",\"inherits\",\"registered\",\"adoptable\",\"problems\"}。
|
||||
|
||||
%prog% instances adopt <version-id> [--name N] [--isolation shared|isolated|custom]
|
||||
[--game-dir DIR] [--dry-run]
|
||||
|
||||
把 versions/<id>/ 登记成实例:只读外部、只写自己的配置——不搬文件、不补清单、不改任何
|
||||
外部文件的 mtime(versions/ libraries/ assets/ 一个字节都不写)。不读任何启动器的账户凭据。
|
||||
运行目录(--gameDir)三档,缺省不沿用全局 isolated(那会把 mods/saves/config 造进
|
||||
别人的 versions/<id>/,那是别的启动器的版本目录):
|
||||
不给 --isolation → <数据根>/.ULL/data/instances/<实例目录名>(新建空目录,隔离档写 custom)
|
||||
--isolation shared → 别人的游戏根(共用其 mods/saves/config;明确选择后才生效)
|
||||
--isolation isolated → versions/<version-id>/(第一次启动会在这里新增玩家数据目录)
|
||||
--isolation custom --game-dir DIR → 指定目录(DIR 必须是绝对路径;不新建、不改动其中内容)
|
||||
拒绝(退出码 1,原因逐条进 error.detail.problems):
|
||||
· 清单坏了 / 读不出来 / 缺 id / id 与目录名不一致
|
||||
· 缺父版本 / 父链成环(说清缺哪个、环是什么)
|
||||
· 条目解析到游戏根之外(符号链接/目录联接/祖先链接)
|
||||
· 展示名已被别的实例占用;这个版本已经同名登记过(重复执行 = 无副作用失败)
|
||||
· 缺省运行目录已存在且非空(空目录可复用;不猜「合并进已有实例」)
|
||||
--dry-run:只检查并打印将要用的隔离档/运行目录,不写任何文件、不建目录。
|
||||
--json 输出 {\"data\":{\"dry_run\":…,\"instance\":{\"id\",\"name\",\"isolation\",\"run_dir\",
|
||||
\"run_dir_source\",\"config_path\",\"created\"},\"notes\":[…]}}。
|
||||
",
|
||||
),
|
||||
"pack" => Some(
|
||||
"\
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use unlucky_core::game::AdoptTarget;
|
||||
|
||||
/// 全局选项(所有命令共享)。
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Globals {
|
||||
@@ -26,6 +28,10 @@ pub enum Command {
|
||||
Help(Option<String>),
|
||||
/// `instances list`。
|
||||
InstancesList,
|
||||
/// `instances scan`:列出当前游戏根里可登记 / 不可登记的外部版本(只读,M221)。
|
||||
InstancesScan,
|
||||
/// `instances adopt <version-id> [--name N] [--isolation ...] [--game-dir DIR] [--dry-run]`。
|
||||
InstancesAdopt(InstancesAdoptArgs),
|
||||
/// `instances launch-args <instance> [--jvm …] [--game …] [--memory …] [--java …] [--backend …] [--clear]`。
|
||||
InstancesLaunchArgs(InstanceLaunchArgs),
|
||||
/// `install <version> [--loader X] [--name N]`。
|
||||
@@ -203,6 +209,20 @@ pub struct DiagArgs {
|
||||
pub tail: usize,
|
||||
}
|
||||
|
||||
/// `instances adopt` 的参数(M221:把盘上已有的版本登记成实例,只读外部、只写自己的配置)。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct InstancesAdoptArgs {
|
||||
/// 要接入的版本 id(= `versions/<id>/`)。
|
||||
pub version_id: String,
|
||||
/// 展示名(缺省 = 版本 id)。
|
||||
pub name: Option<String>,
|
||||
/// 运行目录选择:缺省 [`AdoptTarget::InstanceDir`](ULL 数据区新目录),
|
||||
/// `shared` / `isolated` / `custom` 都必须显式给。
|
||||
pub target: AdoptTarget,
|
||||
/// 只检查、不写任何文件(`--dry-run`)。
|
||||
pub dry_run: bool,
|
||||
}
|
||||
|
||||
/// `instances launch-args` 的参数(M157:实例级启动参数)。
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct InstanceLaunchArgs {
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
//! `instances` 的两个子命令解析(`list` / `launch-args`)。
|
||||
//! `instances` 的子命令解析(`list` / `launch-args` / `scan` / `adopt`)。
|
||||
//!
|
||||
//! 从 `parse.rs` 拆出来只为守 400 行硬线(M157 的 `launch-args` 让那边到 415 行);
|
||||
//! 纯搬移,语义未变。
|
||||
//! 纯搬移,语义未变。M221 在这里加了 `scan` 与 `adopt` 两个只读/登记入口。
|
||||
|
||||
use super::super::model::InstanceLaunchArgs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use unlucky_core::game::AdoptTarget;
|
||||
|
||||
use super::super::model::{InstanceLaunchArgs, InstancesAdoptArgs};
|
||||
use super::*;
|
||||
|
||||
pub(super) fn parse_instances(tail: &[String]) -> Result<Command, CliError> {
|
||||
@@ -12,10 +16,16 @@ pub(super) fn parse_instances(tail: &[String]) -> Result<Command, CliError> {
|
||||
Some("launch-args") => {
|
||||
return parse_instances_launch_args(tail.get(1..).unwrap_or_default())
|
||||
}
|
||||
Some("scan") => {
|
||||
let parsed = parse_flags(tail.get(1..).unwrap_or_default(), &[], &[])?;
|
||||
ensure_no_positionals(&parsed, "instances scan")?;
|
||||
return Ok(Command::InstancesScan);
|
||||
}
|
||||
Some("adopt") => return parse_instances_adopt(tail.get(1..).unwrap_or_default()),
|
||||
Some(other) => {
|
||||
return Err(CliError::usage(format!(
|
||||
"instances 的子命令只有 list / launch-args,收到 `{other}`"
|
||||
)));
|
||||
"instances 的子命令只有 list / launch-args / scan / adopt,收到 `{other}`"
|
||||
)))
|
||||
}
|
||||
};
|
||||
let parsed = parse_flags(args, &[], &[])?;
|
||||
@@ -43,3 +53,62 @@ fn parse_instances_launch_args(tail: &[String]) -> Result<Command, CliError> {
|
||||
clear: parsed.has("clear"),
|
||||
}))
|
||||
}
|
||||
|
||||
/// `instances adopt <version-id> [--name N] [--isolation shared|isolated|custom] [--game-dir DIR] [--dry-run]`。
|
||||
///
|
||||
/// 运行目录的词表只在这里翻译一次([`AdoptTarget::parse`] 是唯一判据):
|
||||
/// - 什么都不给 ⇒ [`AdoptTarget::InstanceDir`](ULL 数据区新目录,**不沿用全局 `isolated`**);
|
||||
/// - `--isolation custom` 必须配 `--game-dir`;
|
||||
/// - `--isolation shared|isolated` 不许再配 `--game-dir`(那两个档的运行目录是派生的)。
|
||||
fn parse_instances_adopt(tail: &[String]) -> Result<Command, CliError> {
|
||||
let parsed = parse_flags(tail, &["name", "isolation", "game-dir"], &["dry-run"])?;
|
||||
let version_id = require_single_positional(&parsed, "instances adopt <version-id>")?;
|
||||
let isolation = parsed.value("isolation");
|
||||
let game_dir = match parsed.value("game-dir") {
|
||||
Some(raw) => {
|
||||
let dir = PathBuf::from(&raw);
|
||||
// 用法错误在解析期就报(和 `--data-dir` 同一口径),别把「参数写错」拖成命令期失败。
|
||||
if !dir.is_absolute() {
|
||||
return Err(CliError::usage(format!(
|
||||
"--game-dir 需要绝对路径,收到 `{raw}`"
|
||||
)));
|
||||
}
|
||||
Some(dir)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let target = match isolation.as_deref() {
|
||||
None => match game_dir {
|
||||
// `--game-dir` 单独给 = 就是 custom(少写一个选项,不制造第二种说法)。
|
||||
Some(dir) => AdoptTarget::Custom(dir),
|
||||
// 缺省**只能**来自 core 的 `AdoptTarget::default()`:这里再写一遍 `InstanceDir`
|
||||
// 就等于有了第二处真相源,改缺省时会漏一处。
|
||||
None => AdoptTarget::default(),
|
||||
},
|
||||
Some("custom") => {
|
||||
let dir = game_dir.ok_or_else(|| {
|
||||
CliError::usage("--isolation custom 需要配 --game-dir <dir>(绝对路径)")
|
||||
})?;
|
||||
AdoptTarget::Custom(dir)
|
||||
}
|
||||
Some(other) => {
|
||||
if game_dir.is_some() {
|
||||
return Err(CliError::usage(
|
||||
"--game-dir 只配 --isolation custom(shared / isolated 的运行目录是派生的)",
|
||||
));
|
||||
}
|
||||
AdoptTarget::parse(other, None).ok_or_else(|| {
|
||||
CliError::usage(format!(
|
||||
"--isolation 只有 shared|isolated|custom,收到 `{other}`"
|
||||
))
|
||||
.with_hint("不给 --isolation = 落 ULL 数据区的独立运行目录(推荐)")
|
||||
})?
|
||||
}
|
||||
};
|
||||
Ok(Command::InstancesAdopt(InstancesAdoptArgs {
|
||||
version_id,
|
||||
name: parsed.value("name"),
|
||||
target,
|
||||
dry_run: parsed.has("dry-run"),
|
||||
}))
|
||||
}
|
||||
@@ -144,6 +144,10 @@ fn loader_json(version_id: &str) -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
pub mod adopt;
|
||||
mod adopt_shared;
|
||||
pub mod scan;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
//! `ull instances adopt`:把盘上已有的版本登记成实例(M221)。
|
||||
//!
|
||||
//! **只读外部、只写自己**:写盘面只有 `<数据根>/.ULL/config/` 下的两份配置(+ 选中缺省运行目录时
|
||||
//! 建那个空目录),`versions/` `libraries/` `assets/` 一个字节都不写。判据、落点与话术全在
|
||||
//! [`unlucky_core::game::adopt`];本模块只做「参数 → core 调用 → 人读/JSON 两条输出」。
|
||||
//!
|
||||
//! `--dry-run` 走 `adopt::plan`(零写盘),所以「先看一眼」不会改任何东西,也不会建目录。
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use unlucky_core::game::adopt::{self, AdoptRequest};
|
||||
use unlucky_core::game::GameLayout;
|
||||
use unlucky_core::launch::time::{format_rfc3339_millis, now};
|
||||
use unlucky_core::platform::layout::LauncherLayout;
|
||||
|
||||
use crate::cli::model::InstancesAdoptArgs;
|
||||
use crate::context::Ctx;
|
||||
use crate::error::CliError;
|
||||
use crate::output::Report;
|
||||
|
||||
use super::adopt_shared::{candidate_json, map_error};
|
||||
|
||||
/// `ull instances adopt <version-id> [--name N] [--isolation …] [--game-dir DIR] [--dry-run]`。
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 版本不在盘上 / 候选不合格 / 名字冲突 / 运行目录不可用 / 读配置失败,全部由
|
||||
/// [`unlucky_core::game::adopt::AdoptError`] 映射成稳定错误码(`adopt_*`)。
|
||||
pub fn run(ctx: &Ctx, args: &InstancesAdoptArgs) -> Result<Report, CliError> {
|
||||
let request = AdoptRequest {
|
||||
version_id: args.version_id.clone(),
|
||||
name: args.name.clone(),
|
||||
target: args.target.clone(),
|
||||
created_at: Some(format_rfc3339_millis(now())),
|
||||
};
|
||||
let (game, launcher) = (ctx.game(), ctx.layout());
|
||||
if args.dry_run {
|
||||
return dry_run(&game, &launcher, &request);
|
||||
}
|
||||
let outcome = adopt::adopt(&game, &launcher, &request).map_err(map_error)?;
|
||||
// 人读行先拼(只借用),再把字段移进 JSON(两条出口的内容同源、顺序不影响事实)。
|
||||
let mut human = vec![format!(
|
||||
"已登记实例 `{}`(id {})→ 版本 {}",
|
||||
outcome.name, outcome.instance_id, outcome.version_id
|
||||
)];
|
||||
human.push(format!(
|
||||
" 隔离档 {}(运行目录来源 {}),运行目录 {}",
|
||||
outcome.isolation.as_str(),
|
||||
outcome.target.as_str(),
|
||||
outcome.run_dir.display()
|
||||
));
|
||||
human.push(format!(" 实例设置 {}", outcome.config_path.display()));
|
||||
if outcome.dir_created {
|
||||
human.push(" 已新建该运行目录(空目录;玩家数据由游戏自己往里写)".to_string());
|
||||
}
|
||||
human.push(
|
||||
" 只写了本启动器的配置:versions/ libraries/ assets/ 一个字节都没动(不搬文件)"
|
||||
.to_string(),
|
||||
);
|
||||
human.extend(outcome.notes.iter().map(|note| format!(" 提示:{note}")));
|
||||
let version_id = outcome.version_id.clone();
|
||||
let data = json!({
|
||||
"dry_run": false,
|
||||
"version_id": version_id,
|
||||
"instance": json!({
|
||||
"id": outcome.instance_id,
|
||||
"name": outcome.name,
|
||||
"version_id": version_id,
|
||||
"isolation": outcome.isolation.as_str(),
|
||||
"run_dir": outcome.run_dir.display().to_string(),
|
||||
"run_dir_source": outcome.target.as_str(),
|
||||
"config_path": outcome.config_path.display().to_string(),
|
||||
"created": outcome.created,
|
||||
"dir_created": outcome.dir_created,
|
||||
}),
|
||||
"notes": outcome.notes,
|
||||
});
|
||||
Ok(Report::new(data, human))
|
||||
}
|
||||
|
||||
/// `--dry-run`:只算落点与判据,不写盘(连缺省运行目录都不建)。
|
||||
fn dry_run(
|
||||
game: &GameLayout,
|
||||
launcher: &LauncherLayout,
|
||||
request: &AdoptRequest,
|
||||
) -> Result<Report, CliError> {
|
||||
let plan = adopt::plan(game, launcher, request).map_err(map_error)?;
|
||||
let mut human = vec![format!(
|
||||
"检查通过:版本 {} 可登记(--dry-run:没有写任何文件)",
|
||||
plan.candidate.version_id
|
||||
)];
|
||||
human.push(format!(
|
||||
" 实例名 {},隔离档 {}(运行目录来源 {})",
|
||||
plan.name,
|
||||
plan.isolation.as_str(),
|
||||
plan.target.as_str()
|
||||
));
|
||||
human.push(format!(" 运行目录 {}", plan.run_dir.display()));
|
||||
human.extend(plan.notes.iter().map(|note| format!(" 提示:{note}")));
|
||||
let version_id = plan.candidate.version_id.clone();
|
||||
let data = json!({
|
||||
"dry_run": true,
|
||||
"version_id": version_id,
|
||||
"candidate": candidate_json(&plan.candidate),
|
||||
"instance": json!({
|
||||
"id": Value::Null,
|
||||
"name": plan.name,
|
||||
"version_id": version_id,
|
||||
"isolation": plan.isolation.as_str(),
|
||||
"run_dir": plan.run_dir.display().to_string(),
|
||||
"run_dir_source": plan.target.as_str(),
|
||||
"config_path": Value::Null,
|
||||
"created": false,
|
||||
"dir_created": false,
|
||||
}),
|
||||
"notes": plan.notes,
|
||||
});
|
||||
Ok(Report::new(data, human))
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
//! `instances scan` / `instances adopt` 共用的 JSON 与错误投影。
|
||||
//!
|
||||
//! 两条命令输出同一种候选形状(`candidate` 对象),错误也走同一份映射——分两份写迟早漂。
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use unlucky_core::game::adopt::{AdoptCandidate, AdoptError, AdoptProblem};
|
||||
|
||||
use crate::error::CliError;
|
||||
|
||||
/// 候选 → `--json` 里的 `candidate` 对象。
|
||||
pub(super) fn candidate_json(candidate: &AdoptCandidate) -> Value {
|
||||
json!({
|
||||
"version_id": candidate.version_id,
|
||||
"version_dir": candidate.version_dir.display().to_string(),
|
||||
"manifest_path": candidate.manifest_path.display().to_string(),
|
||||
"jar_present": candidate.jar_present,
|
||||
"manifest_id": candidate.manifest_id,
|
||||
"inherits": candidate.inherits,
|
||||
"registered": candidate.registered.iter().map(|item| json!({
|
||||
"id": item.id,
|
||||
"name": item.name,
|
||||
})).collect::<Vec<Value>>(),
|
||||
"adoptable": candidate.adoptable(),
|
||||
"problems": problems_json(&candidate.problems),
|
||||
})
|
||||
}
|
||||
|
||||
/// 问题清单 → 结构化数组(`code` 稳定、`message` 人读)。
|
||||
pub(super) fn problems_json(problems: &[AdoptProblem]) -> Value {
|
||||
Value::Array(
|
||||
problems
|
||||
.iter()
|
||||
.map(|problem| {
|
||||
json!({
|
||||
"code": problem.code(),
|
||||
"message": problem.to_string(),
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// `AdoptError` → CLI 错误:稳定 code + 逐条问题进 `detail`(脚本不必解析散文)。
|
||||
pub(super) fn map_error(error: AdoptError) -> CliError {
|
||||
let code = error.code();
|
||||
let message = error.to_string();
|
||||
let cli = CliError::user(code, message);
|
||||
let hint = match &error {
|
||||
AdoptError::DuplicateName { .. } => {
|
||||
Some("换个展示名:%prog% instances adopt <version-id> --name <新名字>")
|
||||
}
|
||||
AdoptError::NotAdoptable { .. } => Some(
|
||||
"这些版本要么清单坏了、要么缺父版本、要么越界:先在原来的启动器里把它修好,\
|
||||
或 `%prog% install <version>` 让本启动器自己装一份",
|
||||
),
|
||||
AdoptError::AlreadyRegistered { .. } => {
|
||||
Some("用 `%prog% instances list` 看已有实例;要第二个实例请换 --name")
|
||||
}
|
||||
AdoptError::TargetNotEmpty { .. } => {
|
||||
Some("换一个名字(缺省目录按名字派生),或用 --isolation custom --game-dir <空目录>")
|
||||
}
|
||||
AdoptError::UnknownVersion { .. } => Some("先看有哪些可用:%prog% instances scan"),
|
||||
_ => None,
|
||||
};
|
||||
let cli = match hint {
|
||||
Some(hint) => cli.with_hint(hint),
|
||||
None => cli,
|
||||
};
|
||||
cli.with_detail(json!({
|
||||
"problems": problems_json(error.problems()),
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
//! `ull instances scan`:列出当前游戏根 `versions/` 里**已经铺好**的版本,逐项说清能不能登记(M221)。
|
||||
//!
|
||||
//! 只读:不写任何文件、不改任何 mtime。用途是「我盘上已经有别的启动器装好的版本,看看 ULL 认不认」,
|
||||
//! 以及 `instances adopt` 的前置检查(同一套判据,见 [`unlucky_core::game::adopt::scan`])。
|
||||
|
||||
use serde_json::json;
|
||||
use unlucky_core::game::adopt;
|
||||
|
||||
use crate::context::Ctx;
|
||||
use crate::error::CliError;
|
||||
use crate::output::Report;
|
||||
|
||||
use super::adopt_shared::candidate_json;
|
||||
|
||||
/// `ull instances scan`。
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// `versions/` 或 `profiles.json` 读不了时返回用户错误(**不降级成空列表**)。
|
||||
pub fn run(ctx: &Ctx) -> Result<Report, CliError> {
|
||||
let scan = adopt::scan(&ctx.game(), &ctx.layout()).map_err(super::adopt_shared::map_error)?;
|
||||
let ready = scan
|
||||
.candidates
|
||||
.iter()
|
||||
.filter(|candidate| candidate.adoptable())
|
||||
.count();
|
||||
let registered = scan
|
||||
.candidates
|
||||
.iter()
|
||||
.filter(|candidate| candidate.is_registered())
|
||||
.count();
|
||||
|
||||
let candidates: Vec<serde_json::Value> = scan.candidates.iter().map(candidate_json).collect();
|
||||
let data = json!({
|
||||
"game_root": ctx.data.game_home.display().to_string(),
|
||||
"versions_dir": scan.versions_dir.display().to_string(),
|
||||
"counts": {
|
||||
"total": scan.candidates.len(),
|
||||
"adoptable": ready,
|
||||
"registered": registered,
|
||||
},
|
||||
"candidates": candidates,
|
||||
});
|
||||
|
||||
let mut human = vec![format!(
|
||||
"游戏根 {}:versions/ 里 {} 个版本,{} 个可登记",
|
||||
scan.versions_dir.display(),
|
||||
scan.candidates.len(),
|
||||
ready
|
||||
)];
|
||||
if scan.candidates.is_empty() {
|
||||
human.push(
|
||||
" (空)这个游戏根下还没有任何版本;`%prog% install <version>` 可以自己装一份"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
for candidate in &scan.candidates {
|
||||
if candidate.adoptable() {
|
||||
let state = if candidate.is_registered() {
|
||||
"已登记"
|
||||
} else {
|
||||
"可登记"
|
||||
};
|
||||
human.push(format!(
|
||||
" ✓ {} [{state}]{}",
|
||||
candidate.version_id,
|
||||
chain_suffix(candidate)
|
||||
));
|
||||
} else {
|
||||
human.push(format!(" ✗ {}", candidate.version_id));
|
||||
for problem in &candidate.problems {
|
||||
human.push(format!(" 原因[{0}] {problem}", problem.code()));
|
||||
}
|
||||
}
|
||||
}
|
||||
if ready > 0 {
|
||||
human.push(
|
||||
"登记一个:%prog% instances adopt <version-id>(缺省落 ULL 数据区的独立运行目录)"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
Ok(Report::new(data, human))
|
||||
}
|
||||
|
||||
/// 人读行尾的父链提示(`1.12.2-forge-…` 后面标出它继承的是谁)。
|
||||
fn chain_suffix(candidate: &unlucky_core::game::AdoptCandidate) -> String {
|
||||
match candidate.inherits.len() {
|
||||
0 | 1 => String::new(),
|
||||
_ => format!(" 继承 {}", candidate.inherits[1..].join(" -> ")),
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,10 @@ pub fn run(invocation: &Invocation) -> Result<Outcome, CliError> {
|
||||
Command::InstancesLaunchArgs(args) => {
|
||||
with_ctx(&invocation.globals, |ctx| instance_launch::run(ctx, args))
|
||||
}
|
||||
Command::InstancesScan => with_ctx(&invocation.globals, instances::scan::run),
|
||||
Command::InstancesAdopt(args) => {
|
||||
with_ctx(&invocation.globals, |ctx| instances::adopt::run(ctx, args))
|
||||
}
|
||||
Command::Install(args) => with_ctx(&invocation.globals, |ctx| install::run(ctx, args)),
|
||||
Command::PackImport(args) => {
|
||||
with_ctx_outcome(&invocation.globals, |ctx| pack::run(ctx, args))
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
//! M221 CLI 端到端:`ull instances scan` / `ull instances adopt` 的真实入口(解析 → 执行 → 两条输出)。
|
||||
//!
|
||||
//! 用的都是**真磁盘**数据根(`support::TempDir`)+ 一份「别的启动器铺好的」`.minecraft`。
|
||||
//! 每条用例都断言外部文件哈希/mtime 不变(`fixture::assert_unchanged`),
|
||||
//! 因为「只登记不搬文件」是本 mission 的核心承诺。
|
||||
|
||||
#[path = "adopt_test/cli_surface.rs"]
|
||||
mod cli_surface;
|
||||
#[path = "adopt_test/fixture.rs"]
|
||||
mod fixture;
|
||||
#[path = "support/mod.rs"]
|
||||
mod support;
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use support::{parse_json, run_cli, TempDir};
|
||||
|
||||
use crate::fixture::{assert_unchanged, foreign_data_root, snapshot};
|
||||
|
||||
/// 缺省登记:落 ULL 数据区的独立目录,隔离档 `custom`,**不沿用全局 `isolated`**。
|
||||
///
|
||||
/// 抓得住:
|
||||
/// - 缺省沿用全局 `isolated`(运行目录会变成 `versions/1.20.1`,第二条断言会红)——
|
||||
/// 这是本 mission 点名的最容易漏的一条;
|
||||
/// - 命令只登记不输出(`--json` 缺 `instance`);
|
||||
/// - 登记过程写了外部 `.minecraft`(哈希断言)。
|
||||
///
|
||||
/// 抓不住:GUI 是否也能触发同一条路(GUI 接线是后续 mission)。
|
||||
#[test]
|
||||
fn adopt_without_isolation_uses_a_separate_run_dir_and_keeps_global_isolated_out_of_it() {
|
||||
let dir = TempDir::new("adopt-default");
|
||||
let root = dir.path();
|
||||
foreign_data_root(root);
|
||||
// 全局档显式写成 isolated(D20 的缺省):登记**不许**继承它去踩别人的版本目录。
|
||||
set_global_isolated(&dir);
|
||||
let minecraft = root.join(".minecraft");
|
||||
let before = snapshot(&minecraft);
|
||||
|
||||
let (code, stdout, stderr) = run_cli(&[
|
||||
"instances",
|
||||
"adopt",
|
||||
"1.20.1",
|
||||
"--json",
|
||||
"--data-dir",
|
||||
&dir.arg(),
|
||||
]);
|
||||
assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}");
|
||||
let after = snapshot(&minecraft);
|
||||
assert_unchanged(&before, &after, "adopt 之后");
|
||||
|
||||
let value = parse_json(&stdout);
|
||||
let instance = &value["data"]["instance"];
|
||||
assert_eq!(instance["isolation"], "custom");
|
||||
assert_eq!(instance["run_dir_source"], "instance_dir");
|
||||
let run_dir = instance["run_dir"].as_str().expect("run_dir");
|
||||
assert!(
|
||||
run_dir.contains("instances"),
|
||||
"缺省运行目录应落 ULL 数据区:{run_dir}"
|
||||
);
|
||||
assert!(
|
||||
!Path::new(run_dir).starts_with(&minecraft),
|
||||
"缺省运行目录不许落进别人的 .minecraft:{run_dir}"
|
||||
);
|
||||
assert!(
|
||||
!run_dir.ends_with("versions/1.20.1") && !run_dir.ends_with("versions\\1.20.1"),
|
||||
"不许沿用全局 isolated 的 versions/<id>:{run_dir}"
|
||||
);
|
||||
assert_eq!(instance["created"], true);
|
||||
|
||||
// 再走一次 `instances list`:档案真的进去了(不是只写了实例文件)。
|
||||
let (code, stdout, _) = run_cli(&["instances", "list", "--json", "--data-dir", &dir.arg()]);
|
||||
assert_eq!(code, 0);
|
||||
let listed = parse_json(&stdout);
|
||||
assert_eq!(listed["data"]["instances"][0]["version_id"], "1.20.1");
|
||||
assert_eq!(listed["data"]["instances"][0]["version_present"], true);
|
||||
}
|
||||
|
||||
/// 登记之后 `launch --dry-run` 的 `--gameDir` 就是选定的运行目录(本 mission 的功能落点)。
|
||||
///
|
||||
/// 抓得住:登记把隔离档写错(`inherit`)⇒ 启动派生坚持全局 `isolated`,`game_dir` 变成
|
||||
/// `versions/1.20.1`(第二条断言会红);`gameDir` 没进启动计划。
|
||||
/// 抓不住:真进程是否真的用这个 CWD(要真跑游戏,本 mission 不跑)。
|
||||
#[test]
|
||||
fn the_launch_plan_points_game_dir_at_the_chosen_run_dir() {
|
||||
let dir = TempDir::new("adopt-launch");
|
||||
let root = dir.path();
|
||||
foreign_data_root(root);
|
||||
set_global_isolated(&dir);
|
||||
|
||||
let (code, stdout, stderr) = run_cli(&[
|
||||
"instances",
|
||||
"adopt",
|
||||
"1.20.1",
|
||||
"--json",
|
||||
"--data-dir",
|
||||
&dir.arg(),
|
||||
]);
|
||||
assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}");
|
||||
let adopted = parse_json(&stdout);
|
||||
let run_dir = adopted["data"]["instance"]["run_dir"]
|
||||
.as_str()
|
||||
.expect("run_dir")
|
||||
.to_string();
|
||||
let instance_id = adopted["data"]["instance"]["id"]
|
||||
.as_str()
|
||||
.expect("instance id")
|
||||
.to_string();
|
||||
|
||||
let dir_arg = dir.arg();
|
||||
let args = [
|
||||
"launch",
|
||||
instance_id.as_str(),
|
||||
"--dry-run",
|
||||
"--json",
|
||||
"--data-dir",
|
||||
dir_arg.as_str(),
|
||||
];
|
||||
let (code, stdout, stderr) = run_cli(&args);
|
||||
assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}");
|
||||
let plan = parse_json(&stdout);
|
||||
assert_eq!(plan["data"]["game_dir"], run_dir.as_str());
|
||||
assert_eq!(plan["data"]["isolation"], "custom");
|
||||
assert_eq!(plan["data"]["isolation_source"], "instance");
|
||||
let command = plan["data"]["argv"]
|
||||
.as_array()
|
||||
.expect("启动计划里应有 argv");
|
||||
let game_dir_flag = command
|
||||
.windows(2)
|
||||
.find(|pair| pair[0].as_str() == Some("--gameDir"))
|
||||
.map(|pair| pair[1].as_str().unwrap_or_default().to_string())
|
||||
.expect("命令行里应有 --gameDir");
|
||||
// `argv` 是**脱敏后**的(主目录 → `<home>`,见 `core::launch::redact`),所以比尾段而不是全等;
|
||||
// 全等的那条断言在 `data.game_dir` 上(那是未脱敏的权威值)。
|
||||
let tail = format!(
|
||||
"instances/{}",
|
||||
Path::new(&run_dir)
|
||||
.file_name()
|
||||
.expect("运行目录名")
|
||||
.to_string_lossy()
|
||||
);
|
||||
assert!(
|
||||
game_dir_flag.ends_with(&tail) || game_dir_flag.ends_with(&tail.replace('/', "\\")),
|
||||
"--gameDir 必须指向选定的运行目录:{game_dir_flag} 应以 {tail} 结尾"
|
||||
);
|
||||
}
|
||||
|
||||
/// `--isolation shared`:明确选共享 ⇒ 运行目录 = 别人的游戏根,**人读输出必须说出后果**。
|
||||
///
|
||||
/// 抓得住:shared 档没有告知(stdout 里没有「共用」)、shared 被写成 custom + 自己的目录、
|
||||
/// 登记往游戏根写文件(哈希断言)。
|
||||
/// 抓不住:用户是否真的看见这句(UI 验收另说)。
|
||||
#[test]
|
||||
fn shared_isolation_states_the_consequence_in_human_output() {
|
||||
let dir = TempDir::new("adopt-shared");
|
||||
let root = dir.path();
|
||||
foreign_data_root(root);
|
||||
let minecraft = root.join(".minecraft");
|
||||
let before = snapshot(&minecraft);
|
||||
|
||||
let (code, stdout, stderr) = run_cli(&[
|
||||
"instances",
|
||||
"adopt",
|
||||
"1.20.1",
|
||||
"--isolation",
|
||||
"shared",
|
||||
"--data-dir",
|
||||
&dir.arg(),
|
||||
]);
|
||||
assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}");
|
||||
let after = snapshot(&minecraft);
|
||||
assert_unchanged(&before, &after, "shared 登记之后");
|
||||
assert!(
|
||||
stdout.contains("共用"),
|
||||
"必须说出「共用别人的 .minecraft」:{stdout}"
|
||||
);
|
||||
assert!(stdout.contains("一个字节都没动"), "{stdout}");
|
||||
}
|
||||
|
||||
/// `--dry-run`:只检查不写盘(连配置目录都不建)。
|
||||
///
|
||||
/// 抓得住:`--dry-run` 真的写了档案或建了运行目录(快照会红)。
|
||||
/// 抓不住:`--dry-run` 有没有顺带读了不该读的东西。
|
||||
#[test]
|
||||
fn dry_run_writes_nothing() {
|
||||
let dir = TempDir::new("adopt-dry");
|
||||
let root = dir.path();
|
||||
foreign_data_root(root);
|
||||
let before = snapshot(root);
|
||||
|
||||
let (code, stdout, stderr) = run_cli(&[
|
||||
"instances",
|
||||
"adopt",
|
||||
"1.20.1",
|
||||
"--dry-run",
|
||||
"--data-dir",
|
||||
&dir.arg(),
|
||||
]);
|
||||
assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}");
|
||||
let after = snapshot(root);
|
||||
assert_unchanged(&before, &after, "--dry-run 之后");
|
||||
assert!(stdout.contains("检查通过"), "{stdout}");
|
||||
assert!(stdout.contains("没有写任何文件"), "{stdout}");
|
||||
}
|
||||
|
||||
/// 坏的版本(缺父)⇒ 退出码 1,`--json` 里带**逐条**问题码。
|
||||
///
|
||||
/// 抓得住:不合格版本被登记成功(退出码变 0)、问题码被折叠成一句散文(`detail.problems` 缺项)。
|
||||
/// 抓不住:用户在原来的启动器里修好之后重试(自然覆盖)。
|
||||
#[test]
|
||||
fn not_adoptable_version_exits_one_with_structured_problems() {
|
||||
let dir = TempDir::new("adopt-refuse");
|
||||
let root = dir.path();
|
||||
foreign_data_root(root);
|
||||
let before = snapshot(root);
|
||||
|
||||
let (code, stdout, _) = run_cli(&[
|
||||
"instances",
|
||||
"adopt",
|
||||
"1.20.1-orphan",
|
||||
"--json",
|
||||
"--data-dir",
|
||||
&dir.arg(),
|
||||
]);
|
||||
assert_eq!(code, 1, "{stdout}");
|
||||
let value = parse_json(&stdout);
|
||||
assert_eq!(value["ok"], false);
|
||||
assert_eq!(value["error"]["code"], "adopt_not_adoptable");
|
||||
assert_eq!(
|
||||
value["error"]["detail"]["problems"][0]["code"],
|
||||
"missing_parent"
|
||||
);
|
||||
let after = snapshot(root);
|
||||
assert_unchanged(&before, &after, "失败之后");
|
||||
}
|
||||
|
||||
/// 重复登记 ⇒ 退出码 1 + 无副作用(档案逐字节不变)。
|
||||
///
|
||||
/// 抓得住:重复登记当成功(退出码 0)或失败时改了档案。
|
||||
/// 抓不住:并发两次登记(没有锁;这不是并发入口)。
|
||||
#[test]
|
||||
fn repeating_the_same_adopt_exits_one_without_side_effects() {
|
||||
let dir = TempDir::new("adopt-repeat");
|
||||
let root = dir.path();
|
||||
foreign_data_root(root);
|
||||
let (code, _, stderr) = run_cli(&["instances", "adopt", "1.20.1", "--data-dir", &dir.arg()]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
let config = root.join(".ULL/config");
|
||||
let before = snapshot(&config);
|
||||
|
||||
let (code, stdout, _) = run_cli(&[
|
||||
"instances",
|
||||
"adopt",
|
||||
"1.20.1",
|
||||
"--json",
|
||||
"--data-dir",
|
||||
&dir.arg(),
|
||||
]);
|
||||
assert_eq!(code, 1, "{stdout}");
|
||||
assert_eq!(
|
||||
parse_json(&stdout)["error"]["code"],
|
||||
"adopt_already_registered"
|
||||
);
|
||||
let after = snapshot(&config);
|
||||
assert_unchanged(&before, &after, "重复登记失败之后");
|
||||
}
|
||||
|
||||
/// `instances scan`:只读列出候选,坏版本逐条给原因。
|
||||
///
|
||||
/// 抓得住:扫描变成空列表(那是本 mission 点名不许的行为)、坏版本被静默跳过、
|
||||
/// 扫描写了文件。
|
||||
/// 抓不住:真实 `.minecraft` 里那些平台特有的怪目录(夹具只覆盖已知形状)。
|
||||
#[test]
|
||||
fn scan_lists_candidates_and_reasons_without_writing() {
|
||||
let dir = TempDir::new("adopt-scan");
|
||||
let root = dir.path();
|
||||
foreign_data_root(root);
|
||||
let before = snapshot(root);
|
||||
|
||||
let (code, stdout, stderr) =
|
||||
run_cli(&["instances", "scan", "--json", "--data-dir", &dir.arg()]);
|
||||
assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}");
|
||||
let after = snapshot(root);
|
||||
assert_unchanged(&before, &after, "scan 之后");
|
||||
|
||||
let value = parse_json(&stdout);
|
||||
assert_eq!(value["data"]["counts"]["total"], 2);
|
||||
assert_eq!(value["data"]["counts"]["adoptable"], 1);
|
||||
let candidates = value["data"]["candidates"].as_array().expect("candidates");
|
||||
let ok = candidates
|
||||
.iter()
|
||||
.find(|item| item["version_id"] == "1.20.1")
|
||||
.expect("有 1.20.1");
|
||||
assert_eq!(ok["adoptable"], true);
|
||||
assert_eq!(ok["jar_present"], true);
|
||||
let orphan = candidates
|
||||
.iter()
|
||||
.find(|item| item["version_id"] == "1.20.1-orphan")
|
||||
.expect("有 1.20.1-orphan");
|
||||
assert_eq!(orphan["adoptable"], false);
|
||||
assert_eq!(orphan["problems"][0]["code"], "missing_parent");
|
||||
}
|
||||
|
||||
/// 把全局隔离档设成 `isolated`(走 schema 校验的正式入口,不手写 launcher.json)。
|
||||
fn set_global_isolated(dir: &TempDir) {
|
||||
let dir_arg = dir.arg();
|
||||
let (code, _, stderr) = run_cli(&[
|
||||
"config",
|
||||
"set",
|
||||
"instances.mode",
|
||||
"isolated",
|
||||
"--data-dir",
|
||||
dir_arg.as_str(),
|
||||
]);
|
||||
assert_eq!(code, 0, "设置全局隔离档失败:{stderr}");
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
//! 命令面: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}");
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
//! CLI 侧夹具:一个「别的启动器铺好了 `.minecraft`」的数据根 + 全量快照工具。
|
||||
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::collections::BTreeMap;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::path::Path;
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
/// 造一份「别的启动器已经铺好的」数据根(`<root>/.minecraft` + `<root>/.ULL`):
|
||||
///
|
||||
/// | 路径 | 用意 |
|
||||
/// | --- | --- |
|
||||
/// | `versions/1.20.1/` | 正常版本(清单 + jar),可登记、可 `launch --dry-run` |
|
||||
/// | `versions/1.20.1-orphan/` | 缺父版本 ⇒ 不可登记 |
|
||||
/// | `libraries/` `assets/` | 恒共享层(登记不该碰) |
|
||||
/// | `mods/` `saves/` | 玩家数据(登记不该碰) |
|
||||
/// | `launcher_profiles.json` | 别的启动器的元数据(连读都不该读,更不该写) |
|
||||
pub fn foreign_data_root(root: &Path) {
|
||||
let minecraft = root.join(".minecraft");
|
||||
let versions = minecraft.join("versions");
|
||||
write_version(&versions, "1.20.1", MANIFEST_OK, true);
|
||||
write_version(&versions, "1.20.1-orphan", MANIFEST_ORPHAN, true);
|
||||
write_file(
|
||||
&minecraft.join("libraries/com/mojang/brigadier/1.0.18/brigadier-1.0.18.jar"),
|
||||
b"library-bytes",
|
||||
);
|
||||
write_file(
|
||||
&minecraft.join("assets/indexes/5.json"),
|
||||
b"{\"objects\":{}}",
|
||||
);
|
||||
write_file(&minecraft.join("mods/jei.jar"), b"mod-bytes");
|
||||
write_file(&minecraft.join("saves/World/level.dat"), b"save-bytes");
|
||||
write_file(
|
||||
&minecraft.join("launcher_profiles.json"),
|
||||
br#"{"profiles":{"1.20.1":{"name":"1.20.1","lastVersionId":"1.20.1"}}}"#,
|
||||
);
|
||||
}
|
||||
|
||||
/// 全量快照:相对路径 → (字节数, 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 Ok(entries) = std::fs::read_dir(dir) else {
|
||||
return;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
let Ok(meta) = std::fs::symlink_metadata(&path) else {
|
||||
continue;
|
||||
};
|
||||
if meta.is_dir() {
|
||||
walk(root, &path, out);
|
||||
continue;
|
||||
}
|
||||
let relative = path
|
||||
.strip_prefix(root)
|
||||
.unwrap_or(&path)
|
||||
.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 {
|
||||
assert_eq!(
|
||||
before,
|
||||
after.get(path).expect("同一路径"),
|
||||
"{what}:文件被改动 -> {path}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn write_version(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"junk").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("写文件");
|
||||
}
|
||||
|
||||
const MANIFEST_OK: &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": 4, "url": "http://example.invalid/client.jar" } }
|
||||
}"#;
|
||||
|
||||
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": []
|
||||
}"#;
|
||||
Reference in new issue
Block a user