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,324 @@
|
||||
//! 落点计算与真正的登记:`plan`(纯算 + 零写盘)与 `adopt`(plan + 只写自己的两份配置)。
|
||||
//!
|
||||
//! # 写盘面(全部在 ULL 数据根下,游戏根一个字节都不动)
|
||||
//!
|
||||
//! 1. `config/instances/<id>.json`(实例设置:隔离档 + 运行目录);
|
||||
//! 2. `config/profiles.json`(档案列表);
|
||||
//! 3. 选了缺省运行目录时,`<data>/instances/<实例目录名>` 这个空目录(已存在且非空 ⇒ 拒绝;
|
||||
//! 路径上的已有祖先若解析到**数据根之外**(符号链接/目录联接)⇒ 拒绝,不沿它写盘)。
|
||||
//!
|
||||
//! `versions/` `libraries/` `assets/` **一个字节都不写**:登记只填 `version_id`,内容靠 D20 的
|
||||
//! 「恒共享层」被启动/下载链路复用([`crate::game::isolation::SHARED_LAYERS`])。
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::super::install::instance::{read_profiles, register_with, InstanceSettings, Isolation};
|
||||
use super::super::install::pack_dir;
|
||||
use super::super::layout::GameLayout;
|
||||
use super::candidate::{AdoptCandidate, AdoptTarget};
|
||||
use super::error::AdoptError;
|
||||
use super::inspect::inspect;
|
||||
use crate::platform::layout::LauncherLayout;
|
||||
|
||||
/// 一次登记请求(CLI / presenter 的输入形状)。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AdoptRequest {
|
||||
/// 要接进来的版本 id(= `versions/<id>/`)。
|
||||
pub version_id: String,
|
||||
/// 展示名;缺省 = 版本 id。
|
||||
pub name: Option<String>,
|
||||
/// 运行目录选择(缺省 [`AdoptTarget::InstanceDir`],**不是** `isolated`)。
|
||||
pub target: AdoptTarget,
|
||||
/// 档案的创建时间(RFC-3339;core 不碰时钟格式,由调用方给)。
|
||||
pub created_at: Option<String>,
|
||||
}
|
||||
|
||||
impl AdoptRequest {
|
||||
/// 最小请求(缺省名 + 缺省运行目录)。
|
||||
#[must_use]
|
||||
pub fn new(version_id: impl Into<String>) -> Self {
|
||||
Self {
|
||||
version_id: version_id.into(),
|
||||
name: None,
|
||||
target: AdoptTarget::default(),
|
||||
created_at: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 一次登记的**计划**(不写任何东西;`--dry-run` / GUI 预检就吃这个)。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AdoptPlan {
|
||||
/// 检查过的候选(含问题清单,正常时为空)。
|
||||
pub candidate: AdoptCandidate,
|
||||
/// 将写进档案的展示名。
|
||||
pub name: String,
|
||||
/// 运行目录选择。
|
||||
pub target: AdoptTarget,
|
||||
/// 生效隔离档。
|
||||
pub isolation: Isolation,
|
||||
/// 生效运行目录(= `--gameDir`)。
|
||||
pub run_dir: PathBuf,
|
||||
/// 人读提示(共享/版本目录的后果、已有同版本实例…)。
|
||||
pub notes: Vec<String>,
|
||||
}
|
||||
|
||||
/// 一次登记的结果。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AdoptOutcome {
|
||||
/// 实例 id(稳定 UUID)。
|
||||
pub instance_id: String,
|
||||
/// 展示名。
|
||||
pub name: String,
|
||||
/// 绑定的版本 id。
|
||||
pub version_id: String,
|
||||
/// 实例设置文件路径。
|
||||
pub config_path: PathBuf,
|
||||
/// 生效隔离档。
|
||||
pub isolation: Isolation,
|
||||
/// 运行目录选择。
|
||||
pub target: AdoptTarget,
|
||||
/// 生效运行目录。
|
||||
pub run_dir: PathBuf,
|
||||
/// 是否新建了档案(`false` 只可能是复用同名同版本档案,本命令会先拒绝那种情况)。
|
||||
pub created: bool,
|
||||
/// 是否新建了缺省运行目录(`false` = 目录已存在但为空、直接复用)。
|
||||
pub dir_created: bool,
|
||||
/// 人读提示(与 [`AdoptPlan::notes`] 同一份)。
|
||||
pub notes: Vec<String>,
|
||||
}
|
||||
|
||||
/// 计算一次登记:检查候选 + 解析名字 + 查重名 + 算运行目录。**零写盘**。
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// - [`AdoptError::UnknownVersion`]:版本不在盘上;
|
||||
/// - [`AdoptError::NotAdoptable`]:候选有问题(清单坏/缺父/环/越界…,原因逐条给出;由
|
||||
/// [`inspect`] 判出来);
|
||||
/// - [`AdoptError::DuplicateName`] / [`AdoptError::AlreadyRegistered`]:名字冲突 / 重复登记;
|
||||
/// - [`AdoptError::TargetNotEmpty`] / [`AdoptError::TargetInvalid`]:运行目录不可用;
|
||||
/// - [`AdoptError::Game`]:`profiles.json` 读不了。
|
||||
pub fn plan(
|
||||
game: &GameLayout,
|
||||
launcher: &LauncherLayout,
|
||||
request: &AdoptRequest,
|
||||
) -> Result<AdoptPlan, AdoptError> {
|
||||
// `inspect` 只在候选**可登记**时返回 `Ok`,不合格一律是 `NotAdoptable`(问题清单已带出)。
|
||||
let candidate = inspect(game, launcher, &request.version_id)?;
|
||||
let name = resolve_name(request.name.as_deref(), &candidate.version_id);
|
||||
let profiles = read_profiles(launcher)?;
|
||||
let mut notes = Vec::new();
|
||||
// 重名与重复登记:**显式报错**,不静默复用(复用会把用户「导入这个」的意图改成「改一个别的实例」)。
|
||||
if let Some(existing) = profiles
|
||||
.profiles
|
||||
.iter()
|
||||
.find(|profile| profile.name == name)
|
||||
{
|
||||
if existing.version_id == candidate.version_id {
|
||||
return Err(AdoptError::AlreadyRegistered {
|
||||
version_id: candidate.version_id.clone(),
|
||||
name,
|
||||
instance_id: existing.id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
return Err(AdoptError::DuplicateName {
|
||||
name,
|
||||
instance_id: existing.id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
for profile in &candidate.registered {
|
||||
notes.push(format!(
|
||||
"这个版本已经有实例了:`{}`(id {})——再登记会得到第二个实例,两个实例共用同一份版本文件",
|
||||
profile.name, profile.id
|
||||
));
|
||||
}
|
||||
|
||||
let run_dir = run_dir_of(
|
||||
game,
|
||||
launcher,
|
||||
&candidate.version_id,
|
||||
&name,
|
||||
&request.target,
|
||||
)?;
|
||||
notes.extend(target_notes(&request.target, &run_dir));
|
||||
|
||||
Ok(AdoptPlan {
|
||||
candidate,
|
||||
name,
|
||||
target: request.target.clone(),
|
||||
isolation: request.target.isolation(),
|
||||
run_dir,
|
||||
notes,
|
||||
})
|
||||
}
|
||||
|
||||
/// 按计划登记:先准备缺省运行目录(若选了它),再写实例设置与档案。
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 同 [`plan`],外加建目录/写配置失败([`AdoptError::Game`])。
|
||||
pub fn adopt(
|
||||
game: &GameLayout,
|
||||
launcher: &LauncherLayout,
|
||||
request: &AdoptRequest,
|
||||
) -> Result<AdoptOutcome, AdoptError> {
|
||||
let plan = plan(game, launcher, request)?;
|
||||
let mut dir_created = false;
|
||||
// 目录先建:建不出来就一个配置都不写(失败的残留是一个空目录,可复用)。
|
||||
if plan.target == AdoptTarget::InstanceDir && !plan.run_dir.is_dir() {
|
||||
std::fs::create_dir_all(&plan.run_dir)
|
||||
.map_err(|error| AdoptError::Game(crate::game::GameError::io(&plan.run_dir, error)))?;
|
||||
dir_created = true;
|
||||
// 建完再核一次:`create_dir_all` 会沿已存在的目录联接走,越过边界就不算成功。
|
||||
ensure_inside_data(launcher, &plan.run_dir)?;
|
||||
}
|
||||
let settings = InstanceSettings {
|
||||
isolation: Some(plan.isolation),
|
||||
game_dir: match &plan.target {
|
||||
// `custom` 档必须有运行目录:缺省目录与用户目录都要落进 `gameDir`。
|
||||
AdoptTarget::InstanceDir | AdoptTarget::Custom(_) => Some(plan.run_dir.clone()),
|
||||
AdoptTarget::Shared | AdoptTarget::VersionDir => None,
|
||||
},
|
||||
};
|
||||
let registration = register_with(
|
||||
launcher,
|
||||
&plan.name,
|
||||
&plan.candidate.version_id,
|
||||
request.created_at.as_deref(),
|
||||
&settings,
|
||||
)?;
|
||||
Ok(AdoptOutcome {
|
||||
instance_id: registration.profile.id.as_str().to_owned(),
|
||||
name: registration.profile.name.clone(),
|
||||
version_id: registration.profile.version_id.clone(),
|
||||
config_path: registration.config_path,
|
||||
isolation: plan.isolation,
|
||||
target: plan.target,
|
||||
run_dir: plan.run_dir,
|
||||
created: registration.created,
|
||||
dir_created,
|
||||
notes: plan.notes,
|
||||
})
|
||||
}
|
||||
|
||||
/// 运行目录的派生(缺省落点复用整合包导入的 `<data>/instances/<实例目录名>`)。
|
||||
fn run_dir_of(
|
||||
game: &GameLayout,
|
||||
launcher: &LauncherLayout,
|
||||
version_id: &str,
|
||||
name: &str,
|
||||
target: &AdoptTarget,
|
||||
) -> Result<PathBuf, AdoptError> {
|
||||
match target {
|
||||
AdoptTarget::InstanceDir => {
|
||||
let dir = pack_dir::instance_dir(launcher, name);
|
||||
if directory_occupied(&dir) {
|
||||
return Err(AdoptError::TargetNotEmpty { path: dir });
|
||||
}
|
||||
// 数据区里**已有**的祖先不许是跑出数据根的链接/联接(junction 不需要管理员权限就能建)。
|
||||
ensure_inside_data(launcher, &dir)?;
|
||||
Ok(dir)
|
||||
}
|
||||
AdoptTarget::Shared => Ok(game.root().to_path_buf()),
|
||||
AdoptTarget::VersionDir => Ok(game.version_dir(version_id)),
|
||||
AdoptTarget::Custom(dir) => {
|
||||
if !dir.is_absolute() {
|
||||
return Err(AdoptError::TargetInvalid {
|
||||
detail: format!("--game-dir 需要绝对路径,收到 `{}`", dir.display()),
|
||||
});
|
||||
}
|
||||
if dir.as_os_str().is_empty() {
|
||||
return Err(AdoptError::TargetInvalid {
|
||||
detail: "运行目录为空".to_owned(),
|
||||
});
|
||||
}
|
||||
Ok(dir.clone())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 运行目录选择的后果说明(人读;CLI 与 GUI 共用同一份话术)。
|
||||
///
|
||||
/// `shared` / `version_dir` 必须**明确告知**:它们会把玩家数据写进别人的 `.minecraft`
|
||||
/// (D20 的 `isolated` 档运行目录就是 `versions/<id>/`)。
|
||||
#[must_use]
|
||||
pub fn target_notes(target: &AdoptTarget, run_dir: &Path) -> Vec<String> {
|
||||
match target {
|
||||
AdoptTarget::InstanceDir => vec![format!(
|
||||
"运行目录 = {}(ULL 数据区新建,与别人的 .minecraft 隔离;versions/libraries/assets 仍按 D20 恒共享,不复制)",
|
||||
run_dir.display()
|
||||
)],
|
||||
AdoptTarget::Shared => vec![format!(
|
||||
"运行目录 = 游戏根 {}(共享档):mods/saves/config 会落在别人的 .minecraft 里,与其它启动器共用;\
|
||||
要隔离请用缺省(ULL 数据区新目录)或 --isolation custom --game-dir <dir>",
|
||||
run_dir.display()
|
||||
)],
|
||||
AdoptTarget::VersionDir => vec![format!(
|
||||
"运行目录 = 版本目录 {}(版本隔离档):第一次启动会在这里新增 mods/saves/config/logs,\
|
||||
而这个目录是别的启动器的版本目录(不覆盖已有文件);要隔离请用缺省或 --isolation custom",
|
||||
run_dir.display()
|
||||
)],
|
||||
AdoptTarget::Custom(_) => vec![format!(
|
||||
"运行目录 = {}(用户指定;不新建、不改动其中已有内容)",
|
||||
run_dir.display()
|
||||
)],
|
||||
}
|
||||
}
|
||||
|
||||
/// 展示名:去空格,空串退回版本 id(与 `pack import` 的「名字不给就用包名」同一口径)。
|
||||
fn resolve_name(name: Option<&str>, version_id: &str) -> String {
|
||||
name.map(str::trim)
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| version_id.to_owned())
|
||||
}
|
||||
|
||||
/// 缺省运行目录必须**真的**落在启动器数据根之下(挡住「数据区里预先放了指向外面的目录联接」)。
|
||||
///
|
||||
/// 边界是 `<data>`(`<root>/.ULL/data`)而不是 `<data>/instances`:后者本身可能就是链接,
|
||||
/// 拿它当基准等于把「越界」当成「正常」。`<data>` 自己是链接是用户自己的迁移手法(D6 的数据目录
|
||||
/// 迁移就是整棵树搬走),那种情况允许——判据是「最终落点仍在**数据根解析后的位置**之内」。
|
||||
///
|
||||
/// **已知边界**:这是检查那一刻的判据;检查与 `create_dir_all` 之间被人换掉组件(TOCTOU)
|
||||
/// 本函数看不到——本命令不是并发/对抗入口。
|
||||
fn ensure_inside_data(launcher: &LauncherLayout, dir: &Path) -> Result<(), AdoptError> {
|
||||
let data = launcher.data();
|
||||
let Some(data_real) = canonical_existing(&data) else {
|
||||
// 连数据根都还不存在 ⇒ 不可能已经有指向外面的链接。
|
||||
return Ok(());
|
||||
};
|
||||
let Some(dir_real) = canonical_existing(dir) else {
|
||||
return Err(AdoptError::TargetInvalid {
|
||||
detail: format!("解析运行目录的真实位置失败:{}", dir.display()),
|
||||
});
|
||||
};
|
||||
if !dir_real.starts_with(&data_real) {
|
||||
return Err(AdoptError::TargetInvalid {
|
||||
detail: format!(
|
||||
"运行目录 {} 解析到 {},落在数据根 {} 之外:数据区里有指向外部的符号链接/目录联接,拒绝沿它写盘",
|
||||
dir.display(),
|
||||
dir_real.display(),
|
||||
data_real.display()
|
||||
),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 最近的**已存在**祖先的真实路径(目标本身可能还不存在)。
|
||||
fn canonical_existing(path: &Path) -> Option<PathBuf> {
|
||||
let mut probe = path.to_path_buf();
|
||||
loop {
|
||||
if std::fs::symlink_metadata(&probe).is_ok() {
|
||||
return probe.canonicalize().ok();
|
||||
}
|
||||
if !probe.pop() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 「这个目录已经有人在用」= 存在且非空(空目录是上次失败的残留,可复用)。
|
||||
fn directory_occupied(path: &Path) -> bool {
|
||||
std::fs::read_dir(path).is_ok_and(|mut entries| entries.next().is_some())
|
||||
}
|
||||
Reference in new issue
Block a user