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:
AskaEth committed 2026-11-09 22:21:37 +08:00
1 parent 0577ee87a3
commit 9f5c001387
25 files changed
+3460 -73

No files matched your search

+4
View File
@@ -144,6 +144,10 @@ fn loader_json(version_id: &str) -> Value {
})
}
pub mod adopt;
mod adopt_shared;
pub mod scan;
#[cfg(test)]
mod tests;
+118
View File
@@ -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()),
}))
}
+91
View File
@@ -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(" -> ")),
}
}
+4
View File
@@ -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))