Merge f-022-modelsdir: the app and the Terminal share one models folder

This commit is contained in:
Niko1221 committed 2026-10-20 15:33:01 +02:00
commit c23a4a5827
6 files changed
+253 -21

No files matched your search

+55 -8
View File
@@ -10,7 +10,8 @@
* made (exFAT, FAT, a network share) the models simply go in `<data>/models`.
*/
import { existsSync, mkdirSync, readFileSync, renameSync, symlinkSync, writeFileSync } from 'node:fs';
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { dirname, join, parse, resolve } from 'node:path';
export const isDriveRoot = path => { const p = resolve(path); return p === parse(p).root; };
@@ -48,18 +49,64 @@ export function alignModels(data, library, { link = symlinkSync } = {}) {
return { data, linked: false };
}
/** Write the person's data folder into the Control settings file (merged, atomically); returns whether it changed. Never throws: the folder
* still works for the app, only the Terminal and the installer's own check lose the shared setting. */
export function rememberDataFolder(file, folder) {
function readSettings(file) {
try { const parsed = JSON.parse(readFileSync(file, 'utf8').replace(/^/, '')); return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}; } catch { return {}; }
}
/** 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). */
export function readDataFolder(file) {
if (!file) return null;
const current = readSettings(file);
if (typeof current.data_dir !== 'string' || !current.data_dir) return null;
let at = Number(current.data_dir_at);
if (!Number.isFinite(at) || at <= 0) { try { at = statSync(file).mtimeMs / 1000; } catch { at = 0; } }
return { folder: current.data_dir, at };
}
/** The settings file the Terminal (command-line Strata) keeps: the same place setup.py and strata_control/discovery.py use. */
export function terminalSettingsFile(env = process.env, platform = process.platform) {
if (env.STRATA_TERMINAL_SETTINGS_FILE) return env.STRATA_TERMINAL_SETTINGS_FILE;
if (platform === 'win32') return join(env.APPDATA || join(homedir(), 'AppData', 'Roaming'), 'Strata', 'settings.json');
return join(env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'strata', 'settings.json');
}
/** Write the person's data folder into a settings file (merged, atomically) with the time of the change; returns whether it changed. Never
* throws: the folder still works for the app, only the Terminal and the installer's own check lose the shared setting. */
export function rememberDataFolder(file, folder, at = Date.now() / 1000, touch = false) {
if (!file || !folder) return false;
try {
let current = {};
try { const parsed = JSON.parse(readFileSync(file, 'utf8').replace(/^\uFEFF/, '')); if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) current = parsed; } catch { /* a new file */ }
if (current.data_dir === folder) return false;
const current = readSettings(file);
if (current.data_dir === folder && !touch) return false;
mkdirSync(dirname(file), { recursive: true });
const temp = `${file}.${process.pid}.tmp`;
writeFileSync(temp, JSON.stringify({ ...current, data_dir: folder }, null, 1) + '\n', { mode: 0o600 });
writeFileSync(temp, JSON.stringify({ ...current, data_dir: folder, data_dir_at: at }, null, 1) + '\n', { mode: 0o600 });
renameSync(temp, file);
return true;
} catch { return false; }
}
const same = (a, b) => resolve(a).toLowerCase() === resolve(b).toLowerCase();
/**
* One models folder for the app and the Terminal. The app keeps its choice in its own settings file (`appFile`), the Terminal in `terminalFile`;
* 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
* connected) is never adopted. `app` is the app's own answer when its file names none (`{ folder, at }`).
* Returns `{ folder, from }`: the shared folder (null when neither names one) and `from` = 'terminal' when the app has to take over the
* Terminal's folder, 'app' when the Terminal's file was updated, null when nothing changed.
*/
export function syncDataFolder({ appFile, terminalFile, app = null, exists = path => existsSync(path) }) {
const mine = readDataFolder(appFile) ?? app;
const theirs = readDataFolder(terminalFile);
const theirsUsable = theirs && exists(theirs.folder);
if (!theirsUsable) {
if (mine && theirs && !same(mine.folder, theirs.folder)) { rememberDataFolder(terminalFile, mine.folder, mine.at); return { folder: mine.folder, from: 'app' }; }
return { folder: mine?.folder ?? null, from: null };
}
if (!mine || (!same(mine.folder, theirs.folder) && theirs.at > mine.at)) {
rememberDataFolder(appFile, theirs.folder, theirs.at);
return { folder: theirs.folder, from: 'terminal' };
}
if (!same(mine.folder, theirs.folder)) { rememberDataFolder(terminalFile, mine.folder, mine.at); return { folder: mine.folder, from: 'app' }; }
return { folder: mine.folder, from: null };
}
+4 -2
View File
@@ -14,7 +14,7 @@ import os from 'node:os';
import { runtimeVision } from './native-vision.mjs';
import { componentsDirectory, installerEnvironment, controlEnvironment } from './control-runtime.mjs';
import { createEngineStep } from './engine-step.mjs';
import { dataFolderFromPick, isDriveRoot, makeFolder, rememberDataFolder } from './model-folder.mjs';
import { dataFolderFromPick, isDriveRoot, makeFolder, rememberDataFolder, syncDataFolder, terminalSettingsFile } from './model-folder.mjs';
import { createAutoTune, writeTuneConfig } from './native-autotune.mjs';
import { plainError, PHASE_TEXT } from './update-messages.mjs';
import { checkRunConfig, describeIssues } from './run-config-check.mjs';
@@ -75,6 +75,8 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
function installRoot(){const found=[preferences.installDir].find(d=>d&&existsSync(d));if(found)return realpathSync(found);mkdirSync(defaultInstall(),{recursive:true});return realpathSync(defaultInstall());}
/* The settings file Strata Control and the installer read (control-runtime.mjs sets STRATA_SETTINGS_FILE to it): the app's data folder is written there. */
function controlSettingsFile(){return process.env.STRATA_SETTINGS_FILE||join(dirname(componentsDirectory()),'app-settings.json');}
/* One models folder for the app and the Terminal: the one changed last wins and the other settings file is updated (nothing is moved). */
function shareDataFolder(){if(!packaged)return;try{let at=0;if(preferences.downloadDirectory)try{at=statSync(settingsPath).mtimeMs/1000;}catch{/* no file yet */}const found=syncDataFolder({appFile:controlSettingsFile(),terminalFile:terminalSettingsFile(),app:preferences.downloadDirectory?{folder:preferences.downloadDirectory,at}:null});if(found.from==='terminal'&&found.folder&&found.folder!==preferences.downloadDirectory){preferences={...preferences,downloadDirectory:found.folder};writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});}}catch{/* the shared setting is a convenience: never stop the app */}}
function repo(){if(packaged)return installRoot();const path=realpathSync(preferences.repo);if(!existsSync(join(path,'setup.py'))||!existsSync(join(path,'tools/strata_mcp.py'))||!existsSync(join(path,'serve/server.py')))throw new Error('Choose the Strata repository folder containing setup.py and tools/strata_mcp.py.');return path;}
function python(){return resolvePython({repo:preferences.repo});}
function send(method,params,timeout=30000){return new Promise((resolve,reject)=>{const id=++seq;const alarm=setTimeout(()=>{pending.delete(id);reject(new Error('The native engine did not respond in time. Check engine logs.'));},timeout);pending.set(id,{resolve,reject,alarm});child.stdin.write(JSON.stringify({jsonrpc:'2.0',id,method,params})+'\n');});}
@@ -124,7 +126,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
refreshing=(async()=>{try{const [catalog,status]=packaged?await (async()=>{const s=await tool('strata_status',{hardware:true});const c=await tool('strata_models').catch(error=>({families:[],contexts:[],recommendation:{family:null,model:null},context_note:'',error:error.message}));return [c,s];})():await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);let visionReader=false;if(packaged){try{const e=await control.engine();const root=e?.engine?.root??(e?.engine?.exe?dirname(e.engine.exe):'');visionReader=!!root&&['strata-vision','strata-vision.exe'].some(n=>existsSync(join(root,n)));}catch{visionReader=false;}}const markImages=c=>c&&Array.isArray(c.families)?{...c,families:c.families.map(f=>({...f,imagesCapable:!!f.images,images:!!f.images&&visionReader,sizes:(f.sizes??[]).map(s=>({...s,imagesCapable:!!s.images,images:!!s.images&&visionReader}))}))}:c;snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog:markEngine(packaged?markImages(catalog):catalog,status.engine),engineInfo:{version:status.engine?.version??null,source:status.engine?.source??null},visionReader:packaged?visionReader:true,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine,installerError:status.installerError}:{})};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});const run=refreshing;if(!force&&snapshot.available){run.catch(()=>{});return state();}return run;
}
function configure({repository}){if(packaged){if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));if(!statSync(next).isDirectory())throw new Error('Choose the folder that holds your Strata model configurations.');preferences={...preferences,installDir:next};packagedInstall=null;disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));const old=preferences;preferences={...preferences,repo:next};try{repo();}catch(e){preferences=old;throw e;}disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}
function setDownloadDirectory(input){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');let path;try{path=realpathSync(input.trim());}catch{throw new Error('That folder does not exist. Check the path, or that the drive is connected.');}if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');/* A whole drive (D:\) is not filled with models: D:\Strata is made and used. */if(isDriveRoot(path)){const own=dataFolderFromPick(path).path;makeFolder(own);path=realpathSync(own);}try{accessSync(path,constants.R_OK|constants.W_OK);}catch{throw new Error('Strata cannot write in that folder. Choose a folder you can save files in.');}preferences={...preferences,downloadDirectory:path};/* the same choice for the installer and the Terminal: the Control settings file */if(packaged)rememberDataFolder(controlSettingsFile(),path);writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});emit();return state();}
function setDownloadDirectory(input){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');let path;try{path=realpathSync(input.trim());}catch{throw new Error('That folder does not exist. Check the path, or that the drive is connected.');}if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');/* A whole drive (D:\) is not filled with models: D:\Strata is made and used. */if(isDriveRoot(path)){const own=dataFolderFromPick(path).path;makeFolder(own);path=realpathSync(own);}try{accessSync(path,constants.R_OK|constants.W_OK);}catch{throw new Error('Strata cannot write in that folder. Choose a folder you can save files in.');}preferences={...preferences,downloadDirectory:path};/* the same choice for the installer and the Terminal: the Control settings file */if(packaged)rememberDataFolder(controlSettingsFile(),path,Date.now()/1000,true);writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});shareDataFolder();emit();return state();}
function recordFile(model){if(!safeId(model))throw new Error('Choose an installed model.');const entry=snapshot.installed?.models?.find(i=>i.model===model);if(!entry)throw new Error('This model is not installed. Download and prepare it first.');const path=realpathSync(entry.configPath??join(repo(),entry.config));if(dirname(path)!==repo()||!/^strata-[a-z0-9_-]+\.json$/i.test(basename(path)))throw new Error('The model configuration is outside the Strata installation.');return {entry,path};}
function record(model){const {entry,path}=recordFile(model);return {entry,path,config:readJson(path)};}
/* The text file a power user edits by hand: where it is and what is wrong in it (run-config-check.mjs). */
+39 -3
View File
@@ -5,7 +5,7 @@ import { fileURLToPath } from 'node:url';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, parse } from 'node:path';
import { alignModels, dataFolderFromPick, isDriveRoot, libraryFolderFromPick, makeFolder, rememberDataFolder } from '../server/model-folder.mjs';
import { alignModels, dataFolderFromPick, isDriveRoot, libraryFolderFromPick, makeFolder, rememberDataFolder, syncDataFolder, readDataFolder, terminalSettingsFile } from '../server/model-folder.mjs';
import { nativeFixture } from './helpers/native-fixture.mjs';
const scratch = t => { const dir = realpathSync(mkdtempSync(join(tmpdir(), 'strata-folder-'))); t.after(() => rmSync(dir, { recursive: true, force: true })); return dir; };
@@ -46,10 +46,10 @@ test('models and Models are one folder; a disk that cannot hold the link gets a
test('the data folder is written into the Control settings file, merged and only when it changes', t => {
const dir = scratch(t), file = join(dir, 'config', 'app-settings.json');
assert.equal(rememberDataFolder(file, 'D:\\Strata'), true);
assert.deepEqual(JSON.parse(readFileSync(file, 'utf8')), { data_dir: 'D:\\Strata' });
assert.equal(JSON.parse(readFileSync(file, 'utf8')).data_dir, 'D:\\Strata');
writeFileSync(file, JSON.stringify({ installs: ['C:\\x'], data_dir: 'C:\\old' }));
assert.equal(rememberDataFolder(file, 'D:\\Strata'), true);
assert.deepEqual(JSON.parse(readFileSync(file, 'utf8')), { installs: ['C:\\x'], data_dir: 'D:\\Strata' });
assert.deepEqual(JSON.parse(readFileSync(file, 'utf8')).installs, ['C:\\x']);
assert.equal(rememberDataFolder(file, 'D:\\Strata'), false);
writeFileSync(file, '\uFEFF{"data_dir":"E:\\\\Strata","installs":[]}');
assert.equal(rememberDataFolder(file, 'E:\\Strata'), false);
@@ -97,3 +97,39 @@ test('Windows: the model library on a whole drive goes to X:\\Strata\\Models', {
assert.equal(run.stdout.trim().toLowerCase(), `${drive}Strata\\Models`.toLowerCase());
assert.equal(existsSync(join(dir, 'Strata', 'Models')), true);
});
test('the app and the Terminal share one models folder: the one changed last wins, the other file follows, nothing moves', t => {
const dir = scratch(t), appFile = join(dir, 'app-settings.json'), terminalFile = join(dir, 'roaming', 'settings.json');
const c = join(dir, 'on-c'), d = join(dir, 'on-d');
mkdirSync(c); mkdirSync(d);
const seed = (file, folder, at) => { mkdirSync(join(file, '..'), { recursive: true }); writeFileSync(file, JSON.stringify({ data_dir: folder, data_dir_at: at, installs: ['keep'] })); };
// the Terminal chose D: after the app chose C:
seed(appFile, c, 1000); seed(terminalFile, d, 2000);
assert.deepEqual(syncDataFolder({ appFile, terminalFile }), { folder: d, from: 'terminal' });
assert.deepEqual(readDataFolder(appFile), { folder: d, at: 2000 });
assert.deepEqual(JSON.parse(readFileSync(appFile, 'utf8')).installs, ['keep']);
assert.deepEqual(syncDataFolder({ appFile, terminalFile }), { folder: d, from: null });
// the app chose C: later
seed(appFile, c, 3000);
assert.deepEqual(syncDataFolder({ appFile, terminalFile }), { folder: c, from: 'app' });
assert.deepEqual(readDataFolder(terminalFile), { folder: c, at: 3000 });
// the Terminal has none: nothing is written there; the app has none: it takes the Terminal's
const lone = join(dir, 'lone.json');
assert.deepEqual(syncDataFolder({ appFile: join(dir, 'none.json'), terminalFile: lone }), { folder: null, from: null });
assert.equal(existsSync(lone), false);
seed(lone, d, 10);
assert.deepEqual(syncDataFolder({ appFile: join(dir, 'none.json'), terminalFile: lone }), { folder: d, from: 'terminal' });
// the app's preference (native-host.json) counts when its file names none
assert.deepEqual(syncDataFolder({ appFile: join(dir, 'none2.json'), terminalFile: lone, app: { folder: c, at: 99 } }), { folder: c, from: 'app' });
// a Terminal folder on a disk that is not there is never adopted
seed(terminalFile, join(dir, 'unplugged'), 9999); seed(appFile, c, 5);
assert.deepEqual(syncDataFolder({ appFile, terminalFile }), { folder: c, from: 'app' });
assert.equal(readdirSyncSafe(c), 0);
});
const readdirSyncSafe = folder => execFileSync(process.execPath, ['-e', `console.log(require('fs').readdirSync(${JSON.stringify(folder)}).length)`]).toString().trim() * 1;
test('the Terminal settings file is where setup.py and Control keep it', () => {
assert.equal(terminalSettingsFile({ APPDATA: 'C:\R' }, 'win32'), join('C:\R', 'Strata', 'settings.json'));
assert.equal(terminalSettingsFile({ XDG_CONFIG_HOME: '/x' }, 'linux'), join('/x', 'strata', 'settings.json'));
assert.equal(terminalSettingsFile({ STRATA_TERMINAL_SETTINGS_FILE: '/t.json' }, 'linux'), '/t.json');
});
+2
View File
@@ -5383,6 +5383,8 @@ def load_settings() -> dict:
def save_settings(s: dict) -> None:
if s.get("data_dir") and s.get("data_dir") != load_settings().get("data_dir"):
s = {**s, "data_dir_at": time.time()} # when the models folder was chosen: the app and the Terminal keep the newer choice
try:
settings_path().parent.mkdir(parents=True, exist_ok=True)
settings_path().write_text(json.dumps(s, indent=1), encoding="utf-8")
+62 -8
View File
@@ -202,25 +202,79 @@ def find_install(*, here: Path | None = None, explicit: str | os.PathLike | None
# ----------------------------------------------------------------------------------------------- the data folder
def _data_dir_entry(file: Path) -> tuple[str, float] | None:
"""(the data folder a settings file names, when it was last changed): ``data_dir_at`` (seconds), else the file's own time."""
data = _read_json(file)
folder = data.get("data_dir")
if not isinstance(folder, str) or not folder:
return None
at = data.get("data_dir_at")
if isinstance(at, bool) or not isinstance(at, (int, float)) or at <= 0:
try:
at = file.stat().st_mtime
except OSError:
at = 0.0
return folder, float(at)
def _same(a: str, b: str) -> bool:
return os.path.normcase(os.path.abspath(a)) == os.path.normcase(os.path.abspath(b))
def _write_data_dir(file: Path, folder: str, at: float) -> bool:
"""Merge the data folder and its time into a settings file (atomic). False when the disk refuses; never raises."""
try:
current = _read_json(file)
current["data_dir"], current["data_dir_at"] = folder, at
file.parent.mkdir(parents=True, exist_ok=True)
temp = file.with_name(f"{file.name}.{os.getpid()}.tmp")
temp.write_text(json.dumps(current, indent=1), encoding="utf-8")
os.replace(temp, file)
return True
except OSError:
return False
def sync_data_dir(*, environ=None, windows: bool | None = None, home: Path | None = None) -> tuple[Path, str] | None:
"""One models folder for the Terminal and the desktop app. The Terminal's settings file and the app's (``app-settings.json``) each name
a data folder; when they disagree the one changed last wins and the other file is updated. Nothing is moved. Returns (folder, source of
the winner) or None when neither names one. The app's own processes never call this (the app syncs from its host)."""
environ = os.environ if environ is None else environ
if in_app_mode(environ):
return None
mine_file = own_settings_file(environ, windows=windows, home=home)
app_file = app_settings_file(environ, windows=windows, home=home)
mine, app = _data_dir_entry(mine_file), _data_dir_entry(app_file)
if mine and app and not _same(mine[0], app[0]):
newer, older_file, source = (mine, app_file, "settings") if mine[1] >= app[1] else (app, mine_file, "app")
if source == "app" and not Path(app[0]).is_dir(): # a disk that is not connected is never adopted
return Path(mine[0]), "settings"
_write_data_dir(older_file, newer[0], newer[1])
return Path(newer[0]), source
if mine:
return Path(mine[0]), "settings"
return (Path(app[0]), "app") if app else None
def data_dir_choices(*, environ=None, windows: bool | None = None, home: Path | None = None) -> list[tuple[Path, str]]:
"""Candidate data folders with their source, best first (not checked for existence)."""
environ = os.environ if environ is None else environ
out: list[tuple[Path, str]] = []
own = _read_json(own_settings_file(environ, windows=windows, home=home)).get("data_dir")
if isinstance(own, str) and own:
out.append((Path(own), "settings"))
own = _data_dir_entry(own_settings_file(environ, windows=windows, home=home))
app = None if in_app_mode(environ) else _data_dir_entry(app_settings_file(environ, windows=windows, home=home))
entries = [(Path(e[0]), src, e[1]) for e, src in ((own, "settings"), (app, "app")) if e]
entries.sort(key=lambda x: -x[2]) # the folder changed last first, whichever file it is in
out.extend((p, src) for p, src, _ in entries)
if not in_app_mode(environ):
app = _read_json(app_settings_file(environ, windows=windows, home=home)).get("data_dir")
if isinstance(app, str) and app:
out.append((Path(app), "app"))
for d in documents_dirs(environ, windows=windows, home=home):
out.append((d / "Strata", "documents"))
return out
def data_dir(default: Path, *, environ=None, windows: bool | None = None, home: Path | None = None) -> tuple[Path, str]:
"""(the data folder, source). The person's own setting wins; then the app's folder, then a ``Documents/Strata`` that holds models;
else `default`."""
"""(the data folder, source). Of the Terminal's own setting and the app's folder the one changed last wins (the other file is brought up
to date); then a ``Documents/Strata`` that holds models; else `default`."""
sync_data_dir(environ=environ, windows=windows, home=home)
choices = data_dir_choices(environ=environ, windows=windows, home=home)
for path, source in choices:
if source == "settings":
@@ -0,0 +1,91 @@
"""One models folder for the Terminal and the desktop app: the folder changed last wins, the other settings file is updated, nothing moves."""
from __future__ import annotations
import json
import os
import time
from pathlib import Path
import setup
from strata_control import discovery
from tests.terminal.test_discovery import GuiLayout
class SharedModelsFolder(GuiLayout):
def files(self):
mine = Path(os.environ["APPDATA"]) / "Strata" / "settings.json"
mine.parent.mkdir(parents=True, exist_ok=True)
return mine, discovery.app_settings_file()
def put(self, file: Path, folder: Path, at: float) -> None:
folder.mkdir(parents=True, exist_ok=True)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(json.dumps({"data_dir": str(folder), "data_dir_at": at, "installs": ["keep"]}))
def read(self, file: Path) -> dict:
return json.loads(file.read_text())
def test_the_terminal_choice_made_last_wins_and_the_app_file_follows(self):
mine, app = self.files()
old, new = self.base / "on-c", self.base / "on-d"
self.put(app, old, 1000)
self.put(mine, new, 2000)
self.assertEqual(discovery.data_dir(self.base / "default"), (new, "settings"))
self.assertEqual(Path(self.read(app)["data_dir"]), new)
self.assertEqual(self.read(app)["data_dir_at"], 2000)
self.assertEqual(self.read(app)["installs"], ["keep"]) # merged, not replaced
self.assertEqual(list(old.iterdir()), []) # nothing moved
def test_the_app_choice_made_last_wins_and_the_terminal_file_follows(self):
mine, app = self.files()
old, new = self.base / "on-c", self.base / "on-d"
self.put(mine, old, 1000)
self.put(app, new, 3000)
self.assertEqual(discovery.data_dir(self.base / "default")[0], new)
self.assertEqual(Path(self.read(mine)["data_dir"]), new)
self.assertEqual(self.read(mine)["data_dir_at"], 3000)
self.assertEqual(self.catalog().data_dir().resolve(), new.resolve())
def test_an_app_folder_on_a_disk_that_is_gone_is_not_adopted(self):
mine, app = self.files()
keep = self.base / "kept"
self.put(mine, keep, 1000)
gone = self.base / "unplugged"
app.write_text(json.dumps({"data_dir": str(gone), "data_dir_at": 5000}))
self.assertEqual(discovery.data_dir(self.base / "default"), (keep, "settings"))
self.assertEqual(Path(self.read(app)["data_dir"]), gone) # the app's file is left alone
def test_the_same_folder_in_both_changes_nothing(self):
mine, app = self.files()
folder = self.base / "same"
self.put(mine, folder, 1000)
self.put(app, folder, 2000)
before = app.read_bytes()
self.assertEqual(discovery.data_dir(self.base / "default")[0], folder)
self.assertEqual(app.read_bytes(), before)
def test_files_without_a_time_use_the_file_time(self):
mine, app = self.files()
old, new = self.base / "a", self.base / "b"
old.mkdir(), new.mkdir()
app.write_text(json.dumps({"data_dir": str(old)}))
os.utime(app, (time.time() - 500, time.time() - 500))
mine.write_text(json.dumps({"data_dir": str(new)}))
self.assertEqual(discovery.data_dir(self.base / "default")[0], new)
def test_the_apps_own_processes_do_not_sync(self):
mine, app = self.files()
self.put(mine, self.base / "t", 9000)
self.put(app, self.base / "a", 1000)
os.environ["STRATA_SETTINGS_FILE"] = str(app)
self.assertIsNone(discovery.sync_data_dir())
self.assertEqual(Path(self.read(app)["data_dir"]), self.base / "a")
def test_setup_stamps_a_changed_data_folder(self):
mine, _ = self.files()
setup.save_settings({"data_dir": str(self.base / "x")})
first = self.read(mine)["data_dir_at"]
self.assertGreater(first, 0)
time.sleep(0.02)
setup.save_settings({**self.read(mine), "installs": ["y"]}) # same folder: the time stays
self.assertEqual(self.read(mine)["data_dir_at"], first)