claude-dev-env 8.119.0 → 8.119.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/git_hooks_installer.mjs +26 -2
- package/bin/git_hooks_installer.test.mjs +36 -0
- package/bin/install-transaction.mjs +3 -1
- package/bin/install.mjs +12 -8
- package/bin/install.test.mjs +89 -0
- package/bin/install.transaction.test.mjs +34 -0
- package/bin/merge_profile_settings.mjs +3 -2
- package/bin/merge_profile_settings.test.mjs +25 -1
- package/bin/profile-stop-gate.mjs +2 -1
- package/bin/profile-stop-gate.test.mjs +26 -1
- package/bin/write-file-atomically.mjs +148 -0
- package/bin/write-file-atomically.test.mjs +263 -0
- package/package.json +1 -1
|
@@ -18,12 +18,23 @@ export const SHIM_DOCSTRING = (
|
|
|
18
18
|
const RENAME_RETRY_DELAYS_MS = Object.freeze([50, 100, 200]);
|
|
19
19
|
|
|
20
20
|
|
|
21
|
-
|
|
21
|
+
/**
|
|
22
|
+
* Rename a file, retrying while Windows reports the destination as busy.
|
|
23
|
+
*
|
|
24
|
+
* A scanner or reader that holds the file open makes a Windows rename fail
|
|
25
|
+
* with EPERM or EBUSY for a moment. Each retry waits a little longer, and the
|
|
26
|
+
* last busy error is thrown once the waits run out.
|
|
27
|
+
*
|
|
28
|
+
* @param {string} sourcePath The file to move.
|
|
29
|
+
* @param {string} destinationPath The path it replaces.
|
|
30
|
+
* @returns {void}
|
|
31
|
+
*/
|
|
32
|
+
export function renameSyncRetryingWhileBusy(sourcePath, destinationPath) {
|
|
22
33
|
let lastError;
|
|
23
34
|
for (const delayMs of [0, ...RENAME_RETRY_DELAYS_MS]) {
|
|
24
35
|
if (delayMs > 0) {
|
|
25
36
|
const deadline = Date.now() + delayMs;
|
|
26
|
-
while (Date.now() < deadline) {
|
|
37
|
+
while (Date.now() < deadline) { }
|
|
27
38
|
}
|
|
28
39
|
try {
|
|
29
40
|
renameSync(sourcePath, destinationPath);
|
|
@@ -35,6 +46,19 @@ function renameSyncWithWindowsRetry(sourcePath, destinationPath) {
|
|
|
35
46
|
lastError = renameError;
|
|
36
47
|
}
|
|
37
48
|
}
|
|
49
|
+
throw lastError;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
function renameSyncWithWindowsRetry(sourcePath, destinationPath) {
|
|
54
|
+
try {
|
|
55
|
+
renameSyncRetryingWhileBusy(sourcePath, destinationPath);
|
|
56
|
+
return;
|
|
57
|
+
} catch (renameError) {
|
|
58
|
+
if (renameError.code !== 'EPERM' && renameError.code !== 'EBUSY') {
|
|
59
|
+
throw renameError;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
38
62
|
try {
|
|
39
63
|
renameSync(sourcePath, destinationPath);
|
|
40
64
|
return;
|
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
writeAllGitHookShims,
|
|
11
11
|
configureGlobalGitHooksPath,
|
|
12
12
|
KNOWN_GIT_HOOK_NAMES,
|
|
13
|
+
renameSyncRetryingWhileBusy,
|
|
13
14
|
} from './git_hooks_installer.mjs';
|
|
14
15
|
|
|
15
16
|
|
|
@@ -375,3 +376,38 @@ test('generated advisory shim preserves KeyboardInterrupt cancellation', () => {
|
|
|
375
376
|
assert.notEqual(shimResult.status, 0);
|
|
376
377
|
assert.match(shimResult.stderr, /KeyboardInterrupt/);
|
|
377
378
|
});
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
test('renameSyncRetryingWhileBusy should move the file over the destination', () => {
|
|
382
|
+
const { temporaryRoot, gitHooksDirectory } = makeTemporaryGitHooksDirectory();
|
|
383
|
+
try {
|
|
384
|
+
const sourcePath = join(gitHooksDirectory, 'next.tmp');
|
|
385
|
+
const destinationPath = join(gitHooksDirectory, 'current');
|
|
386
|
+
writeFileSync(sourcePath, 'next');
|
|
387
|
+
writeFileSync(destinationPath, 'prior');
|
|
388
|
+
|
|
389
|
+
renameSyncRetryingWhileBusy(sourcePath, destinationPath);
|
|
390
|
+
|
|
391
|
+
assert.equal(readFileSync(destinationPath, 'utf8'), 'next');
|
|
392
|
+
assert.equal(existsSync(sourcePath), false);
|
|
393
|
+
} finally {
|
|
394
|
+
rmSync(temporaryRoot, { recursive: true, force: true });
|
|
395
|
+
}
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
test('renameSyncRetryingWhileBusy should throw a missing source error without retrying it away', () => {
|
|
400
|
+
const { temporaryRoot, gitHooksDirectory } = makeTemporaryGitHooksDirectory();
|
|
401
|
+
try {
|
|
402
|
+
const destinationPath = join(gitHooksDirectory, 'current');
|
|
403
|
+
writeFileSync(destinationPath, 'prior');
|
|
404
|
+
|
|
405
|
+
assert.throws(
|
|
406
|
+
() => renameSyncRetryingWhileBusy(join(gitHooksDirectory, 'missing.tmp'), destinationPath),
|
|
407
|
+
(error) => error.code === 'ENOENT',
|
|
408
|
+
);
|
|
409
|
+
assert.equal(readFileSync(destinationPath, 'utf8'), 'prior');
|
|
410
|
+
} finally {
|
|
411
|
+
rmSync(temporaryRoot, { recursive: true, force: true });
|
|
412
|
+
}
|
|
413
|
+
});
|
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
lstatSync,
|
|
21
21
|
mkdirSync,
|
|
22
22
|
mkdtempSync,
|
|
23
|
+
readFileSync,
|
|
23
24
|
readdirSync,
|
|
24
25
|
readlinkSync,
|
|
25
26
|
rmdirSync,
|
|
@@ -31,6 +32,7 @@ import {
|
|
|
31
32
|
import { dirname, join } from 'node:path';
|
|
32
33
|
import { execFileSync } from 'node:child_process';
|
|
33
34
|
import { ADDITIONAL_SETTINGS_BLOB_PREFIX } from './install-constants.mjs';
|
|
35
|
+
import { writeFileAtomically } from './write-file-atomically.mjs';
|
|
34
36
|
|
|
35
37
|
/** Env var that forces a throw after a named mutation phase (tests only). */
|
|
36
38
|
export const INSTALL_FAULT_ENV = 'CLAUDE_DEV_ENV_INSTALL_FAULT';
|
|
@@ -341,7 +343,7 @@ export function restorePriorInstallSnapshot(snapshot, options = {}) {
|
|
|
341
343
|
for (const eachSnapshot of settingsSnapshots) {
|
|
342
344
|
if (eachSnapshot.existed) {
|
|
343
345
|
mkdir(dirname(eachSnapshot.path), { recursive: true });
|
|
344
|
-
|
|
346
|
+
writeFileAtomically(eachSnapshot.path, readFileSync(join(snapshot.journalRoot, eachSnapshot.blobName)));
|
|
345
347
|
} else if (exists(eachSnapshot.path)) {
|
|
346
348
|
try {
|
|
347
349
|
unlink(eachSnapshot.path);
|
package/bin/install.mjs
CHANGED
|
@@ -153,6 +153,7 @@ import {
|
|
|
153
153
|
unparsedSettingsMayHoldGate,
|
|
154
154
|
} from './profile-stop-gate.mjs';
|
|
155
155
|
import { pythonExecutableProbeCommand, pythonVersionMeetsFloor } from './python-probe.mjs';
|
|
156
|
+
import { writeFileAtomically } from './write-file-atomically.mjs';
|
|
156
157
|
|
|
157
158
|
const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
158
159
|
const INSTALL_ROOT_RESOLUTION = resolveInstallRoot({
|
|
@@ -523,7 +524,9 @@ function seedSubagentModelPolicy() {
|
|
|
523
524
|
* Cursor. The pstack plugin now carries the SessionStart context the companion
|
|
524
525
|
* supplied, so a registration left behind points every session at a deleted
|
|
525
526
|
* script. Every install clears all three hosts; an uninstall passes the two the
|
|
526
|
-
* settings block does not already own.
|
|
527
|
+
* settings block does not already own. An empty or blank configuration file
|
|
528
|
+
* holds no registration, so it is left as it is, the way the settings loader
|
|
529
|
+
* reads an empty settings.json as an empty object.
|
|
527
530
|
*
|
|
528
531
|
* @param {string[]} [hosts] The hosts to clear. Defaults to all three.
|
|
529
532
|
* @returns {string[]} The host configuration paths this run changed.
|
|
@@ -535,10 +538,11 @@ function removeRetiredSessionContinuityHooks(hosts = ['claude', 'codex', 'cursor
|
|
|
535
538
|
const configurationPath = configurationPaths[host];
|
|
536
539
|
if (!existsSync(configurationPath)) continue;
|
|
537
540
|
const configurationText = readFileSync(configurationPath, 'utf8');
|
|
541
|
+
if (!configurationText.trim()) continue;
|
|
538
542
|
const configuration = JSON.parse(configurationText);
|
|
539
543
|
if (removeContinuityHooks(configuration) === 0) continue;
|
|
540
544
|
const indent = hostConfigurationIndent(configurationText);
|
|
541
|
-
|
|
545
|
+
writeFileAtomically(configurationPath, JSON.stringify(configuration, null, indent) + '\n');
|
|
542
546
|
changedPaths.push(configurationPath);
|
|
543
547
|
console.log(` Session continuity: retired hook registrations removed from ${configurationPath}`);
|
|
544
548
|
}
|
|
@@ -2097,7 +2101,7 @@ export function pruneRetiredHookEntriesFromSettings(
|
|
|
2097
2101
|
);
|
|
2098
2102
|
if (removedCount === 0) return 0;
|
|
2099
2103
|
const settingsIndent = hostConfigurationIndent(settingsText);
|
|
2100
|
-
|
|
2104
|
+
writeFileAtomically(settingsPath, JSON.stringify(settings, null, settingsIndent) + '\n');
|
|
2101
2105
|
return removedCount;
|
|
2102
2106
|
}
|
|
2103
2107
|
|
|
@@ -2345,7 +2349,7 @@ function mergeHooksAtPath(
|
|
|
2345
2349
|
const groupCount = mergeHooksIntoSettings(
|
|
2346
2350
|
settings, hooksConfig, pluginRootDir, pythonCommand, realPathOrNull(settingsPath),
|
|
2347
2351
|
);
|
|
2348
|
-
|
|
2352
|
+
writeFileAtomically(settingsPath, JSON.stringify(settings, null, indentation) + '\n');
|
|
2349
2353
|
return groupCount;
|
|
2350
2354
|
}
|
|
2351
2355
|
|
|
@@ -2512,7 +2516,7 @@ function mergeManagedPermissions() {
|
|
|
2512
2516
|
|| mergeOutcome.addedCount > 0
|
|
2513
2517
|
|| (!settingsExisted && hasCurrentManagedPermissions);
|
|
2514
2518
|
if (shouldWriteSettings) {
|
|
2515
|
-
|
|
2519
|
+
writeFileAtomically(settingsPath, JSON.stringify(settings, null, 4) + '\n');
|
|
2516
2520
|
}
|
|
2517
2521
|
return { ...mergeOutcome, removedCount: pruneOutcome.removedCount };
|
|
2518
2522
|
}
|
|
@@ -2532,7 +2536,7 @@ function mergePackageSettingsDefaults() {
|
|
|
2532
2536
|
const settings = loadClaudeSettingsObject(settingsPath);
|
|
2533
2537
|
const mergeOutcome = mergeMissingSettingsDefaults(settings, settingsDefaults);
|
|
2534
2538
|
if (mergeOutcome.addedKeys.length > 0) {
|
|
2535
|
-
|
|
2539
|
+
writeFileAtomically(settingsPath, JSON.stringify(settings, null, 4) + '\n');
|
|
2536
2540
|
}
|
|
2537
2541
|
return mergeOutcome;
|
|
2538
2542
|
}
|
|
@@ -3649,7 +3653,7 @@ function pruneManagedHooksFromHostConfiguration(settingsPath, defaultIndentation
|
|
|
3649
3653
|
managedPackageSourceRoots(),
|
|
3650
3654
|
);
|
|
3651
3655
|
pruneManagedHooksFromSettings(settings, managedHookRelativePaths);
|
|
3652
|
-
|
|
3656
|
+
writeFileAtomically(
|
|
3653
3657
|
settingsPath,
|
|
3654
3658
|
JSON.stringify(settings, null, hostConfigurationIndent(settingsText) || defaultIndentation) + '\n',
|
|
3655
3659
|
);
|
|
@@ -3725,7 +3729,7 @@ function executeUninstallPlan(plan, helpers = {}) {
|
|
|
3725
3729
|
}
|
|
3726
3730
|
}
|
|
3727
3731
|
if (didSettingsChange) {
|
|
3728
|
-
|
|
3732
|
+
writeFileAtomically(plan.settingsPath, JSON.stringify(settings, null, 4) + '\n');
|
|
3729
3733
|
}
|
|
3730
3734
|
}
|
|
3731
3735
|
for (const eachChangedPath of removeOpenTasksGateFromProfiles({
|
package/bin/install.test.mjs
CHANGED
|
@@ -2514,6 +2514,70 @@ test('pruneRetiredHookEntriesFromSettings leaves settings.json byte-identical wh
|
|
|
2514
2514
|
});
|
|
2515
2515
|
|
|
2516
2516
|
|
|
2517
|
+
const FILE_SIZE_LIMIT_COMMAND = 'prlimit';
|
|
2518
|
+
const isFileSizeLimitAvailable = spawnSync(FILE_SIZE_LIMIT_COMMAND, ['--version']).status === 0;
|
|
2519
|
+
|
|
2520
|
+
|
|
2521
|
+
test(
|
|
2522
|
+
'a settings.json write that fails part way through leaves the prior settings.json whole',
|
|
2523
|
+
{ skip: isFileSizeLimitAvailable ? false : `${FILE_SIZE_LIMIT_COMMAND} is not on PATH` },
|
|
2524
|
+
() => {
|
|
2525
|
+
const settings = settingsRegisteringRetiredAndUserHooks(RETIRED_HOOK_RELATIVE_PATH);
|
|
2526
|
+
settings.userNotes = 'n'.repeat(8192);
|
|
2527
|
+
const { settingsPath, sandboxRoot } = createSettingsFixture(settings, 4);
|
|
2528
|
+
const pruneScriptPath = join(sandboxRoot, 'prune-under-limit.mjs');
|
|
2529
|
+
writeFileSync(pruneScriptPath, [
|
|
2530
|
+
`import { ownedHookRootComparisonKeys, pruneRetiredHookEntriesFromSettings } from ${JSON.stringify(new URL('./install.mjs', import.meta.url).href)};`,
|
|
2531
|
+
`const sandboxRoot = ${JSON.stringify(sandboxRoot)};`,
|
|
2532
|
+
`pruneRetiredHookEntriesFromSettings(${JSON.stringify(settingsPath)}, new Set([${JSON.stringify(RETIRED_HOOK_RELATIVE_PATH)}]), {`,
|
|
2533
|
+
` allOwnedHookRootKeys: ownedHookRootComparisonKeys([${JSON.stringify(join(sandboxRoot, '.claude', 'hooks'))}]),`,
|
|
2534
|
+
' homeDirectory: sandboxRoot,',
|
|
2535
|
+
'});',
|
|
2536
|
+
].join('\n'));
|
|
2537
|
+
try {
|
|
2538
|
+
const settingsTextBefore = readFileSync(settingsPath, 'utf8');
|
|
2539
|
+
const fileSizeLimitBytes = Math.floor(settingsTextBefore.length / 2);
|
|
2540
|
+
|
|
2541
|
+
const limitedRun = spawnSync(
|
|
2542
|
+
FILE_SIZE_LIMIT_COMMAND,
|
|
2543
|
+
[`--fsize=${fileSizeLimitBytes}`, process.execPath, pruneScriptPath],
|
|
2544
|
+
{ encoding: 'utf8', env: { ...process.env, HOME: sandboxRoot, USERPROFILE: sandboxRoot } },
|
|
2545
|
+
);
|
|
2546
|
+
|
|
2547
|
+
assert.notEqual(limitedRun.status, 0, 'the write past the file size limit fails the run');
|
|
2548
|
+
assert.match(limitedRun.stderr, /EFBIG/, 'the run fails on the file size limit');
|
|
2549
|
+
const settingsTextAfter = readFileSync(settingsPath, 'utf8');
|
|
2550
|
+
assert.equal(
|
|
2551
|
+
settingsTextAfter,
|
|
2552
|
+
settingsTextBefore,
|
|
2553
|
+
`expected settings.json to keep its prior ${settingsTextBefore.length} bytes after the failed write, found ${settingsTextAfter.length} bytes`,
|
|
2554
|
+
);
|
|
2555
|
+
assert.deepEqual(
|
|
2556
|
+
readdirSync(sandboxRoot).sort(),
|
|
2557
|
+
['prune-under-limit.mjs', 'settings.json'],
|
|
2558
|
+
'the failed write leaves no temporary file beside settings.json',
|
|
2559
|
+
);
|
|
2560
|
+
|
|
2561
|
+
const unlimitedRun = spawnSync(process.execPath, [pruneScriptPath], {
|
|
2562
|
+
encoding: 'utf8',
|
|
2563
|
+
env: { ...process.env, HOME: sandboxRoot, USERPROFILE: sandboxRoot },
|
|
2564
|
+
});
|
|
2565
|
+
|
|
2566
|
+
assert.equal(unlimitedRun.status, 0, unlimitedRun.stderr);
|
|
2567
|
+
const prunedSettings = JSON.parse(readFileSync(settingsPath, 'utf8'));
|
|
2568
|
+
assert.deepEqual(
|
|
2569
|
+
prunedSettings.hooks.PreToolUse[0].hooks.map(hook => hook.command),
|
|
2570
|
+
['python3 my_own_gate.py --user-authored'],
|
|
2571
|
+
'the next write completes and drops the retired entry',
|
|
2572
|
+
);
|
|
2573
|
+
assert.equal(prunedSettings.userNotes, settings.userNotes, 'the user key survives whole');
|
|
2574
|
+
} finally {
|
|
2575
|
+
rmSync(sandboxRoot, { recursive: true, force: true });
|
|
2576
|
+
}
|
|
2577
|
+
},
|
|
2578
|
+
);
|
|
2579
|
+
|
|
2580
|
+
|
|
2517
2581
|
const ALL_HOST_CONFIGURATION_INDENT_WIDTHS = [2, 4];
|
|
2518
2582
|
|
|
2519
2583
|
|
|
@@ -3789,6 +3853,31 @@ test('a full install clears a retired session-continuity registration from every
|
|
|
3789
3853
|
}
|
|
3790
3854
|
});
|
|
3791
3855
|
|
|
3856
|
+
test('should install over an empty settings.json and leave a settings object', t => {
|
|
3857
|
+
const sandbox = pstackPluginSandbox(t);
|
|
3858
|
+
const settingsPath = join(sandbox.homeDirectory, '.claude', 'settings.json');
|
|
3859
|
+
mkdirSync(dirname(settingsPath), { recursive: true });
|
|
3860
|
+
writeFileSync(settingsPath, '');
|
|
3861
|
+
|
|
3862
|
+
runPstackInstaller(sandbox.homeDirectory, [], sandbox.environment);
|
|
3863
|
+
|
|
3864
|
+
const settings = JSON.parse(readFileSync(settingsPath, 'utf8'));
|
|
3865
|
+
assert.equal(typeof settings.hooks, 'object');
|
|
3866
|
+
});
|
|
3867
|
+
|
|
3868
|
+
test('should refuse a settings.json that holds malformed JSON and leave it unchanged', t => {
|
|
3869
|
+
const sandbox = pstackPluginSandbox(t);
|
|
3870
|
+
const settingsPath = join(sandbox.homeDirectory, '.claude', 'settings.json');
|
|
3871
|
+
mkdirSync(dirname(settingsPath), { recursive: true });
|
|
3872
|
+
writeFileSync(settingsPath, '{ "hooks": ');
|
|
3873
|
+
|
|
3874
|
+
assert.throws(
|
|
3875
|
+
() => runPstackInstaller(sandbox.homeDirectory, [], sandbox.environment),
|
|
3876
|
+
error => error.status === 1,
|
|
3877
|
+
);
|
|
3878
|
+
assert.equal(readFileSync(settingsPath, 'utf8'), '{ "hooks": ');
|
|
3879
|
+
});
|
|
3880
|
+
|
|
3792
3881
|
function installWithGlobalPrefix(context, globalPrefix) {
|
|
3793
3882
|
const homeDirectory = mkdtempSync(join(tmpdir(), 'cde-action-needed-'));
|
|
3794
3883
|
context.after(() => rmSync(homeDirectory, { recursive: true, force: true }));
|
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
readFileSync,
|
|
13
13
|
realpathSync,
|
|
14
14
|
rmSync,
|
|
15
|
+
symlinkSync,
|
|
15
16
|
writeFileSync,
|
|
16
17
|
} from 'node:fs';
|
|
17
18
|
import { tmpdir } from 'node:os';
|
|
@@ -143,6 +144,39 @@ test('capture and restore recover settings, manifest, files, and hooksPath', ()
|
|
|
143
144
|
rmSync(box.root, { recursive: true, force: true });
|
|
144
145
|
});
|
|
145
146
|
|
|
147
|
+
test(
|
|
148
|
+
'restore should write the prior settings through a linked settings.json and keep the link',
|
|
149
|
+
{ skip: process.platform === 'win32' ? 'creating a file link on Windows needs a privilege the runner may lack' : false },
|
|
150
|
+
() => {
|
|
151
|
+
const box = sandbox();
|
|
152
|
+
const gitConfigPath = join(box.root, '.gitconfig');
|
|
153
|
+
writeFileSync(gitConfigPath, '');
|
|
154
|
+
const io = { env: { ...process.env, HOME: box.root, USERPROFILE: box.root, GIT_CONFIG_GLOBAL: gitConfigPath }, execFileSync };
|
|
155
|
+
const sharedSettingsPath = join(box.root, 'shared', 'settings.json');
|
|
156
|
+
writeFileWithParents(sharedSettingsPath, '{"prior":true}\n');
|
|
157
|
+
symlinkSync(sharedSettingsPath, box.settingsPath);
|
|
158
|
+
try {
|
|
159
|
+
const snapshot = capturePriorInstallSnapshot({
|
|
160
|
+
managedRoot: box.managedRoot,
|
|
161
|
+
manifestFilePath: box.manifestFilePath,
|
|
162
|
+
settingsPath: box.settingsPath,
|
|
163
|
+
priorManifestFiles: [],
|
|
164
|
+
journalParentDirectory: box.journalParent,
|
|
165
|
+
io,
|
|
166
|
+
});
|
|
167
|
+
writeFileSync(sharedSettingsPath, '{"hooks":{"broken":true}}\n');
|
|
168
|
+
|
|
169
|
+
restorePriorInstallSnapshot(snapshot, { allWrittenPaths: [box.settingsPath], io });
|
|
170
|
+
|
|
171
|
+
assert.equal(lstatSync(box.settingsPath).isSymbolicLink(), true, 'settings.json is still a link');
|
|
172
|
+
assert.equal(readFileSync(sharedSettingsPath, 'utf8'), '{"prior":true}\n');
|
|
173
|
+
discardInstallTransactionJournal(snapshot);
|
|
174
|
+
} finally {
|
|
175
|
+
rmSync(box.root, { recursive: true, force: true });
|
|
176
|
+
}
|
|
177
|
+
},
|
|
178
|
+
);
|
|
179
|
+
|
|
146
180
|
test('capture and restore recover an additional host settings file', () => {
|
|
147
181
|
const box = sandbox();
|
|
148
182
|
const gitConfigPath = join(box.root, '.gitconfig');
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
* every profile on this machine without writing anything.
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
|
-
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync
|
|
18
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync } from 'node:fs';
|
|
19
19
|
import { homedir } from 'node:os';
|
|
20
20
|
import { dirname, join, resolve } from 'node:path';
|
|
21
21
|
import { fileURLToPath } from 'node:url';
|
|
@@ -28,6 +28,7 @@ import {
|
|
|
28
28
|
normalizePathForComparison,
|
|
29
29
|
} from './resolve-install-root.mjs';
|
|
30
30
|
import { resolveProfilesRootDirectory } from './select-install-targets.mjs';
|
|
31
|
+
import { writeFileAtomically } from './write-file-atomically.mjs';
|
|
31
32
|
|
|
32
33
|
export const DRY_RUN_FLAG = '--dry-run';
|
|
33
34
|
export const RETIRED_SESSION_TITLE_GATE_FILE_NAME = 'session_title_status_gate.py';
|
|
@@ -195,7 +196,7 @@ export function mergeProfileSettingsFile(settingsPath, options) {
|
|
|
195
196
|
copyFileSync(settingsPath, backupPath);
|
|
196
197
|
}
|
|
197
198
|
mkdirSync(dirname(settingsPath), { recursive: true });
|
|
198
|
-
|
|
199
|
+
writeFileAtomically(
|
|
199
200
|
settingsPath,
|
|
200
201
|
JSON.stringify(settings, null, hostConfigurationIndent(settingsText, DEFAULT_SETTINGS_INDENT)) + '\n',
|
|
201
202
|
);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { test } from 'node:test';
|
|
2
2
|
import { strict as assert } from 'node:assert';
|
|
3
|
-
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, symlinkSync, writeFileSync } from 'node:fs';
|
|
4
4
|
import { tmpdir } from 'node:os';
|
|
5
5
|
import { join, resolve } from 'node:path';
|
|
6
6
|
|
|
@@ -73,6 +73,30 @@ test('a missing settings.json is created with every declared entry and no Stop h
|
|
|
73
73
|
assert.deepEqual(outcome.gate.removedPaths, []);
|
|
74
74
|
});
|
|
75
75
|
|
|
76
|
+
test('a linked profile settings.json keeps its link and the shared file gets every declared entry', (context) => {
|
|
77
|
+
const homeDirectory = makeHome();
|
|
78
|
+
const claudeDirectory = join(homeDirectory, '.claude');
|
|
79
|
+
mkdirSync(claudeDirectory);
|
|
80
|
+
const sharedSettingsPath = join(homeDirectory, 'shared', 'settings.json');
|
|
81
|
+
writeSettings(sharedSettingsPath, { outputStyle: 'plain' });
|
|
82
|
+
const linkedPath = join(claudeDirectory, 'settings.json');
|
|
83
|
+
try {
|
|
84
|
+
symlinkSync(sharedSettingsPath, linkedPath, 'file');
|
|
85
|
+
} catch (error) {
|
|
86
|
+
if (error.code === 'EPERM') return context.skip('this account cannot create symlinks');
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
mergeProfileSettings([linkedPath], { dryRun: false, homeDirectory, now: FIXED_NOW });
|
|
91
|
+
|
|
92
|
+
assert.equal(lstatSync(linkedPath).isSymbolicLink(), true, 'the profile entry is still a link');
|
|
93
|
+
assert.deepEqual(readSettings(sharedSettingsPath), {
|
|
94
|
+
outputStyle: 'plain',
|
|
95
|
+
permissions: { allow: PERMISSION_ALLOW_ITEMS },
|
|
96
|
+
autoMode: { allow: AUTO_MODE_ALLOW_ITEMS },
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
|
|
76
100
|
test('the retired profile gate leaves settings.json and ~/.claude, and another Stop hook stays', () => {
|
|
77
101
|
const homeDirectory = makeHome();
|
|
78
102
|
const claudeDirectory = join(homeDirectory, '.claude');
|
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
mergeProfileSettingsFile,
|
|
9
9
|
} from './merge_profile_settings.mjs';
|
|
10
10
|
import { normalizePathForComparison } from './resolve-install-root.mjs';
|
|
11
|
+
import { writeFileAtomically } from './write-file-atomically.mjs';
|
|
11
12
|
|
|
12
13
|
const STOP_EVENT_NAME = 'Stop';
|
|
13
14
|
const MANAGED_HOOKS_DIRECTORY_NAME = 'hooks';
|
|
@@ -235,7 +236,7 @@ export function removeOpenTasksGateFromProfiles(options) {
|
|
|
235
236
|
);
|
|
236
237
|
if (settings.hooks[STOP_EVENT_NAME].length === 0) delete settings.hooks[STOP_EVENT_NAME];
|
|
237
238
|
if (Object.keys(settings.hooks).length === 0) delete settings.hooks;
|
|
238
|
-
|
|
239
|
+
writeFileAtomically(eachPath, JSON.stringify(settings, null, hostConfigurationIndent(settingsText, SETTINGS_INDENT)) + '\n');
|
|
239
240
|
allChangedPaths.push(eachPath);
|
|
240
241
|
}
|
|
241
242
|
return allChangedPaths;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { test } from 'node:test';
|
|
2
2
|
import { strict as assert } from 'node:assert';
|
|
3
|
-
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
|
|
4
4
|
import { tmpdir } from 'node:os';
|
|
5
5
|
import { join } from 'node:path';
|
|
6
6
|
|
|
@@ -68,6 +68,31 @@ test('a profile whose settings.json links to the main settings is left out', (co
|
|
|
68
68
|
assert.deepEqual(otherProfileSettingsPaths({ homeDirectory, environment: {}, mainSettingsPath }), []);
|
|
69
69
|
});
|
|
70
70
|
|
|
71
|
+
test('removal through a linked profile settings.json updates the shared file and keeps the link', (context) => {
|
|
72
|
+
const { homeDirectory, claudeHome, gateCommand } = makeHome(context);
|
|
73
|
+
const sharedSettingsPath = join(homeDirectory, 'shared', 'settings.json');
|
|
74
|
+
mkdirSync(join(homeDirectory, 'shared'));
|
|
75
|
+
writeFileSync(sharedSettingsPath, JSON.stringify({
|
|
76
|
+
hooks: { Stop: [{ hooks: [
|
|
77
|
+
{ type: 'command', command: 'python3 /opt/own/stop.py' },
|
|
78
|
+
{ type: 'command', command: gateCommand },
|
|
79
|
+
] }] },
|
|
80
|
+
}, null, 4));
|
|
81
|
+
const linkedPath = writeProfile(homeDirectory, 'linked');
|
|
82
|
+
try {
|
|
83
|
+
symlinkSync(sharedSettingsPath, linkedPath, 'file');
|
|
84
|
+
} catch (error) {
|
|
85
|
+
if (error.code === 'EPERM') return context.skip('this account cannot create symlinks');
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const allChangedPaths = removeOpenTasksGateFromProfiles({ claudeHome, allProfileSettingsPaths: [linkedPath] });
|
|
90
|
+
|
|
91
|
+
assert.deepEqual(allChangedPaths, [linkedPath]);
|
|
92
|
+
assert.equal(lstatSync(linkedPath).isSymbolicLink(), true, 'the profile entry is still a link');
|
|
93
|
+
assert.deepEqual(stopCommands(sharedSettingsPath), ['python3 /opt/own/stop.py']);
|
|
94
|
+
});
|
|
95
|
+
|
|
71
96
|
test('a second run adds nothing, and an older interpreter spelling is replaced', (context) => {
|
|
72
97
|
const { homeDirectory, claudeHome, mainSettingsPath, gateCommand } = makeHome(context);
|
|
73
98
|
const staleCommand = gateCommand.replace(/^python3/, '/usr/bin/python3.9');
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Replace a file's contents so a kill at any point leaves a whole file.
|
|
3
|
+
*
|
|
4
|
+
* The new contents go to a temporary file beside the target, and a rename
|
|
5
|
+
* moves that file over the target. A run that stops before the rename leaves
|
|
6
|
+
* the prior file as it was; a run that stops after it leaves the new file.
|
|
7
|
+
* A write that throws removes its temporary file before the error goes on.
|
|
8
|
+
* Each write first removes this target's stale temporary files, the ones a
|
|
9
|
+
* killed writer left behind.
|
|
10
|
+
*
|
|
11
|
+
* A target that is a symbolic link keeps the link: the write lands on the
|
|
12
|
+
* file the link resolves to. A target that already exists keeps its mode.
|
|
13
|
+
*
|
|
14
|
+
* ::
|
|
15
|
+
*
|
|
16
|
+
* writeFileAtomically(settingsPath, JSON.stringify(settings, null, 4) + '\n')
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { randomBytes } from 'node:crypto';
|
|
20
|
+
import { chmodSync, lstatSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
21
|
+
import { basename, dirname, join, resolve } from 'node:path';
|
|
22
|
+
|
|
23
|
+
import { renameSyncRetryingWhileBusy } from './git_hooks_installer.mjs';
|
|
24
|
+
|
|
25
|
+
const TEMPORARY_NAME_RANDOM_BYTE_COUNT = 6;
|
|
26
|
+
const PERMISSION_BITS_MASK = 0o7777;
|
|
27
|
+
const STALE_TEMPORARY_FILE_AGE_MS = 10 * 60 * 1000;
|
|
28
|
+
const REGULAR_EXPRESSION_SPECIAL_CHARACTERS = /[.*+?^${}()|[\]\\]/g;
|
|
29
|
+
const MAXIMUM_LINK_COUNT = 40;
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Say whether a process with this id runs on this machine now.
|
|
34
|
+
*
|
|
35
|
+
* @param {number} processId The process id a temporary file name carries.
|
|
36
|
+
* @returns {boolean} True when the process exists, or exists and belongs to another user.
|
|
37
|
+
*/
|
|
38
|
+
function processIsRunning(processId) {
|
|
39
|
+
try {
|
|
40
|
+
process.kill(processId, 0);
|
|
41
|
+
return true;
|
|
42
|
+
} catch (probeError) {
|
|
43
|
+
return probeError.code === 'EPERM';
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Remove temporary files that a killed write of this target left behind.
|
|
50
|
+
*
|
|
51
|
+
* A temporary file is stale when its name carries a process id that no
|
|
52
|
+
* longer runs and it is older than ten minutes::
|
|
53
|
+
*
|
|
54
|
+
* .settings.json.4242.a1b2c3d4e5f6.tmp process 4242 gone, an hour old -> removed
|
|
55
|
+
* .settings.json.4242.a1b2c3d4e5f6.tmp process 4242 gone, a minute old -> kept
|
|
56
|
+
* .settings.json.5151.a1b2c3d4e5f6.tmp process 5151 runs -> kept
|
|
57
|
+
*
|
|
58
|
+
* A file that cannot be read or removed stays.
|
|
59
|
+
*
|
|
60
|
+
* @param {string} writeTargetPath The file the write lands on.
|
|
61
|
+
* @returns {void}
|
|
62
|
+
*/
|
|
63
|
+
function removeStaleTemporaryFiles(writeTargetPath) {
|
|
64
|
+
const targetDirectory = dirname(writeTargetPath);
|
|
65
|
+
const escapedName = basename(writeTargetPath).replace(REGULAR_EXPRESSION_SPECIAL_CHARACTERS, '\\$&');
|
|
66
|
+
const temporaryNamePattern = new RegExp(`^\\.${escapedName}\\.(\\d+)\\.[0-9a-f]+\\.tmp$`);
|
|
67
|
+
let allEntryNames;
|
|
68
|
+
try {
|
|
69
|
+
allEntryNames = readdirSync(targetDirectory);
|
|
70
|
+
} catch {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
for (const eachName of allEntryNames) {
|
|
74
|
+
const nameMatch = temporaryNamePattern.exec(eachName);
|
|
75
|
+
if (!nameMatch) {
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
const writerProcessId = Number(nameMatch[1]);
|
|
79
|
+
if (writerProcessId === process.pid || processIsRunning(writerProcessId)) {
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const temporaryPath = join(targetDirectory, eachName);
|
|
83
|
+
try {
|
|
84
|
+
if (Date.now() - statSync(temporaryPath).mtimeMs > STALE_TEMPORARY_FILE_AGE_MS) {
|
|
85
|
+
rmSync(temporaryPath, { force: true });
|
|
86
|
+
}
|
|
87
|
+
} catch {
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Resolve the file a write to this path lands on.
|
|
95
|
+
*
|
|
96
|
+
* A chain of links is followed to its last entry, which may not exist yet::
|
|
97
|
+
*
|
|
98
|
+
* profile/settings.json -> dotfiles/settings.json -> store/settings.json (missing)
|
|
99
|
+
* -> store/settings.json
|
|
100
|
+
*
|
|
101
|
+
* @param {string} targetPath The path the caller names.
|
|
102
|
+
* @returns {string} The path itself, or the file its chain of links ends at.
|
|
103
|
+
* @throws {Error} With code ELOOP when the chain is longer than the link limit.
|
|
104
|
+
*/
|
|
105
|
+
function resolveWriteTargetPath(targetPath) {
|
|
106
|
+
if (!lstatSync(targetPath, { throwIfNoEntry: false })?.isSymbolicLink()) {
|
|
107
|
+
return targetPath;
|
|
108
|
+
}
|
|
109
|
+
try {
|
|
110
|
+
return realpathSync(targetPath);
|
|
111
|
+
} catch {
|
|
112
|
+
let currentPath = targetPath;
|
|
113
|
+
for (let linkCount = 0; linkCount < MAXIMUM_LINK_COUNT; linkCount += 1) {
|
|
114
|
+
if (!lstatSync(currentPath, { throwIfNoEntry: false })?.isSymbolicLink()) {
|
|
115
|
+
return currentPath;
|
|
116
|
+
}
|
|
117
|
+
currentPath = resolve(dirname(currentPath), readlinkSync(currentPath));
|
|
118
|
+
}
|
|
119
|
+
throw Object.assign(new Error(`ELOOP: too many links to resolve '${targetPath}'`), { code: 'ELOOP' });
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Write contents to a path through a temporary file and a rename.
|
|
125
|
+
*
|
|
126
|
+
* @param {string} targetPath The file to create or replace.
|
|
127
|
+
* @param {string | Uint8Array} contents The complete new contents.
|
|
128
|
+
* @returns {void}
|
|
129
|
+
*/
|
|
130
|
+
export function writeFileAtomically(targetPath, contents) {
|
|
131
|
+
const writeTargetPath = resolveWriteTargetPath(targetPath);
|
|
132
|
+
removeStaleTemporaryFiles(writeTargetPath);
|
|
133
|
+
const priorStats = statSync(writeTargetPath, { throwIfNoEntry: false });
|
|
134
|
+
const temporaryPath = join(
|
|
135
|
+
dirname(writeTargetPath),
|
|
136
|
+
`.${basename(writeTargetPath)}.${process.pid}.${randomBytes(TEMPORARY_NAME_RANDOM_BYTE_COUNT).toString('hex')}.tmp`,
|
|
137
|
+
);
|
|
138
|
+
try {
|
|
139
|
+
writeFileSync(temporaryPath, contents, { flag: 'wx' });
|
|
140
|
+
if (priorStats) {
|
|
141
|
+
chmodSync(temporaryPath, priorStats.mode & PERMISSION_BITS_MASK);
|
|
142
|
+
}
|
|
143
|
+
renameSyncRetryingWhileBusy(temporaryPath, writeTargetPath);
|
|
144
|
+
} catch (writeError) {
|
|
145
|
+
rmSync(temporaryPath, { force: true });
|
|
146
|
+
throw writeError;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import { strict as assert } from 'node:assert';
|
|
3
|
+
import { spawnSync } from 'node:child_process';
|
|
4
|
+
import {
|
|
5
|
+
chmodSync,
|
|
6
|
+
lstatSync,
|
|
7
|
+
mkdirSync,
|
|
8
|
+
mkdtempSync,
|
|
9
|
+
readFileSync,
|
|
10
|
+
readdirSync,
|
|
11
|
+
readlinkSync,
|
|
12
|
+
rmSync,
|
|
13
|
+
statSync,
|
|
14
|
+
symlinkSync,
|
|
15
|
+
utimesSync,
|
|
16
|
+
writeFileSync,
|
|
17
|
+
} from 'node:fs';
|
|
18
|
+
import { tmpdir } from 'node:os';
|
|
19
|
+
import { join } from 'node:path';
|
|
20
|
+
|
|
21
|
+
import { writeFileAtomically } from './write-file-atomically.mjs';
|
|
22
|
+
|
|
23
|
+
const FILE_SIZE_LIMIT_COMMAND = 'prlimit';
|
|
24
|
+
const isFileSizeLimitAvailable = spawnSync(FILE_SIZE_LIMIT_COMMAND, ['--version']).status === 0;
|
|
25
|
+
const isPosixPlatform = process.platform !== 'win32';
|
|
26
|
+
const PRIOR_SETTINGS_TEXT = '{\n "prior": true\n}\n';
|
|
27
|
+
const NEW_SETTINGS_TEXT = `{\n "next": "${'x'.repeat(4096)}"\n}\n`;
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
function withSandbox(runInSandbox) {
|
|
31
|
+
const sandboxRoot = mkdtempSync(join(tmpdir(), 'cdev-atomic-write-'));
|
|
32
|
+
try {
|
|
33
|
+
runInSandbox(sandboxRoot);
|
|
34
|
+
} finally {
|
|
35
|
+
rmSync(sandboxRoot, { recursive: true, force: true });
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
test('writeFileAtomically should replace an existing file with the complete new text and leave no temporary file', () => {
|
|
41
|
+
withSandbox((sandboxRoot) => {
|
|
42
|
+
const settingsPath = join(sandboxRoot, 'settings.json');
|
|
43
|
+
writeFileSync(settingsPath, PRIOR_SETTINGS_TEXT);
|
|
44
|
+
|
|
45
|
+
writeFileAtomically(settingsPath, NEW_SETTINGS_TEXT);
|
|
46
|
+
|
|
47
|
+
assert.equal(readFileSync(settingsPath, 'utf8'), NEW_SETTINGS_TEXT);
|
|
48
|
+
assert.deepEqual(readdirSync(sandboxRoot), ['settings.json']);
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
test('writeFileAtomically should create a file that does not exist yet', () => {
|
|
54
|
+
withSandbox((sandboxRoot) => {
|
|
55
|
+
const settingsPath = join(sandboxRoot, 'settings.json');
|
|
56
|
+
|
|
57
|
+
writeFileAtomically(settingsPath, NEW_SETTINGS_TEXT);
|
|
58
|
+
|
|
59
|
+
assert.equal(readFileSync(settingsPath, 'utf8'), NEW_SETTINGS_TEXT);
|
|
60
|
+
assert.deepEqual(readdirSync(sandboxRoot), ['settings.json']);
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
test(
|
|
66
|
+
'writeFileAtomically should keep the mode of the file it replaces',
|
|
67
|
+
{ skip: isPosixPlatform ? false : 'Windows keeps no POSIX mode bits' },
|
|
68
|
+
() => {
|
|
69
|
+
withSandbox((sandboxRoot) => {
|
|
70
|
+
const settingsPath = join(sandboxRoot, 'settings.json');
|
|
71
|
+
writeFileSync(settingsPath, PRIOR_SETTINGS_TEXT);
|
|
72
|
+
chmodSync(settingsPath, 0o600);
|
|
73
|
+
|
|
74
|
+
writeFileAtomically(settingsPath, NEW_SETTINGS_TEXT);
|
|
75
|
+
|
|
76
|
+
assert.equal(statSync(settingsPath).mode & 0o777, 0o600);
|
|
77
|
+
});
|
|
78
|
+
},
|
|
79
|
+
);
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
test(
|
|
83
|
+
'writeFileAtomically should write through a linked settings.json and keep the link',
|
|
84
|
+
{ skip: isPosixPlatform ? false : 'creating a file link on Windows needs a privilege the runner may lack' },
|
|
85
|
+
() => {
|
|
86
|
+
withSandbox((sandboxRoot) => {
|
|
87
|
+
const sharedDirectory = join(sandboxRoot, 'shared');
|
|
88
|
+
const profileDirectory = join(sandboxRoot, 'profile');
|
|
89
|
+
mkdirSync(sharedDirectory);
|
|
90
|
+
mkdirSync(profileDirectory);
|
|
91
|
+
const sharedSettingsPath = join(sharedDirectory, 'settings.json');
|
|
92
|
+
const linkedSettingsPath = join(profileDirectory, 'settings.json');
|
|
93
|
+
writeFileSync(sharedSettingsPath, PRIOR_SETTINGS_TEXT);
|
|
94
|
+
symlinkSync(sharedSettingsPath, linkedSettingsPath);
|
|
95
|
+
|
|
96
|
+
writeFileAtomically(linkedSettingsPath, NEW_SETTINGS_TEXT);
|
|
97
|
+
|
|
98
|
+
assert.equal(lstatSync(linkedSettingsPath).isSymbolicLink(), true, 'the profile entry is still a link');
|
|
99
|
+
assert.equal(readlinkSync(linkedSettingsPath), sharedSettingsPath);
|
|
100
|
+
assert.equal(readFileSync(sharedSettingsPath, 'utf8'), NEW_SETTINGS_TEXT);
|
|
101
|
+
assert.deepEqual(readdirSync(sharedDirectory), ['settings.json']);
|
|
102
|
+
assert.deepEqual(readdirSync(profileDirectory), ['settings.json']);
|
|
103
|
+
});
|
|
104
|
+
},
|
|
105
|
+
);
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
test(
|
|
109
|
+
'writeFileAtomically should create the missing file at the end of a chain of links and keep every link',
|
|
110
|
+
{ skip: isPosixPlatform ? false : 'creating a file link on Windows needs a privilege the runner may lack' },
|
|
111
|
+
() => {
|
|
112
|
+
withSandbox((sandboxRoot) => {
|
|
113
|
+
const profileDirectory = join(sandboxRoot, 'profile');
|
|
114
|
+
const dotfilesDirectory = join(sandboxRoot, 'dotfiles');
|
|
115
|
+
const storeDirectory = join(sandboxRoot, 'store');
|
|
116
|
+
mkdirSync(profileDirectory);
|
|
117
|
+
mkdirSync(dotfilesDirectory);
|
|
118
|
+
mkdirSync(storeDirectory);
|
|
119
|
+
const profileSettingsPath = join(profileDirectory, 'settings.json');
|
|
120
|
+
const dotfilesSettingsPath = join(dotfilesDirectory, 'settings.json');
|
|
121
|
+
const storedSettingsPath = join(storeDirectory, 'settings.json');
|
|
122
|
+
symlinkSync(dotfilesSettingsPath, profileSettingsPath);
|
|
123
|
+
symlinkSync(join('..', 'store', 'settings.json'), dotfilesSettingsPath);
|
|
124
|
+
|
|
125
|
+
writeFileAtomically(profileSettingsPath, NEW_SETTINGS_TEXT);
|
|
126
|
+
|
|
127
|
+
assert.equal(lstatSync(profileSettingsPath).isSymbolicLink(), true, 'the profile entry is still a link');
|
|
128
|
+
assert.equal(lstatSync(dotfilesSettingsPath).isSymbolicLink(), true, 'the middle entry is still a link');
|
|
129
|
+
assert.equal(readFileSync(storedSettingsPath, 'utf8'), NEW_SETTINGS_TEXT);
|
|
130
|
+
assert.deepEqual(readdirSync(storeDirectory), ['settings.json']);
|
|
131
|
+
assert.deepEqual(readdirSync(dotfilesDirectory), ['settings.json']);
|
|
132
|
+
});
|
|
133
|
+
},
|
|
134
|
+
);
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
test(
|
|
138
|
+
'writeFileAtomically should refuse a link that loops back to itself and leave the link in place',
|
|
139
|
+
{ skip: isPosixPlatform ? false : 'creating a file link on Windows needs a privilege the runner may lack' },
|
|
140
|
+
() => {
|
|
141
|
+
withSandbox((sandboxRoot) => {
|
|
142
|
+
const settingsPath = join(sandboxRoot, 'settings.json');
|
|
143
|
+
symlinkSync('settings.json', settingsPath);
|
|
144
|
+
|
|
145
|
+
assert.throws(() => writeFileAtomically(settingsPath, NEW_SETTINGS_TEXT), { code: 'ELOOP' });
|
|
146
|
+
|
|
147
|
+
assert.equal(lstatSync(settingsPath).isSymbolicLink(), true, 'the looping entry is still a link');
|
|
148
|
+
assert.deepEqual(readdirSync(sandboxRoot), ['settings.json']);
|
|
149
|
+
});
|
|
150
|
+
},
|
|
151
|
+
);
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
test(
|
|
155
|
+
'writeFileAtomically should keep the prior file whole and remove its temporary file when the write fails part way',
|
|
156
|
+
{ skip: isFileSizeLimitAvailable ? false : `${FILE_SIZE_LIMIT_COMMAND} is not on PATH` },
|
|
157
|
+
() => {
|
|
158
|
+
withSandbox((sandboxRoot) => {
|
|
159
|
+
const settingsPath = join(sandboxRoot, 'settings.json');
|
|
160
|
+
writeFileSync(settingsPath, PRIOR_SETTINGS_TEXT);
|
|
161
|
+
const writerScriptPath = join(sandboxRoot, 'write.mjs');
|
|
162
|
+
writeFileSync(writerScriptPath, [
|
|
163
|
+
`import { writeFileAtomically } from ${JSON.stringify(new URL('./write-file-atomically.mjs', import.meta.url).href)};`,
|
|
164
|
+
`writeFileAtomically(${JSON.stringify(settingsPath)}, ${JSON.stringify(NEW_SETTINGS_TEXT)});`,
|
|
165
|
+
].join('\n'));
|
|
166
|
+
|
|
167
|
+
const limitedRun = spawnSync(
|
|
168
|
+
FILE_SIZE_LIMIT_COMMAND,
|
|
169
|
+
[`--fsize=${Math.floor(NEW_SETTINGS_TEXT.length / 2)}`, process.execPath, writerScriptPath],
|
|
170
|
+
{ encoding: 'utf8' },
|
|
171
|
+
);
|
|
172
|
+
|
|
173
|
+
assert.notEqual(limitedRun.status, 0, 'the write past the file size limit fails');
|
|
174
|
+
assert.match(limitedRun.stderr, /EFBIG/);
|
|
175
|
+
assert.equal(readFileSync(settingsPath, 'utf8'), PRIOR_SETTINGS_TEXT);
|
|
176
|
+
assert.deepEqual(readdirSync(sandboxRoot).sort(), ['settings.json', 'write.mjs']);
|
|
177
|
+
});
|
|
178
|
+
},
|
|
179
|
+
);
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
const KILL_AT_TARGET_CHANGE_PRELOAD = `
|
|
183
|
+
const fs = require('node:fs');
|
|
184
|
+
const targetPath = process.env.KILL_TARGET_PATH;
|
|
185
|
+
const originalWriteFileSync = fs.writeFileSync;
|
|
186
|
+
const originalRenameSync = fs.renameSync;
|
|
187
|
+
fs.writeFileSync = function (filePath, data, options) {
|
|
188
|
+
if (String(filePath) === targetPath) {
|
|
189
|
+
const text = String(data);
|
|
190
|
+
originalWriteFileSync(filePath, text.slice(0, Math.floor(text.length / 2)));
|
|
191
|
+
process.kill(process.pid, 'SIGKILL');
|
|
192
|
+
}
|
|
193
|
+
return originalWriteFileSync.apply(this, arguments);
|
|
194
|
+
};
|
|
195
|
+
fs.renameSync = function (sourcePath, destinationPath) {
|
|
196
|
+
if (String(destinationPath) === targetPath) {
|
|
197
|
+
process.kill(process.pid, 'SIGKILL');
|
|
198
|
+
}
|
|
199
|
+
return originalRenameSync.apply(this, arguments);
|
|
200
|
+
};
|
|
201
|
+
require('node:module').syncBuiltinESMExports();
|
|
202
|
+
`;
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
test(
|
|
206
|
+
'writeFileAtomically should keep the prior file whole when the writer is killed as the target changes',
|
|
207
|
+
{ skip: isPosixPlatform ? false : 'a SIGKILL a process sends itself is POSIX only' },
|
|
208
|
+
() => {
|
|
209
|
+
withSandbox((sandboxRoot) => {
|
|
210
|
+
const settingsPath = join(sandboxRoot, 'settings.json');
|
|
211
|
+
writeFileSync(settingsPath, PRIOR_SETTINGS_TEXT);
|
|
212
|
+
const preloadPath = join(sandboxRoot, 'kill-at-target-change.cjs');
|
|
213
|
+
writeFileSync(preloadPath, KILL_AT_TARGET_CHANGE_PRELOAD);
|
|
214
|
+
const writerScriptPath = join(sandboxRoot, 'write.mjs');
|
|
215
|
+
writeFileSync(writerScriptPath, [
|
|
216
|
+
`import { writeFileAtomically } from ${JSON.stringify(new URL('./write-file-atomically.mjs', import.meta.url).href)};`,
|
|
217
|
+
`writeFileAtomically(${JSON.stringify(settingsPath)}, ${JSON.stringify(NEW_SETTINGS_TEXT)});`,
|
|
218
|
+
].join('\n'));
|
|
219
|
+
|
|
220
|
+
const killedRun = spawnSync(
|
|
221
|
+
process.execPath,
|
|
222
|
+
['--require', preloadPath, writerScriptPath],
|
|
223
|
+
{ encoding: 'utf8', env: { ...process.env, KILL_TARGET_PATH: settingsPath } },
|
|
224
|
+
);
|
|
225
|
+
|
|
226
|
+
assert.equal(killedRun.signal, 'SIGKILL', killedRun.stderr);
|
|
227
|
+
assert.equal(readFileSync(settingsPath, 'utf8'), PRIOR_SETTINGS_TEXT);
|
|
228
|
+
});
|
|
229
|
+
},
|
|
230
|
+
);
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
function exitedProcessId() {
|
|
234
|
+
return spawnSync(process.execPath, ['-e', '']).pid;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
test('writeFileAtomically should remove old temporary files of this target whose writer is gone', () => {
|
|
239
|
+
withSandbox((sandboxRoot) => {
|
|
240
|
+
const settingsPath = join(sandboxRoot, 'settings.json');
|
|
241
|
+
writeFileSync(settingsPath, PRIOR_SETTINGS_TEXT);
|
|
242
|
+
const goneWriterId = exitedProcessId();
|
|
243
|
+
const hourAgo = new Date(Date.now() - 60 * 60 * 1000);
|
|
244
|
+
const staleName = `.settings.json.${goneWriterId}.aaaaaaaaaaaa.tmp`;
|
|
245
|
+
const liveWriterName = `.settings.json.${process.pid}.bbbbbbbbbbbb.tmp`;
|
|
246
|
+
const freshName = `.settings.json.${goneWriterId}.cccccccccccc.tmp`;
|
|
247
|
+
const otherTargetName = `.other.json.${goneWriterId}.dddddddddddd.tmp`;
|
|
248
|
+
for (const eachName of [staleName, liveWriterName, freshName, otherTargetName]) {
|
|
249
|
+
writeFileSync(join(sandboxRoot, eachName), '{"half":');
|
|
250
|
+
}
|
|
251
|
+
for (const eachName of [staleName, liveWriterName, otherTargetName]) {
|
|
252
|
+
utimesSync(join(sandboxRoot, eachName), hourAgo, hourAgo);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
writeFileAtomically(settingsPath, NEW_SETTINGS_TEXT);
|
|
256
|
+
|
|
257
|
+
assert.equal(readFileSync(settingsPath, 'utf8'), NEW_SETTINGS_TEXT);
|
|
258
|
+
assert.deepEqual(
|
|
259
|
+
readdirSync(sandboxRoot).sort(),
|
|
260
|
+
[freshName, otherTargetName, liveWriterName, 'settings.json'].sort(),
|
|
261
|
+
);
|
|
262
|
+
});
|
|
263
|
+
});
|