okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-022-int' into f-022-intfix67bb56bd1

main
6.6 KiB112 linesraw
1/**
2 * Where the person's models go: what a picked folder means (0.2.2).
3 *
4 * - A drive on its own (D:\ or /) is never filled with model files: it becomes D:\Strata (the data folder) and D:\Strata\Models (the
5 *   model library), which the person is told.
6 * - The data folder is the person's own choice, so it is written into the settings file Strata Control reads (`data_dir`). Control's
7 *   installer accepts a data folder that is that setting, whatever the folder is called; for a folder it has not been told about it wants a
8 *   name starting with "Strata" (a rule against an AI tool filling an arbitrary folder, tools/strata_mcp.py check_data_dir).
9 * - The link that makes `<data>/models` and `<data>/Models` one folder is only needed where the file system tells them apart; where it cannot be
10 *   made (exFAT, FAT, a network share) the models simply go in `<data>/models`.
11 */
12
13import { existsSync, mkdirSync, readFileSync, renameSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
14import { homedir } from 'node:os';
15import { dirname, join, parse, resolve } from 'node:path';
16
17export const isDriveRoot = path => { const p = resolve(path); return p === parse(p).root; };
18
19/** The data folder for a picked folder: a drive root gets a `Strata` folder of its own. `{ path, note }`. */
20export function dataFolderFromPick(picked) {
21  const path = resolve(picked);
22  if (!isDriveRoot(path)) return { path, note: null };
23  const target = join(path, 'Strata');
24  return { path: target, note: `${path} is a whole drive, so the models go in ${target}.` };
25}
26
27/** The model library folder for a picked folder: a drive root gets `Strata/Models`. `{ path, note }`. */
28export function libraryFolderFromPick(picked) {
29  const path = resolve(picked);
30  if (!isDriveRoot(path)) return { path, note: null };
31  const target = join(path, 'Strata', 'Models');
32  return { path: target, note: `${path} is a whole drive, so the models go in ${target}.` };
33}
34
35/** Make a folder the person asked for; a refusal of the disk is said in words. */
36export function makeFolder(path) {
37  try { mkdirSync(path, { recursive: true }); }
38  catch (error) { throw new Error(`Strata could not create ${path} (${error.code === 'EACCES' || error.code === 'EPERM' ? 'access was denied' : error.code === 'ENOSPC' ? 'the drive is full' : error.message}). Choose another folder.`); }
39  return path;
40}
41
42/** `models` beside `Models`: a link where the two are different names. A disk that cannot hold the link gets a plain `models` folder instead. */
43export function alignModels(data, library, { link = symlinkSync } = {}) {
44  const models = join(data, 'models');
45  if (existsSync(models)) return { data, linked: false };
46  try { link(process.platform === 'win32' ? library : 'Models', models, process.platform === 'win32' ? 'junction' : 'dir'); return { data, linked: true }; }
47  catch { /* exFAT, FAT, NFS, a share: no links there */ }
48  try { mkdirSync(models, { recursive: true }); } catch { /* the install says what it cannot write */ }
49  return { data, linked: false };
50}
51
52
53function readSettings(file) {
54  try { const parsed = JSON.parse(readFileSync(file, 'utf8').replace(/^/, '')); return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}; } catch { return {}; }
55}
56
57/** The data folder a settings file names and when it was last changed (`data_dir_at`, seconds; the file's own time for a file that has none). */
58export function readDataFolder(file) {
59  if (!file) return null;
60  const current = readSettings(file);
61  if (typeof current.data_dir !== 'string' || !current.data_dir) return null;
62  let at = Number(current.data_dir_at);
63  if (!Number.isFinite(at) || at <= 0) { try { at = statSync(file).mtimeMs / 1000; } catch { at = 0; } }
64  return { folder: current.data_dir, at };
65}
66
67/** The settings file the Terminal (command-line Strata) keeps: the same place setup.py and strata_control/discovery.py use. */
68export function terminalSettingsFile(env = process.env, platform = process.platform) {
69  if (env.STRATA_TERMINAL_SETTINGS_FILE) return env.STRATA_TERMINAL_SETTINGS_FILE;
70  if (platform === 'win32') return join(env.APPDATA || join(homedir(), 'AppData', 'Roaming'), 'Strata', 'settings.json');
71  return join(env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'strata', 'settings.json');
72}
73
74/** Write the person's data folder into a settings file (merged, atomically) with the time of the change; returns whether it changed. Never
75 *  throws: the folder still works for the app, only the Terminal and the installer's own check lose the shared setting. */
76export function rememberDataFolder(file, folder, at = Date.now() / 1000, touch = false) {
77  if (!file || !folder) return false;
78  try {
79    const current = readSettings(file);
80    if (current.data_dir === folder && !touch) return false;
81    mkdirSync(dirname(file), { recursive: true });
82    const temp = `${file}.${process.pid}.tmp`;
83    writeFileSync(temp, JSON.stringify({ ...current, data_dir: folder, data_dir_at: at }, null, 1) + '\n', { mode: 0o600 });
84    renameSync(temp, file);
85    return true;
86  } catch { return false; }
87}
88
89const same = (a, b) => resolve(a).toLowerCase() === resolve(b).toLowerCase();
90
91/**
92 * One models folder for the app and the Terminal. The app keeps its choice in its own settings file (`appFile`), the Terminal in `terminalFile`;
93 * whichever was changed last wins and the other file is brought up to date. Nothing is moved. A folder that is gone (a disk that is not
94 * connected) is never adopted. `app` is the app's own answer when its file names none (`{ folder, at }`).
95 * Returns `{ folder, from }`: the shared folder (null when neither names one) and `from` = 'terminal' when the app has to take over the
96 * Terminal's folder, 'app' when the Terminal's file was updated, null when nothing changed.
97 */
98export function syncDataFolder({ appFile, terminalFile, app = null, exists = path => existsSync(path) }) {
99  const mine = readDataFolder(appFile) ?? app;
100  const theirs = readDataFolder(terminalFile);
101  const theirsUsable = theirs && exists(theirs.folder);
102  if (!theirsUsable) {
103    if (mine && theirs && !same(mine.folder, theirs.folder)) { rememberDataFolder(terminalFile, mine.folder, mine.at); return { folder: mine.folder, from: 'app' }; }
104    return { folder: mine?.folder ?? null, from: null };
105  }
106  if (!mine || (!same(mine.folder, theirs.folder) && theirs.at > mine.at)) {
107    rememberDataFolder(appFile, theirs.folder, theirs.at);
108    return { folder: theirs.folder, from: 'terminal' };
109  }
110  if (!same(mine.folder, theirs.folder)) { rememberDataFolder(terminalFile, mine.folder, mine.at); return { folder: mine.folder, from: 'app' }; }
111  return { folder: mine.folder, from: null };
112}