feat(launcher)!: manage multiple game copies
BREAKING CHANGE: The launcher stores copy registrations in copies.json. Installations recorded only in install.json must be registered again.
This commit is contained in:
1 parent
e41b73aaa3
commit
7d68dc0548
24 files changed
+408
-97
No files matched your search
@@ -5,7 +5,7 @@ import { app, dialog, shell, type BrowserWindow } from 'electron';
|
||||
import { zipSync } from 'fflate';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import { getSettings } from '../config/settings-store.ts';
|
||||
import { readInstallRecord } from '../install/install-record.ts';
|
||||
import { COPIES_FILENAME, readInstallRecord } from '../install/install-record.ts';
|
||||
import { LAUNCHER_LOG_FILES, launcherLogFolder } from './launcher-log.ts';
|
||||
|
||||
type ArchiveFiles = Record<string, Uint8Array>;
|
||||
@@ -35,7 +35,7 @@ export async function exportDiagnostics(window: BrowserWindow | null): Promise<{
|
||||
const files: ArchiveFiles = {};
|
||||
const userData = app.getPath('userData');
|
||||
await addFile(files, 'settings.json', join(userData, 'settings.json'));
|
||||
await addFile(files, 'install.json', join(userData, 'install.json'));
|
||||
await addFile(files, COPIES_FILENAME, join(userData, COPIES_FILENAME));
|
||||
const launcherLogs = launcherLogFolder();
|
||||
if ((await ifPresent(() => lstat(launcherLogs)))?.isDirectory()) {
|
||||
for (const name of LAUNCHER_LOG_FILES) {
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { InstallProgress, InstallRecord, InstallRequest, PatchCheck } from
|
||||
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
|
||||
import { inspectTargetFolder } from '../game-folder/inspect-target-folder.ts';
|
||||
import { copyPlannedFiles, planCopy, removeInterruptedCopy } from './copy-game.ts';
|
||||
import { writeInstallRecord } from './install-record.ts';
|
||||
import { requireAvailableCopy, writeInstallRecord } from './install-record.ts';
|
||||
import { checkPatches } from './patch-check.ts';
|
||||
import { backUpStockFiles, stockBackupPath } from './stock-backup.ts';
|
||||
|
||||
@@ -67,6 +67,7 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
|
||||
const gameFolder = request.method === 'copy' ? request.sourcePath : request.gamePath;
|
||||
const game = await requireGameFolder(gameFolder);
|
||||
const copyPath = request.method === 'copy' ? request.copyPath : request.gamePath;
|
||||
await requireAvailableCopy(request.id, copyPath, request.dataPath);
|
||||
|
||||
const target = request.method === 'copy' ? await inspectTargetFolder(copyPath, gameFolder) : null;
|
||||
if (target?.problem) throw new AppError('target_not_usable', { problem: target.problem });
|
||||
@@ -88,6 +89,9 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
|
||||
|
||||
report({ phase: 'recording', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
|
||||
const record: InstallRecord = {
|
||||
id: request.id,
|
||||
name: request.name,
|
||||
sourcePath: request.method === 'copy' ? request.sourcePath : null,
|
||||
method: request.method,
|
||||
copyPath,
|
||||
dataPath: request.dataPath,
|
||||
|
||||
@@ -1,36 +1,110 @@
|
||||
import { join } from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { realpath } from 'node:fs/promises';
|
||||
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
||||
import { app } from 'electron';
|
||||
import { InstallRecordSchema, type InstallRecord } from '@shared/schemas/install.ts';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import { CopiesSchema, type Copies, type InstallRecord } from '@shared/schemas/install.ts';
|
||||
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
|
||||
|
||||
/** The installed game copy, `<user data>/install.json`; null before the first installation. */
|
||||
export const COPIES_FILENAME = 'copies.json';
|
||||
const EMPTY: Copies = { formatVersion: 1, current: null, copies: [] };
|
||||
|
||||
let pending: Promise<void> = Promise.resolve();
|
||||
|
||||
function recordPath(): string {
|
||||
return join(app.getPath('userData'), 'install.json');
|
||||
return join(app.getPath('userData'), COPIES_FILENAME);
|
||||
}
|
||||
|
||||
async function readRegistry(): Promise<Copies> {
|
||||
return CopiesSchema.parse(await readJsonOr(recordPath(), EMPTY));
|
||||
}
|
||||
|
||||
export async function listCopies(): Promise<Copies> {
|
||||
try {
|
||||
return await readRegistry();
|
||||
} catch (error) {
|
||||
console.warn('[copies] could not read the copy registry:', error);
|
||||
return EMPTY;
|
||||
}
|
||||
}
|
||||
|
||||
export async function readInstallRecord(): Promise<InstallRecord | null> {
|
||||
let raw: unknown;
|
||||
try {
|
||||
raw = await readJsonOr(recordPath(), null);
|
||||
} catch (error) {
|
||||
console.warn('[install] install.json is unreadable:', error);
|
||||
return null;
|
||||
}
|
||||
if (raw === null) return null;
|
||||
const parsed = InstallRecordSchema.safeParse(raw);
|
||||
if (!parsed.success) {
|
||||
console.warn('[install] install.json did not validate:', parsed.error.issues);
|
||||
return null;
|
||||
}
|
||||
return parsed.data;
|
||||
const registry = await listCopies();
|
||||
return registry.copies.find(({ id }) => id === registry.current) ?? null;
|
||||
}
|
||||
|
||||
export function createCopyDraft(): { id: string; dataPath: string } {
|
||||
const id = randomUUID();
|
||||
return { id, dataPath: join(app.getPath('userData'), 'copies', id, 'data') };
|
||||
}
|
||||
|
||||
export async function requireAvailableCopy(id: string, copyPath: string, dataPath: string): Promise<void> {
|
||||
await requireUniquePaths(await readRegistry(), id, copyPath, dataPath);
|
||||
}
|
||||
|
||||
export async function writeInstallRecord(record: InstallRecord): Promise<void> {
|
||||
await writeJsonAtomic(recordPath(), InstallRecordSchema.parse(record));
|
||||
await changeRegistry(async (registry) => {
|
||||
await requireUniquePaths(registry, record.id, record.copyPath, record.dataPath);
|
||||
return { ...registry, current: record.id, copies: [...registry.copies, record] };
|
||||
});
|
||||
}
|
||||
|
||||
/** The data folder offered when the player does not choose one. */
|
||||
export function defaultDataPath(): string {
|
||||
return join(app.getPath('userData'), 'data');
|
||||
export function setCurrentCopy(id: string): Promise<Copies> {
|
||||
return changeRegistry((registry) => {
|
||||
if (!registry.copies.some((copy) => copy.id === id)) throw new AppError('copy_not_found');
|
||||
return { ...registry, current: id };
|
||||
});
|
||||
}
|
||||
|
||||
export function renameCopy(id: string, name: string): Promise<Copies> {
|
||||
return changeRegistry((registry) => {
|
||||
if (!registry.copies.some((copy) => copy.id === id)) throw new AppError('copy_not_found');
|
||||
return { ...registry, copies: registry.copies.map((copy) => copy.id === id ? { ...copy, name } : copy) };
|
||||
});
|
||||
}
|
||||
|
||||
/** Serialize writes so switching, renaming and completing an installation preserve each other. */
|
||||
function changeRegistry(change: (registry: Copies) => Promise<Copies> | Copies): Promise<Copies> {
|
||||
const operation = pending.then(async () => {
|
||||
try {
|
||||
const updated = CopiesSchema.parse(await change(await readRegistry()));
|
||||
await writeJsonAtomic(recordPath(), updated);
|
||||
return updated;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) throw error;
|
||||
console.error('[copies] could not update the copy registry:', error);
|
||||
throw new AppError('copies_write_failed');
|
||||
}
|
||||
});
|
||||
pending = operation.then(() => undefined, () => undefined);
|
||||
return operation;
|
||||
}
|
||||
|
||||
async function requireUniquePaths(registry: Copies, id: string, copyPath: string, dataPath: string): Promise<void> {
|
||||
const paths = await Promise.all([canonical(copyPath), canonical(dataPath)]);
|
||||
for (const existing of registry.copies) {
|
||||
const used = await Promise.all([canonical(existing.copyPath), canonical(existing.dataPath)]);
|
||||
if (id === existing.id || paths.some((path) => used.some((other) => overlaps(path, other)))) {
|
||||
throw new AppError('copy_location_in_use');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function overlaps(left: string, right: string): boolean {
|
||||
function contains(parent: string, child: string): boolean {
|
||||
const remainder = relative(parent, child);
|
||||
return !isAbsolute(remainder) && remainder !== '..' && !remainder.startsWith('..' + sep);
|
||||
}
|
||||
return contains(left, right) || contains(right, left);
|
||||
}
|
||||
|
||||
/** Resolve junctions in a path even when its final folders have yet to be made. */
|
||||
async function canonical(path: string): Promise<string> {
|
||||
const absolute = resolve(path);
|
||||
try {
|
||||
return await realpath(absolute);
|
||||
} catch {
|
||||
const parent = dirname(absolute);
|
||||
return parent === absolute ? absolute : join(await canonical(parent), relative(parent, absolute));
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ interface LaunchJob {
|
||||
readonly stop: AbortController;
|
||||
readonly report: (state: LaunchState) => void;
|
||||
done: Promise<void>;
|
||||
copyId?: string;
|
||||
}
|
||||
|
||||
let active: LaunchJob | null = null;
|
||||
@@ -30,7 +31,7 @@ export function getLaunchState(): LaunchState {
|
||||
|
||||
export function startLaunch(report: LaunchJob['report']): LaunchState {
|
||||
if (active) throw new AppError('launch_busy');
|
||||
const job = { stop: new AbortController(), report, done: Promise.resolve() };
|
||||
const job: LaunchJob = { stop: new AbortController(), report, done: Promise.resolve() };
|
||||
active = job;
|
||||
update(job, { phase: 'checking' });
|
||||
job.done = launch(job).catch((error: unknown) => {
|
||||
@@ -75,14 +76,15 @@ export async function openServerStatus(): Promise<void> {
|
||||
}
|
||||
|
||||
function update(job: LaunchJob, next: LaunchState): void {
|
||||
state = next;
|
||||
job.report(next);
|
||||
state = job.copyId ? { ...next, copyId: job.copyId } : next;
|
||||
job.report(state);
|
||||
}
|
||||
|
||||
async function launch(job: LaunchJob): Promise<void> {
|
||||
const signal = job.stop.signal;
|
||||
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
|
||||
if (!record) throw new AppError('launch_no_copy');
|
||||
job.copyId = record.id;
|
||||
if (!settings.developerMode) throw new AppError('launch_lab_required');
|
||||
if (isInSteamLibrary(record.copyPath)) throw new AppError('launch_copy_in_steam');
|
||||
const currentVersion = await readVersion(record.copyPath, signal);
|
||||
|
||||
Reference in new issue
Block a user