import { readdir, realpath, stat, statfs } from 'node:fs/promises'; import { dirname, parse, relative, resolve, isAbsolute } from 'node:path'; import { isInSteamLibrary } from '@wto/patcher'; import type { TargetFolderInspection } from '@shared/schemas/install.ts'; /** * Look at the folder the player chose for the game copy (install by copying): it must be new or * empty, must not overlap the stock installation, and the drive must have room. Only reads. */ export async function inspectTargetFolder(path: string, stockPath: string): Promise { const target = await canonical(path); const stock = await canonical(stockPath); return { path, problem: await targetProblem(target, stock), inSteamLibrary: isInSteamLibrary(target), freeBytes: await freeBytes(target), sameDriveAsStock: parse(target).root.toLowerCase() === parse(stock).root.toLowerCase(), }; } async function targetProblem(target: string, stock: string): Promise { if (contains(stock, target) || contains(target, stock)) return 'overlaps_stock'; let entries: string[]; try { const info = await stat(target); if (!info.isDirectory()) return 'not_a_folder'; entries = await readdir(target); } catch { return null; // does not exist yet: the copy creates it } return entries.length ? 'not_empty' : null; } /** Whether `inner` is `outer` or lies inside it. */ function contains(outer: string, inner: string): boolean { const path = relative(outer.toLowerCase(), inner.toLowerCase()); return path === '' || (!path.startsWith('..') && !isAbsolute(path)); } /** Free bytes on the drive of the nearest existing folder at or above `path`. */ async function freeBytes(path: string): Promise { for (let folder = path; ; folder = dirname(folder)) { try { const info = await statfs(folder); return info.bavail * info.bsize; } catch { if (dirname(folder) === folder) return null; } } } /** The real path of the nearest existing part, with the rest appended as given. */ async function canonical(path: string): Promise { const absolute = resolve(path); try { return await realpath(absolute); } catch { const parent = dirname(absolute); if (parent === absolute) return absolute; return resolve(await canonical(parent), relative(parent, absolute)); } }