From 1c7f4ac4705f7521a0674a503d0137d974b5f39d Mon Sep 17 00:00:00 2001 From: Ian Clanton-Thuon Date: Thu, 29 Oct 2026 23:06:17 -0700 Subject: [PATCH 1/4] [rushstack] Keep integration fixtures in project temp folders Check in immutable Git and daemon graph fixture inputs, copy them into isolated project-local workspaces, and let the Heft test clean phase remove retained outputs. Preserve daemon shutdown and child-process joins while removing teardown directory deletion that flakes on Windows. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...ct-local-fixtures_2026-10-30-06-04-53.json | 11 +++ ...ct-local-fixtures_2026-10-30-06-04-53.json | 11 +++ ...ct-local-fixtures_2026-10-30-06-04-53.json | 11 +++ libraries/package-deps-hash/config/heft.json | 8 ++ .../package-deps-hash/config/typescript.json | 6 ++ .../src/test/GitIndexFile.test.ts | 24 +++--- .../src/test/RepoStateCache.test.ts | 80 +++++++------------ .../src/test/fixtures/git-index/a.txt | 1 + .../src/test/fixtures/git-index/dir/b.txt | 1 + .../src/test/fixtures/git-index/dir/sub/c.txt | 1 + ...ng-name-long-name-long-name-long-name-.txt | 1 + .../src/test/fixtures/repo-state/git-config | 13 +++ .../src/test/fixtures/repo-state/repo/a.txt | 1 + .../src/test/fixtures/repo-state/repo/b.txt | 1 + .../test/fixtures/repo-state/repo/dir/c.txt | 1 + libraries/rush-client-core/config/heft.json | 8 ++ .../src/test/connectOrStartDaemon.test.ts | 12 +-- libraries/rush-daemon/config/heft.json | 8 ++ libraries/rush-daemon/config/typescript.json | 6 ++ .../src/test/DaemonGraphFixturePaths.test.ts | 40 +++++++--- .../src/test/DaemonGraphFixtureSetup.test.ts | 15 ++-- .../src/test/DaemonGraphTestFixture.ts | 68 ++++------------ .../rush-daemon/src/test/fixtures/README.md | 19 +++++ .../src/test/fixtures/graph/a/build.cjs | 5 ++ .../src/test/fixtures/graph/a/input.txt | 1 + .../src/test/fixtures/graph/a/package.json | 8 ++ .../src/test/fixtures/graph/b/build.cjs | 5 ++ .../src/test/fixtures/graph/b/input.txt | 1 + .../src/test/fixtures/graph/b/package.json | 10 +++ .../src/test/fixtures/graph/c/build.cjs | 5 ++ .../src/test/fixtures/graph/c/input.txt | 1 + .../src/test/fixtures/graph/c/package.json | 8 ++ .../common/config/rush/command-line.json | 12 +++ .../common/config/rush/npm-shrinkwrap.json | 4 + .../src/test/fixtures/graph/gitignore | 4 + .../src/test/fixtures/graph/rush.json | 13 +++ 36 files changed, 280 insertions(+), 144 deletions(-) create mode 100644 common/changes/@rushstack/package-deps-hash/test-project-local-fixtures_2026-10-30-06-04-53.json create mode 100644 common/changes/@rushstack/rush-client-core/test-project-local-fixtures_2026-10-30-06-04-53.json create mode 100644 common/changes/@rushstack/rush-daemon/test-project-local-fixtures_2026-10-30-06-04-53.json create mode 100644 libraries/package-deps-hash/config/heft.json create mode 100644 libraries/package-deps-hash/config/typescript.json create mode 100644 libraries/package-deps-hash/src/test/fixtures/git-index/a.txt create mode 100644 libraries/package-deps-hash/src/test/fixtures/git-index/dir/b.txt create mode 100644 libraries/package-deps-hash/src/test/fixtures/git-index/dir/sub/c.txt create mode 100644 libraries/package-deps-hash/src/test/fixtures/git-index/dir/sub/long-name-long-name-long-name-long-name-long-name-long-name-long-name-long-name-long-name-long-name-long-name-long-name-.txt create mode 100644 libraries/package-deps-hash/src/test/fixtures/repo-state/git-config create mode 100644 libraries/package-deps-hash/src/test/fixtures/repo-state/repo/a.txt create mode 100644 libraries/package-deps-hash/src/test/fixtures/repo-state/repo/b.txt create mode 100644 libraries/package-deps-hash/src/test/fixtures/repo-state/repo/dir/c.txt create mode 100644 libraries/rush-client-core/config/heft.json create mode 100644 libraries/rush-daemon/config/heft.json create mode 100644 libraries/rush-daemon/config/typescript.json create mode 100644 libraries/rush-daemon/src/test/fixtures/README.md create mode 100644 libraries/rush-daemon/src/test/fixtures/graph/a/build.cjs create mode 100644 libraries/rush-daemon/src/test/fixtures/graph/a/input.txt create mode 100644 libraries/rush-daemon/src/test/fixtures/graph/a/package.json create mode 100644 libraries/rush-daemon/src/test/fixtures/graph/b/build.cjs create mode 100644 libraries/rush-daemon/src/test/fixtures/graph/b/input.txt create mode 100644 libraries/rush-daemon/src/test/fixtures/graph/b/package.json create mode 100644 libraries/rush-daemon/src/test/fixtures/graph/c/build.cjs create mode 100644 libraries/rush-daemon/src/test/fixtures/graph/c/input.txt create mode 100644 libraries/rush-daemon/src/test/fixtures/graph/c/package.json create mode 100644 libraries/rush-daemon/src/test/fixtures/graph/common/config/rush/command-line.json create mode 100644 libraries/rush-daemon/src/test/fixtures/graph/common/config/rush/npm-shrinkwrap.json create mode 100644 libraries/rush-daemon/src/test/fixtures/graph/gitignore create mode 100644 libraries/rush-daemon/src/test/fixtures/graph/rush.json diff --git a/common/changes/@rushstack/package-deps-hash/test-project-local-fixtures_2026-10-30-06-04-53.json b/common/changes/@rushstack/package-deps-hash/test-project-local-fixtures_2026-10-30-06-04-53.json new file mode 100644 index 00000000000..3aafebf85be --- /dev/null +++ b/common/changes/@rushstack/package-deps-hash/test-project-local-fixtures_2026-10-30-06-04-53.json @@ -0,0 +1,11 @@ +{ + "changes": [ + { + "comment": "", + "type": "none", + "packageName": "@rushstack/package-deps-hash" + } + ], + "packageName": "@rushstack/package-deps-hash", + "email": "iclanton@users.noreply.github.com" +} \ No newline at end of file diff --git a/common/changes/@rushstack/rush-client-core/test-project-local-fixtures_2026-10-30-06-04-53.json b/common/changes/@rushstack/rush-client-core/test-project-local-fixtures_2026-10-30-06-04-53.json new file mode 100644 index 00000000000..a489987b94b --- /dev/null +++ b/common/changes/@rushstack/rush-client-core/test-project-local-fixtures_2026-10-30-06-04-53.json @@ -0,0 +1,11 @@ +{ + "changes": [ + { + "comment": "", + "type": "none", + "packageName": "@rushstack/rush-client-core" + } + ], + "packageName": "@rushstack/rush-client-core", + "email": "iclanton@users.noreply.github.com" +} \ No newline at end of file diff --git a/common/changes/@rushstack/rush-daemon/test-project-local-fixtures_2026-10-30-06-04-53.json b/common/changes/@rushstack/rush-daemon/test-project-local-fixtures_2026-10-30-06-04-53.json new file mode 100644 index 00000000000..6989f28f355 --- /dev/null +++ b/common/changes/@rushstack/rush-daemon/test-project-local-fixtures_2026-10-30-06-04-53.json @@ -0,0 +1,11 @@ +{ + "changes": [ + { + "comment": "", + "type": "none", + "packageName": "@rushstack/rush-daemon" + } + ], + "packageName": "@rushstack/rush-daemon", + "email": "iclanton@users.noreply.github.com" +} \ No newline at end of file diff --git a/libraries/package-deps-hash/config/heft.json b/libraries/package-deps-hash/config/heft.json new file mode 100644 index 00000000000..b7597218dca --- /dev/null +++ b/libraries/package-deps-hash/config/heft.json @@ -0,0 +1,8 @@ +{ + "extends": "local-node-rig/profiles/default/config/heft.json", + "phasesByName": { + "test": { + "cleanFiles": [{ "includeGlobs": ["temp/test"] }] + } + } +} diff --git a/libraries/package-deps-hash/config/typescript.json b/libraries/package-deps-hash/config/typescript.json new file mode 100644 index 00000000000..04a10505698 --- /dev/null +++ b/libraries/package-deps-hash/config/typescript.json @@ -0,0 +1,6 @@ +{ + "extends": "local-node-rig/profiles/default/config/typescript.json", + "staticAssetsToCopy": { + "includeGlobs": ["test/fixtures/**"] + } +} diff --git a/libraries/package-deps-hash/src/test/GitIndexFile.test.ts b/libraries/package-deps-hash/src/test/GitIndexFile.test.ts index 08e734b06f1..624719b225b 100644 --- a/libraries/package-deps-hash/src/test/GitIndexFile.test.ts +++ b/libraries/package-deps-hash/src/test/GitIndexFile.test.ts @@ -4,7 +4,6 @@ import { execFileSync } from 'node:child_process'; import { createHash } from 'node:crypto'; import * as fs from 'node:fs'; -import * as os from 'node:os'; import * as path from 'node:path'; import { @@ -22,6 +21,12 @@ import { createFsmonitorHook, type IFsmonitorHook } from './FsmonitorHook'; const SHA1_OBJECT_ID_LENGTH: number = 20; const SHA256_OBJECT_ID_LENGTH: number = 32; const LONG_FILE_PATH: string = `dir/sub/${'long-name-'.repeat(12)}.txt`; +const TEST_ROOT: string = `${__dirname}/../../temp/test/git-index`; + +function createTestFolder(): string { + fs.mkdirSync(TEST_ROOT, { recursive: true }); + return fs.mkdtempSync(`${TEST_ROOT}/case-`); +} function getGitEnvironment(): NodeJS.ProcessEnv { const environment: NodeJS.ProcessEnv = { ...process.env }; @@ -68,10 +73,7 @@ function createRepo(...initArgs: string[]): void { runGit('config', 'index.skipHash', 'false'); // Windows runners turn this on in the system configuration, and Git then warns about each file that it adds runGit('config', 'core.autocrlf', 'false'); - writeFile('a.txt', 'a\n'); - writeFile('dir/b.txt', 'b\n'); - writeFile('dir/sub/c.txt', 'c\n'); - writeFile(LONG_FILE_PATH, 'd\n'); + fs.cpSync(`${__dirname}/fixtures/git-index`, repoPath, { recursive: true }); runGit('add', '.'); } @@ -95,11 +97,7 @@ describe(summarizeGitIndex.name, () => { } beforeEach(() => { - repoPath = fs.mkdtempSync(path.join(os.tmpdir(), 'git-index-file-test-')); - }); - - afterEach(() => { - fs.rmSync(repoPath, { recursive: true, force: true }); + repoPath = createTestFolder(); }); it.each([2, 3, 4])('summarizes a version %i index', (version: number) => { @@ -501,15 +499,11 @@ describe(tryCarryOverGitIndexCaches.name, () => { } beforeEach(() => { - repoPath = fs.mkdtempSync(path.join(os.tmpdir(), 'git-index-file-test-')); + repoPath = createTestFolder(); copyPath = path.join(repoPath, '.git', 'copy'); newCopyPath = path.join(repoPath, '.git', 'new-copy'); }); - afterEach(() => { - fs.rmSync(repoPath, { recursive: true, force: true }); - }); - it.each([2, 3, 4])( 'keeps the untracked cache of the previous copy of a version %i index', (version: number) => { diff --git a/libraries/package-deps-hash/src/test/RepoStateCache.test.ts b/libraries/package-deps-hash/src/test/RepoStateCache.test.ts index 90ea5831408..5dc19f1a50a 100644 --- a/libraries/package-deps-hash/src/test/RepoStateCache.test.ts +++ b/libraries/package-deps-hash/src/test/RepoStateCache.test.ts @@ -3,7 +3,6 @@ import { type ChildProcess, execFileSync } from 'node:child_process'; import * as fs from 'node:fs'; -import * as os from 'node:os'; import * as path from 'node:path'; import { Executable, type IExecutableSpawnOptions } from '@rushstack/node-core-library'; @@ -15,6 +14,8 @@ import { createFsmonitorHook, type IFsmonitorHook } from './FsmonitorHook'; const originalDateNow: () => number = Date.now; const originalSpawn: typeof Executable.spawn = Executable.spawn; +const TEST_ROOT: string = `${__dirname}/../../temp/test/repo-state-cache`; +const FIXTURE_ROOT: string = `${__dirname}/fixtures/repo-state`; // These integration tests launch real Git processes, which can take hundreds of milliseconds each on Windows. jest.setTimeout(30000); @@ -190,32 +191,15 @@ describe(RepoStateCache.name, () => { } beforeEach(() => { - repoPath = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'repo-state-cache-test-'))); - temporaryFolderPath = fs.mkdtempSync(path.join(os.tmpdir(), 'repo-state-cache-private-')); + fs.mkdirSync(TEST_ROOT, { recursive: true }); + const testFolder: string = fs.mkdtempSync(`${TEST_ROOT}/case-`); + repoPath = `${testFolder}/repo`; + temporaryFolderPath = `${testFolder}/private`; + fs.cpSync(`${FIXTURE_ROOT}/repo`, repoPath, { recursive: true }); + repoPath = fs.realpathSync.native(repoPath); + fs.mkdirSync(temporaryFolderPath); runGit('init', '--quiet'); - // Avoid eight Git process launches per test, which are particularly costly on Windows. - fs.appendFileSync( - `${repoPath}/.git/config`, - [ - '', - '[user]', - '\tname = Test', - '\temail = test@example.com', - '[commit]', - '\tgpgSign = false', - '[core]', - '\tautocrlf = false', - '\tsafecrlf = false', - '\tfsmonitor = false', - '\tuntrackedCache = true', - '[maintenance]', - '\tauto = false', - '' - ].join('\n') - ); - writeFile('a.txt', 'a\n'); - writeFile('b.txt', 'b\n'); - writeFile('dir/c.txt', 'c\n'); + fs.appendFileSync(`${repoPath}/.git/config`, fs.readFileSync(`${FIXTURE_ROOT}/git-config`)); commit(); cache = new RepoStateCache({ rootDirectory: repoPath, temporaryFolderPath }); @@ -241,8 +225,6 @@ describe(RepoStateCache.name, () => { afterEach(() => { cache.dispose(); jest.restoreAllMocks(); - fs.rmSync(repoPath, { recursive: true, force: true }); - fs.rmSync(temporaryFolderPath, { recursive: true, force: true }); }); it('initializes the fixture with the expected local Git configuration', () => { @@ -1158,30 +1140,26 @@ describe(RepoStateCache.name, () => { }); it('stops using the cache for a repository with submodules', async () => { - const submodulePath: string = fs.mkdtempSync(path.join(os.tmpdir(), 'repo-state-cache-submodule-')); - try { - execFileSync('git', ['init', '--quiet'], { cwd: submodulePath, env: getGitEnvironment() }); - fs.writeFileSync(path.join(submodulePath, 'inner.txt'), 'inner\n'); - execFileSync('git', ['-c', 'core.autocrlf=false', 'add', '--all'], { - cwd: submodulePath, - env: getGitEnvironment() - }); - execFileSync( - 'git', - ['-c', 'user.name=Test', '-c', 'user.email=test@example.com', 'commit', '--quiet', '-m', 'Inner'], - { cwd: submodulePath, env: getGitEnvironment() } - ); - runGit('-c', 'protocol.file.allow=always', 'submodule', '--quiet', 'add', submodulePath, 'sub'); - commit(); + const submodulePath: string = fs.mkdtempSync(`${TEST_ROOT}/submodule-`); + execFileSync('git', ['init', '--quiet'], { cwd: submodulePath, env: getGitEnvironment() }); + fs.writeFileSync(`${submodulePath}/inner.txt`, 'inner\n'); + execFileSync('git', ['-c', 'core.autocrlf=false', 'add', '--all'], { + cwd: submodulePath, + env: getGitEnvironment() + }); + execFileSync( + 'git', + ['-c', 'user.name=Test', '-c', 'user.email=test@example.com', 'commit', '--quiet', '-m', 'Inner'], + { cwd: submodulePath, env: getGitEnvironment() } + ); + runGit('-c', 'protocol.file.allow=always', 'submodule', '--quiet', 'add', submodulePath, 'sub'); + commit(); - const state: IDetailedRepoState = await getStateAsync(); - await expectUncachedStateAsync(state); - expect(state.hasSubmodules).toBe(true); - expect(state.files.has('sub/inner.txt')).toBe(true); - expect(fs.readdirSync(temporaryFolderPath)).toEqual([]); - } finally { - fs.rmSync(submodulePath, { recursive: true, force: true }); - } + const state: IDetailedRepoState = await getStateAsync(); + await expectUncachedStateAsync(state); + expect(state.hasSubmodules).toBe(true); + expect(state.files.has('sub/inner.txt')).toBe(true); + expect(fs.readdirSync(temporaryFolderPath)).toEqual([]); }); it('falls back to getDetailedRepoStateAsync when it fails, and stops after repeated failures', async () => { diff --git a/libraries/package-deps-hash/src/test/fixtures/git-index/a.txt b/libraries/package-deps-hash/src/test/fixtures/git-index/a.txt new file mode 100644 index 00000000000..78981922613 --- /dev/null +++ b/libraries/package-deps-hash/src/test/fixtures/git-index/a.txt @@ -0,0 +1 @@ +a diff --git a/libraries/package-deps-hash/src/test/fixtures/git-index/dir/b.txt b/libraries/package-deps-hash/src/test/fixtures/git-index/dir/b.txt new file mode 100644 index 00000000000..61780798228 --- /dev/null +++ b/libraries/package-deps-hash/src/test/fixtures/git-index/dir/b.txt @@ -0,0 +1 @@ +b diff --git a/libraries/package-deps-hash/src/test/fixtures/git-index/dir/sub/c.txt b/libraries/package-deps-hash/src/test/fixtures/git-index/dir/sub/c.txt new file mode 100644 index 00000000000..f2ad6c76f01 --- /dev/null +++ b/libraries/package-deps-hash/src/test/fixtures/git-index/dir/sub/c.txt @@ -0,0 +1 @@ +c diff --git a/libraries/package-deps-hash/src/test/fixtures/git-index/dir/sub/long-name-long-name-long-name-long-name-long-name-long-name-long-name-long-name-long-name-long-name-long-name-long-name-.txt b/libraries/package-deps-hash/src/test/fixtures/git-index/dir/sub/long-name-long-name-long-name-long-name-long-name-long-name-long-name-long-name-long-name-long-name-long-name-long-name-.txt new file mode 100644 index 00000000000..4bcfe98e640 --- /dev/null +++ b/libraries/package-deps-hash/src/test/fixtures/git-index/dir/sub/long-name-long-name-long-name-long-name-long-name-long-name-long-name-long-name-long-name-long-name-long-name-long-name-.txt @@ -0,0 +1 @@ +d diff --git a/libraries/package-deps-hash/src/test/fixtures/repo-state/git-config b/libraries/package-deps-hash/src/test/fixtures/repo-state/git-config new file mode 100644 index 00000000000..208f7b14f1f --- /dev/null +++ b/libraries/package-deps-hash/src/test/fixtures/repo-state/git-config @@ -0,0 +1,13 @@ + +[user] + name = Test + email = test@example.com +[commit] + gpgSign = false +[core] + autocrlf = false + safecrlf = false + fsmonitor = false + untrackedCache = true +[maintenance] + auto = false diff --git a/libraries/package-deps-hash/src/test/fixtures/repo-state/repo/a.txt b/libraries/package-deps-hash/src/test/fixtures/repo-state/repo/a.txt new file mode 100644 index 00000000000..78981922613 --- /dev/null +++ b/libraries/package-deps-hash/src/test/fixtures/repo-state/repo/a.txt @@ -0,0 +1 @@ +a diff --git a/libraries/package-deps-hash/src/test/fixtures/repo-state/repo/b.txt b/libraries/package-deps-hash/src/test/fixtures/repo-state/repo/b.txt new file mode 100644 index 00000000000..61780798228 --- /dev/null +++ b/libraries/package-deps-hash/src/test/fixtures/repo-state/repo/b.txt @@ -0,0 +1 @@ +b diff --git a/libraries/package-deps-hash/src/test/fixtures/repo-state/repo/dir/c.txt b/libraries/package-deps-hash/src/test/fixtures/repo-state/repo/dir/c.txt new file mode 100644 index 00000000000..f2ad6c76f01 --- /dev/null +++ b/libraries/package-deps-hash/src/test/fixtures/repo-state/repo/dir/c.txt @@ -0,0 +1 @@ +c diff --git a/libraries/rush-client-core/config/heft.json b/libraries/rush-client-core/config/heft.json new file mode 100644 index 00000000000..b7597218dca --- /dev/null +++ b/libraries/rush-client-core/config/heft.json @@ -0,0 +1,8 @@ +{ + "extends": "local-node-rig/profiles/default/config/heft.json", + "phasesByName": { + "test": { + "cleanFiles": [{ "includeGlobs": ["temp/test"] }] + } + } +} diff --git a/libraries/rush-client-core/src/test/connectOrStartDaemon.test.ts b/libraries/rush-client-core/src/test/connectOrStartDaemon.test.ts index f0fbcae3748..d93db99b5fd 100644 --- a/libraries/rush-client-core/src/test/connectOrStartDaemon.test.ts +++ b/libraries/rush-client-core/src/test/connectOrStartDaemon.test.ts @@ -6,7 +6,6 @@ import { randomUUID } from 'node:crypto'; import { once } from 'node:events'; import * as fs from 'node:fs'; import * as net from 'node:net'; -import * as os from 'node:os'; import * as path from 'node:path'; import { performance } from 'node:perf_hooks'; import { setTimeout as delayAsync } from 'node:timers/promises'; @@ -60,10 +59,11 @@ import { startOrphanedOperationAsync, stopOperationIfRunning } from './OrphanedOperation'; -import { removeTestFolderAsync, waitForTestProcessExitAsync } from './TestProcessExit'; +import { waitForTestProcessExitAsync } from './TestProcessExit'; /** How long after a launch a client may take over its reservation once the helper exited. */ const RELAUNCH_DELAY_MS: number = 15000; +const TEST_ROOT: string = `${__dirname}/../../temp/test/s`; // Leave room for Unix socket names. function readIfPresent(filePath: string): string { return fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : ''; @@ -77,14 +77,15 @@ describe('detached daemon startup', () => { beforeEach(() => { starterProcesses = []; - folder = fs.mkdtempSync(path.join(os.tmpdir(), 'rush-client-')); + fs.mkdirSync(TEST_ROOT, { recursive: true }); + folder = fs.realpathSync.native(fs.mkdtempSync(`${TEST_ROOT}/c-`)); paths = { runtimeDir: folder, socketPath: process.platform === 'win32' ? `\\\\.\\pipe\\rush-client-${path.basename(folder)}` - : path.join(folder, 'd.sock'), - lockfilePath: path.join(folder, 'daemon.pid.json') + : `${folder}/d.sock`, + lockfilePath: `${folder}/daemon.pid.json` }; const environment = captureDaemonRequest({ argv: [], @@ -127,7 +128,6 @@ describe('detached daemon startup', () => { const parents = new Set(fs.readFileSync(path.join(folder, 'parents'), 'utf8').trim().split('\n')); await Promise.all([...parents].map((pid) => waitForTestProcessExitAsync(Number(pid)))); } - await removeTestFolderAsync(folder); }); function startClient(startOptions: IConnectOrStartDaemonOptions = options): { diff --git a/libraries/rush-daemon/config/heft.json b/libraries/rush-daemon/config/heft.json new file mode 100644 index 00000000000..b7597218dca --- /dev/null +++ b/libraries/rush-daemon/config/heft.json @@ -0,0 +1,8 @@ +{ + "extends": "local-node-rig/profiles/default/config/heft.json", + "phasesByName": { + "test": { + "cleanFiles": [{ "includeGlobs": ["temp/test"] }] + } + } +} diff --git a/libraries/rush-daemon/config/typescript.json b/libraries/rush-daemon/config/typescript.json new file mode 100644 index 00000000000..3cf6e2c6718 --- /dev/null +++ b/libraries/rush-daemon/config/typescript.json @@ -0,0 +1,6 @@ +{ + "extends": "local-node-rig/profiles/default/config/typescript.json", + "staticAssetsToCopy": { + "includeGlobs": ["test/fixtures/graph/**"] + } +} diff --git a/libraries/rush-daemon/src/test/DaemonGraphFixturePaths.test.ts b/libraries/rush-daemon/src/test/DaemonGraphFixturePaths.test.ts index bb9a5cbb5c5..46324e370cb 100644 --- a/libraries/rush-daemon/src/test/DaemonGraphFixturePaths.test.ts +++ b/libraries/rush-daemon/src/test/DaemonGraphFixturePaths.test.ts @@ -2,29 +2,47 @@ // See LICENSE in the project root for license information. import * as fs from 'node:fs'; -import * as os from 'node:os'; import * as path from 'node:path'; import { DaemonGraphTestFixture } from './DaemonGraphTestFixture'; -import { removeTestFolderAsync } from './TestProcessExit'; it('uses the physical fixture folder even when the temporary root is reached through an alias', async () => { - const root: string = fs.mkdtempSync(path.join(os.tmpdir(), 'rush-fixture-path-')); - const physical: string = path.join(root, 'physical temporary directory'); - const alias: string = path.join(root, 'alias'); - let temporaryRoot: jest.SpyInstance | undefined; + const testRoot: string = `${__dirname}/../../temp/test/graph-paths`; + fs.mkdirSync(testRoot, { recursive: true }); + const root: string = fs.mkdtempSync(`${testRoot}/case-`); + const physical: string = `${root}/physical temporary directory`; + const alias: string = `${root}/alias`; let fixture: DaemonGraphTestFixture | undefined; try { fs.mkdirSync(physical); fs.symlinkSync(physical, alias, process.platform === 'win32' ? 'junction' : 'dir'); - const realOs = jest.requireActual('node:os'); - temporaryRoot = jest.spyOn(realOs, 'tmpdir').mockReturnValue(alias); - fixture = new DaemonGraphTestFixture(); + fixture = new DaemonGraphTestFixture(alias); expect(fixture.folder).toBe(fs.realpathSync.native(fixture.folder)); expect(path.dirname(fixture.folder)).toBe(fs.realpathSync.native(physical)); } finally { - temporaryRoot?.mockRestore(); await fixture?.[Symbol.asyncDispose](); - await removeTestFolderAsync(root); } }); + +it('copies immutable inputs into independent project-local workspaces and retains them after disposal', async () => { + const first: DaemonGraphTestFixture = await DaemonGraphTestFixture.createAsync(); + let second: DaemonGraphTestFixture | undefined; + try { + const root: string = fs.realpathSync.native(`${__dirname}/../../temp/test/graph`); + const fixtureInput: string = fs.readFileSync(`${__dirname}/fixtures/graph/a/input.txt`, 'utf8'); + expect(path.dirname(first.folder)).toBe(root); + first.write('a/input.txt', 'changed'); + await first[Symbol.asyncDispose](); + expect(fs.readFileSync(`${first.folder}/a/input.txt`, 'utf8')).toBe('changed'); + expect(fs.existsSync(first.host.paths.lockfilePath)).toBe(false); + + second = await DaemonGraphTestFixture.createAsync(); + expect(path.dirname(second.folder)).toBe(root); + expect(second.folder).not.toBe(first.folder); + expect(fs.readFileSync(`${second.folder}/a/input.txt`, 'utf8')).toBe(fixtureInput); + expect(fs.readFileSync(`${__dirname}/fixtures/graph/a/input.txt`, 'utf8')).toBe(fixtureInput); + } finally { + await second?.[Symbol.asyncDispose](); + await first[Symbol.asyncDispose](); + } +}, 30000); diff --git a/libraries/rush-daemon/src/test/DaemonGraphFixtureSetup.test.ts b/libraries/rush-daemon/src/test/DaemonGraphFixtureSetup.test.ts index b1131a1cebb..5f6978d0ecb 100644 --- a/libraries/rush-daemon/src/test/DaemonGraphFixtureSetup.test.ts +++ b/libraries/rush-daemon/src/test/DaemonGraphFixtureSetup.test.ts @@ -6,7 +6,6 @@ import * as fs from 'node:fs'; import { RushDaemonHost } from '../RushDaemonHost'; import { DaemonGraphTestFixture } from './DaemonGraphTestFixture'; import { createDeferred, hideResolvedValueAsync } from './DaemonRequestWireTestUtilities'; -import * as testProcessExit from './TestProcessExit'; describe('daemon graph fixture initialization ownership', () => { let cleanup: (() => Promise) | undefined; @@ -71,7 +70,7 @@ describe('daemon graph fixture initialization ownership', () => { release.resolve(); expect(await joined).toEqual([{ status: 'rejected', reason: controller.signal.reason }]); expect(closed).toBe(true); - expect(fs.existsSync(captured!.folder)).toBe(false); + expect(fs.existsSync(captured!.folder)).toBe(true); expect(fs.existsSync(host.paths.lockfilePath)).toBe(false); expect(published === undefined).toBe(true); } finally { @@ -79,7 +78,7 @@ describe('daemon graph fixture initialization ownership', () => { } }); - it('cleans partial setup and preserves its original failure', async () => { + it('retains partial setup for diagnosis and preserves its original failure', async () => { const failure: Error = new Error('injected partial graph fixture setup failure'); let captured: DaemonGraphTestFixture | undefined; await expect( @@ -90,7 +89,7 @@ describe('daemon graph fixture initialization ownership', () => { }) ) ).rejects.toBe(failure); - expect(fs.existsSync(captured!.folder)).toBe(false); + expect(fs.existsSync(captured!.folder)).toBe(true); expect(captured!.host).toBeUndefined(); }); @@ -98,7 +97,9 @@ describe('daemon graph fixture initialization ownership', () => { const failure: Error = new Error('injected graph fixture setup failure'); const cleanupFailure: Error = new Error('injected graph fixture cleanup failure'); let captured: DaemonGraphTestFixture | undefined; - const remove = jest.spyOn(testProcessExit, 'removeTestFolderAsync').mockRejectedValueOnce(cleanupFailure); + const dispose = jest + .spyOn(DaemonGraphTestFixture.prototype, Symbol.asyncDispose) + .mockRejectedValueOnce(cleanupFailure); try { await expect( hideResolvedValueAsync( @@ -110,7 +111,7 @@ describe('daemon graph fixture initialization ownership', () => { ).rejects.toMatchObject({ errors: [failure, cleanupFailure] }); expect(fs.existsSync(captured!.folder)).toBe(true); } finally { - remove.mockRestore(); + dispose.mockRestore(); if (captured) await captured[Symbol.asyncDispose](); } }); @@ -133,7 +134,7 @@ describe('daemon graph fixture initialization ownership', () => { ) ).rejects.toBe(controller.signal.reason); expect(start).not.toHaveBeenCalled(); - expect(fs.existsSync(captured!.folder)).toBe(false); + expect(fs.existsSync(captured!.folder)).toBe(true); } finally { start.mockRestore(); } diff --git a/libraries/rush-daemon/src/test/DaemonGraphTestFixture.ts b/libraries/rush-daemon/src/test/DaemonGraphTestFixture.ts index d0a42b35138..ad2be9dad71 100644 --- a/libraries/rush-daemon/src/test/DaemonGraphTestFixture.ts +++ b/libraries/rush-daemon/src/test/DaemonGraphTestFixture.ts @@ -3,7 +3,6 @@ import { execFileSync } from 'node:child_process'; import * as fs from 'node:fs'; -import * as os from 'node:os'; import * as path from 'node:path'; import { Rush } from '@microsoft/rush-lib'; @@ -30,7 +29,6 @@ import { type ITerminalExchange } from './DaemonRequestWireTestUtilities'; import { assertSuccessfulNativeBuild } from './NativeBuildTestResult'; -import { removeTestFolderAsync } from './TestProcessExit'; import { trackTestDaemonHostAsync } from './TestDaemonHostCleanup'; /** @@ -94,9 +92,7 @@ export class DaemonGraphTestFixture implements AsyncDisposable { * resolver's `workspaceLifecycle` (see `wrapWorkspaceResolverLifecycle`). Set it in `createAsync`'s `configure`. */ public wrapResolver: ((resolver: IDaemonRequestResolver) => IDaemonRequestResolver) | undefined; - public readonly folder: string = fs.realpathSync.native( - fs.mkdtempSync(path.join(os.tmpdir(), 'rushd-graph-')) - ); + public readonly folder: string; public readonly environment: Record = { ...Object.fromEntries( Object.entries(process.env).filter((pair): pair is [string, string] => pair[1] !== undefined) @@ -105,6 +101,11 @@ export class DaemonGraphTestFixture implements AsyncDisposable { #nextId: number = 0; #lifecycle: boolean = true; + public constructor(root: string = `${__dirname}/../../temp/test/graph`) { + fs.mkdirSync(root, { recursive: true }); + this.folder = fs.realpathSync.native(fs.mkdtempSync(`${root}/case-`)); + } + public static async createAsync( configure?: (fixture: DaemonGraphTestFixture) => void, lifecycle: boolean = true, @@ -114,54 +115,14 @@ export class DaemonGraphTestFixture implements AsyncDisposable { fixture.#lifecycle = lifecycle; try { signal?.throwIfAborted(); - fixture.write( - 'rush.json', - JSON.stringify({ - rushVersion: Rush.version, - npmVersion: '10.0.0', - // Graph-control assertions must not depend on the surrounding Jest worker's RSS. - // Warm-policy fixtures explicitly override this budget to exercise real pressure. - daemon: { warmMemoryBudgetMB: 100_000 }, - projectFolderMinDepth: 1, - projects: ['a', 'b', 'c'].map((name) => ({ packageName: name, projectFolder: name })) - }) + fs.cpSync(`${__dirname}/fixtures/graph`, fixture.folder, { recursive: true }); + fs.renameSync(`${fixture.folder}/gitignore`, `${fixture.folder}/.gitignore`); + const rushJson: { rushVersion: string } = JSON.parse( + fs.readFileSync(`${fixture.folder}/rush.json`, 'utf8') ); - fixture.write('.gitignore', 'common/temp/\n**/.rush/\n**/rush-logs/\nruns.txt\n'); + rushJson.rushVersion = Rush.version; + fixture.write('rush.json', JSON.stringify(rushJson)); fixture.write('common/temp/last-link.flag', '{}'); - fixture.write('common/config/rush/npm-shrinkwrap.json', '{"lockfileVersion":3,"packages":{}}'); - fixture.write( - 'common/config/rush/command-line.json', - JSON.stringify({ - phases: [{ name: '_phase:compile', dependencies: { upstream: ['_phase:compile'] } }], - commands: [ - { - commandKind: 'phased', - name: 'build', - phases: ['_phase:compile'], - incremental: true, - enableParallelism: true - } - ] - }) - ); - for (const name of ['a', 'b', 'c']) { - fixture.write( - `${name}/package.json`, - JSON.stringify({ - name, - version: '1.0.0', - dependencies: name === 'b' ? { a: '1.0.0' } : {}, - scripts: { '_phase:compile': 'node build.cjs' } - }) - ); - fixture.write(`${name}/input.txt`, 'one'); - fixture.write( - `${name}/build.cjs`, - "const fs=require('node:fs');const name=require('./package.json').name;" + - "fs.appendFileSync('../runs.txt',name+'\\n');console.log('building-'+name);" + - "setTimeout(()=>console.log('finished-'+name),150);" - ); - } configure?.(fixture); signal?.throwIfAborted(); execFileSync('git', ['init', '--quiet'], { cwd: fixture.folder }); @@ -238,13 +199,13 @@ export class DaemonGraphTestFixture implements AsyncDisposable { } public write(name: string, text: string): void { - const filename: string = path.join(this.folder, name); + const filename: string = `${this.folder}/${name}`; fs.mkdirSync(path.dirname(filename), { recursive: true }); fs.writeFileSync(filename, text); } public runs(): string[] { - const filename: string = path.join(this.folder, 'runs.txt'); + const filename: string = `${this.folder}/runs.txt`; return fs.existsSync(filename) ? fs.readFileSync(filename, 'utf8').trim().split('\n') : []; } @@ -299,7 +260,6 @@ export class DaemonGraphTestFixture implements AsyncDisposable { public async [Symbol.asyncDispose](): Promise { await this.host?.closeAsync(); - await removeTestFolderAsync(this.folder, true); } } diff --git a/libraries/rush-daemon/src/test/fixtures/README.md b/libraries/rush-daemon/src/test/fixtures/README.md new file mode 100644 index 00000000000..2340f6c8fe1 --- /dev/null +++ b/libraries/rush-daemon/src/test/fixtures/README.md @@ -0,0 +1,19 @@ +# Graph test fixtures + +The `graph` directory contains the immutable starting repository used by +`DaemonGraphTestFixture`. Heft copies these assets alongside the compiled tests. +Keep fixture scripts, package manifests, and initial file contents here rather +than assembling them as strings during test setup. + +Each fixture copies this repository into a fresh directory under the project's +`temp/test/graph` folder. Separate case directories allow multiple fixtures and +concurrent test runs without sharing mutable files. Setup substitutes the current +Rush version and creates the installation flag; tests may then deliberately +change files to exercise invalidation and other behavior. + +Disposal still awaits daemon shutdown and releases its resources. It retains the +workspace for diagnosis instead of recursively deleting it during teardown. +`heft run --only test -- --clean` removes `temp/test` before the next test run. + +The initial `input.txt` files intentionally have no trailing newline, matching the +original fixtures and cache-restoration assertions. diff --git a/libraries/rush-daemon/src/test/fixtures/graph/a/build.cjs b/libraries/rush-daemon/src/test/fixtures/graph/a/build.cjs new file mode 100644 index 00000000000..e28466dba4b --- /dev/null +++ b/libraries/rush-daemon/src/test/fixtures/graph/a/build.cjs @@ -0,0 +1,5 @@ +const fs = require('node:fs'); +const name = require('./package.json').name; +fs.appendFileSync('../runs.txt', name + '\n'); +console.log('building-' + name); +setTimeout(() => console.log('finished-' + name), 150); diff --git a/libraries/rush-daemon/src/test/fixtures/graph/a/input.txt b/libraries/rush-daemon/src/test/fixtures/graph/a/input.txt new file mode 100644 index 00000000000..43dd47ea691 --- /dev/null +++ b/libraries/rush-daemon/src/test/fixtures/graph/a/input.txt @@ -0,0 +1 @@ +one \ No newline at end of file diff --git a/libraries/rush-daemon/src/test/fixtures/graph/a/package.json b/libraries/rush-daemon/src/test/fixtures/graph/a/package.json new file mode 100644 index 00000000000..d2cdea2e52d --- /dev/null +++ b/libraries/rush-daemon/src/test/fixtures/graph/a/package.json @@ -0,0 +1,8 @@ +{ + "name": "a", + "version": "1.0.0", + "dependencies": {}, + "scripts": { + "_phase:compile": "node build.cjs" + } +} diff --git a/libraries/rush-daemon/src/test/fixtures/graph/b/build.cjs b/libraries/rush-daemon/src/test/fixtures/graph/b/build.cjs new file mode 100644 index 00000000000..e28466dba4b --- /dev/null +++ b/libraries/rush-daemon/src/test/fixtures/graph/b/build.cjs @@ -0,0 +1,5 @@ +const fs = require('node:fs'); +const name = require('./package.json').name; +fs.appendFileSync('../runs.txt', name + '\n'); +console.log('building-' + name); +setTimeout(() => console.log('finished-' + name), 150); diff --git a/libraries/rush-daemon/src/test/fixtures/graph/b/input.txt b/libraries/rush-daemon/src/test/fixtures/graph/b/input.txt new file mode 100644 index 00000000000..43dd47ea691 --- /dev/null +++ b/libraries/rush-daemon/src/test/fixtures/graph/b/input.txt @@ -0,0 +1 @@ +one \ No newline at end of file diff --git a/libraries/rush-daemon/src/test/fixtures/graph/b/package.json b/libraries/rush-daemon/src/test/fixtures/graph/b/package.json new file mode 100644 index 00000000000..a54d9a9c915 --- /dev/null +++ b/libraries/rush-daemon/src/test/fixtures/graph/b/package.json @@ -0,0 +1,10 @@ +{ + "name": "b", + "version": "1.0.0", + "dependencies": { + "a": "1.0.0" + }, + "scripts": { + "_phase:compile": "node build.cjs" + } +} diff --git a/libraries/rush-daemon/src/test/fixtures/graph/c/build.cjs b/libraries/rush-daemon/src/test/fixtures/graph/c/build.cjs new file mode 100644 index 00000000000..e28466dba4b --- /dev/null +++ b/libraries/rush-daemon/src/test/fixtures/graph/c/build.cjs @@ -0,0 +1,5 @@ +const fs = require('node:fs'); +const name = require('./package.json').name; +fs.appendFileSync('../runs.txt', name + '\n'); +console.log('building-' + name); +setTimeout(() => console.log('finished-' + name), 150); diff --git a/libraries/rush-daemon/src/test/fixtures/graph/c/input.txt b/libraries/rush-daemon/src/test/fixtures/graph/c/input.txt new file mode 100644 index 00000000000..43dd47ea691 --- /dev/null +++ b/libraries/rush-daemon/src/test/fixtures/graph/c/input.txt @@ -0,0 +1 @@ +one \ No newline at end of file diff --git a/libraries/rush-daemon/src/test/fixtures/graph/c/package.json b/libraries/rush-daemon/src/test/fixtures/graph/c/package.json new file mode 100644 index 00000000000..6c7df3c8634 --- /dev/null +++ b/libraries/rush-daemon/src/test/fixtures/graph/c/package.json @@ -0,0 +1,8 @@ +{ + "name": "c", + "version": "1.0.0", + "dependencies": {}, + "scripts": { + "_phase:compile": "node build.cjs" + } +} diff --git a/libraries/rush-daemon/src/test/fixtures/graph/common/config/rush/command-line.json b/libraries/rush-daemon/src/test/fixtures/graph/common/config/rush/command-line.json new file mode 100644 index 00000000000..77286b8b599 --- /dev/null +++ b/libraries/rush-daemon/src/test/fixtures/graph/common/config/rush/command-line.json @@ -0,0 +1,12 @@ +{ + "phases": [{ "name": "_phase:compile", "dependencies": { "upstream": ["_phase:compile"] } }], + "commands": [ + { + "commandKind": "phased", + "name": "build", + "phases": ["_phase:compile"], + "incremental": true, + "enableParallelism": true + } + ] +} diff --git a/libraries/rush-daemon/src/test/fixtures/graph/common/config/rush/npm-shrinkwrap.json b/libraries/rush-daemon/src/test/fixtures/graph/common/config/rush/npm-shrinkwrap.json new file mode 100644 index 00000000000..7be60d9ad23 --- /dev/null +++ b/libraries/rush-daemon/src/test/fixtures/graph/common/config/rush/npm-shrinkwrap.json @@ -0,0 +1,4 @@ +{ + "lockfileVersion": 3, + "packages": {} +} diff --git a/libraries/rush-daemon/src/test/fixtures/graph/gitignore b/libraries/rush-daemon/src/test/fixtures/graph/gitignore new file mode 100644 index 00000000000..7be860668de --- /dev/null +++ b/libraries/rush-daemon/src/test/fixtures/graph/gitignore @@ -0,0 +1,4 @@ +common/temp/ +**/.rush/ +**/rush-logs/ +runs.txt diff --git a/libraries/rush-daemon/src/test/fixtures/graph/rush.json b/libraries/rush-daemon/src/test/fixtures/graph/rush.json new file mode 100644 index 00000000000..97822309b0d --- /dev/null +++ b/libraries/rush-daemon/src/test/fixtures/graph/rush.json @@ -0,0 +1,13 @@ +{ + "rushVersion": "0.0.0", + "npmVersion": "10.0.0", + "daemon": { + "warmMemoryBudgetMB": 100000 + }, + "projectFolderMinDepth": 1, + "projects": [ + { "packageName": "a", "projectFolder": "a" }, + { "packageName": "b", "projectFolder": "b" }, + { "packageName": "c", "projectFolder": "c" } + ] +} From 1e17bdb36aeeacf672b6be9bc303a0ceef08850c Mon Sep 17 00:00:00 2001 From: Ian Clanton-Thuon Date: Thu, 29 Oct 2026 23:22:41 -0700 Subject: [PATCH 2/4] [rush-client-core] Keep project fixture sockets within CI path limits Use temp/sXXXXXX for the startup cases and clean only that generated workspace pattern. The longest staging socket in the Linux CI checkout now fits its 107-byte usable path limit, including maximum Linux PID digits. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- libraries/rush-client-core/config/heft.json | 2 +- .../rush-client-core/src/test/connectOrStartDaemon.test.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/libraries/rush-client-core/config/heft.json b/libraries/rush-client-core/config/heft.json index b7597218dca..5221b2d63ee 100644 --- a/libraries/rush-client-core/config/heft.json +++ b/libraries/rush-client-core/config/heft.json @@ -2,7 +2,7 @@ "extends": "local-node-rig/profiles/default/config/heft.json", "phasesByName": { "test": { - "cleanFiles": [{ "includeGlobs": ["temp/test"] }] + "cleanFiles": [{ "includeGlobs": ["temp/test", "temp/s??????"] }] } } } diff --git a/libraries/rush-client-core/src/test/connectOrStartDaemon.test.ts b/libraries/rush-client-core/src/test/connectOrStartDaemon.test.ts index d93db99b5fd..2522bb58118 100644 --- a/libraries/rush-client-core/src/test/connectOrStartDaemon.test.ts +++ b/libraries/rush-client-core/src/test/connectOrStartDaemon.test.ts @@ -63,7 +63,7 @@ import { waitForTestProcessExitAsync } from './TestProcessExit'; /** How long after a launch a client may take over its reservation once the helper exited. */ const RELAUNCH_DELAY_MS: number = 15000; -const TEST_ROOT: string = `${__dirname}/../../temp/test/s`; // Leave room for Unix socket names. +const TEST_ROOT: string = `${__dirname}/../../temp`; // Leave room for Unix socket names on CI. function readIfPresent(filePath: string): string { return fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : ''; @@ -78,7 +78,7 @@ describe('detached daemon startup', () => { beforeEach(() => { starterProcesses = []; fs.mkdirSync(TEST_ROOT, { recursive: true }); - folder = fs.realpathSync.native(fs.mkdtempSync(`${TEST_ROOT}/c-`)); + folder = fs.realpathSync.native(fs.mkdtempSync(`${TEST_ROOT}/s`)); paths = { runtimeDir: folder, socketPath: From 3ce23ff96187dfc4a9a75d5b872ff153e97f406f Mon Sep 17 00:00:00 2001 From: Ian Clanton-Thuon Date: Thu, 29 Oct 2026 23:32:32 -0700 Subject: [PATCH 3/4] [rushstack] Preserve fixture bytes on Windows checkout Pin immutable fixture text to LF so copied Git inputs keep the byte hashes that the tests assert. Keep the existing hash and cache-restoration assertions unchanged. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- libraries/package-deps-hash/src/test/fixtures/.gitattributes | 1 + libraries/rush-daemon/src/test/fixtures/.gitattributes | 1 + libraries/rush-daemon/src/test/fixtures/README.md | 3 ++- 3 files changed, 4 insertions(+), 1 deletion(-) create mode 100644 libraries/package-deps-hash/src/test/fixtures/.gitattributes create mode 100644 libraries/rush-daemon/src/test/fixtures/.gitattributes diff --git a/libraries/package-deps-hash/src/test/fixtures/.gitattributes b/libraries/package-deps-hash/src/test/fixtures/.gitattributes new file mode 100644 index 00000000000..fcadb2cf979 --- /dev/null +++ b/libraries/package-deps-hash/src/test/fixtures/.gitattributes @@ -0,0 +1 @@ +* text eol=lf diff --git a/libraries/rush-daemon/src/test/fixtures/.gitattributes b/libraries/rush-daemon/src/test/fixtures/.gitattributes new file mode 100644 index 00000000000..fcadb2cf979 --- /dev/null +++ b/libraries/rush-daemon/src/test/fixtures/.gitattributes @@ -0,0 +1 @@ +* text eol=lf diff --git a/libraries/rush-daemon/src/test/fixtures/README.md b/libraries/rush-daemon/src/test/fixtures/README.md index 2340f6c8fe1..2020a18e51e 100644 --- a/libraries/rush-daemon/src/test/fixtures/README.md +++ b/libraries/rush-daemon/src/test/fixtures/README.md @@ -16,4 +16,5 @@ workspace for diagnosis instead of recursively deleting it during teardown. `heft run --only test -- --clean` removes `temp/test` before the next test run. The initial `input.txt` files intentionally have no trailing newline, matching the -original fixtures and cache-restoration assertions. +original fixtures and cache-restoration assertions. The fixture-local attributes +file pins text to LF so a Windows checkout preserves the intended input bytes. From 8a8e375b83348334c7cfbdb41a9fb60a6a500e8a Mon Sep 17 00:00:00 2001 From: Ian Clanton-Thuon Date: Thu, 29 Oct 2026 23:52:39 -0700 Subject: [PATCH 4/4] [rushstack] Use FileSystem in migrated integration tests Use node-core-library helpers for ordinary reads, writes, copies, path resolution, directory enumeration, and timestamps in the fixture cleanup. Preserve Buffer reads, strict file-deletion errors, and native APIs needed for temporary allocation, bigint stats, permissions, links, or native fs interception. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../src/test/GitIndexFile.test.ts | 61 +-- .../src/test/RepoStateCache.test.ts | 157 +++---- .../src/test/connectOrStartDaemon.test.ts | 398 +++++++++--------- .../src/test/DaemonGraphFixturePaths.test.ts | 22 +- .../src/test/DaemonGraphFixtureSetup.test.ts | 14 +- .../src/test/DaemonGraphTestFixture.ts | 21 +- 6 files changed, 347 insertions(+), 326 deletions(-) diff --git a/libraries/package-deps-hash/src/test/GitIndexFile.test.ts b/libraries/package-deps-hash/src/test/GitIndexFile.test.ts index 624719b225b..16d617a1093 100644 --- a/libraries/package-deps-hash/src/test/GitIndexFile.test.ts +++ b/libraries/package-deps-hash/src/test/GitIndexFile.test.ts @@ -6,6 +6,8 @@ import { createHash } from 'node:crypto'; import * as fs from 'node:fs'; import * as path from 'node:path'; +import { FileSystem } from '@rushstack/node-core-library'; + import { type IGitIndexExtension, type IGitIndexSummary, @@ -24,7 +26,7 @@ const LONG_FILE_PATH: string = `dir/sub/${'long-name-'.repeat(12)}.txt`; const TEST_ROOT: string = `${__dirname}/../../temp/test/git-index`; function createTestFolder(): string { - fs.mkdirSync(TEST_ROOT, { recursive: true }); + FileSystem.ensureFolder(TEST_ROOT); return fs.mkdtempSync(`${TEST_ROOT}/case-`); } @@ -53,9 +55,7 @@ function runGitWithIndex(indexPath: string, ...args: string[]): string { } function writeFile(relativePath: string, content: string): void { - const filePath: string = path.join(repoPath, relativePath); - fs.mkdirSync(path.dirname(filePath), { recursive: true }); - fs.writeFileSync(filePath, content); + FileSystem.writeFile(`${repoPath}/${relativePath}`, content, { ensureFolderExists: true }); } function getIndexPath(): string { @@ -63,7 +63,7 @@ function getIndexPath(): string { } function readIndex(): Buffer { - return fs.readFileSync(getIndexPath()); + return FileSystem.readFileToBuffer(getIndexPath()); } function createRepo(...initArgs: string[]): void { @@ -73,7 +73,7 @@ function createRepo(...initArgs: string[]): void { runGit('config', 'index.skipHash', 'false'); // Windows runners turn this on in the system configuration, and Git then warns about each file that it adds runGit('config', 'core.autocrlf', 'false'); - fs.cpSync(`${__dirname}/fixtures/git-index`, repoPath, { recursive: true }); + FileSystem.copyFiles({ sourcePath: `${__dirname}/fixtures/git-index`, destinationPath: repoPath }); runGit('add', '.'); } @@ -128,7 +128,7 @@ describe(summarizeGitIndex.name, () => { // Change the recorded times of a file, and the untracked cache const time: number = Math.floor(Date.now() / 1000) - 100; - fs.utimesSync(path.join(repoPath, 'a.txt'), time, time); + FileSystem.updateTimes(path.join(repoPath, 'a.txt'), { accessedTime: time, modifiedTime: time }); writeFile('untracked.txt', 'untracked\n'); runGit('status', '--porcelain'); @@ -179,15 +179,15 @@ describe(summarizeGitIndex.name, () => { // Git writes the file with other line endings, and records its new size runGit('config', 'core.autocrlf', 'true'); - fs.unlinkSync(path.join(repoPath, 'a.txt')); + FileSystem.deleteFile(path.join(repoPath, 'a.txt'), { throwIfNotExists: true }); runGit('checkout', '--', 'a.txt'); - expect(fs.readFileSync(path.join(repoPath, 'a.txt'), 'utf8')).toBe('a\r\n'); + expect(FileSystem.readFile(path.join(repoPath, 'a.txt'))).toBe('a\r\n'); let summary: IGitIndexSummary = summarize(); expect(summary.entriesDigest).toBe(initialSummary.entriesDigest); expect(summary.sizesDigest).not.toBe(initialSummary.sizesDigest); runGit('config', 'core.autocrlf', 'false'); - fs.unlinkSync(path.join(repoPath, 'a.txt')); + FileSystem.deleteFile(path.join(repoPath, 'a.txt'), { throwIfNotExists: true }); runGit('checkout', '--', 'a.txt'); summary = summarize(); expect(summary.entriesDigest).toBe(initialSummary.entriesDigest); @@ -423,18 +423,18 @@ describe(tryCarryOverGitIndexCaches.name, () => { // Git doesn't trust the recorded times of a file or folder that changed in the same second as the index was saved function settleWorkingTree(folderPath: string, time: number): void { - for (const entry of fs.readdirSync(folderPath, { withFileTypes: true })) { + for (const entry of FileSystem.readFolderItems(folderPath)) { if (entry.name !== '.git') { const entryPath: string = path.join(folderPath, entry.name); if (entry.isDirectory()) { settleWorkingTree(entryPath, time); } - fs.utimesSync(entryPath, time, time); + FileSystem.updateTimes(entryPath, { accessedTime: time, modifiedTime: time }); } } - fs.utimesSync(folderPath, time, time); + FileSystem.updateTimes(folderPath, { accessedTime: time, modifiedTime: time }); } // Creates a repository with untracked files, and a copy of its index in which Git saved the untracked cache @@ -448,9 +448,9 @@ describe(tryCarryOverGitIndexCaches.name, () => { settleWorkingTree(repoPath, Math.floor(Date.now() / 1000) - 100); runGit('update-index', '--refresh'); commit(); - fs.copyFileSync(getIndexPath(), copyPath); + FileSystem.copyFile({ sourcePath: getIndexPath(), destinationPath: copyPath }); runGitWithIndex(copyPath, 'status', '--porcelain'); - expect(getExtension(fs.readFileSync(copyPath), 'UNTR', objectIdLength)).toBeDefined(); + expect(getExtension(FileSystem.readFileToBuffer(copyPath), 'UNTR', objectIdLength)).toBeDefined(); } function stageModifiedFile(): void { @@ -461,14 +461,14 @@ describe(tryCarryOverGitIndexCaches.name, () => { function carryOver(objectIdLength: number = SHA1_OBJECT_ID_LENGTH): Buffer { const content: Buffer | undefined = tryCarryOverGitIndexCaches( readIndex(), - fs.readFileSync(copyPath), + FileSystem.readFileToBuffer(copyPath), objectIdLength ); if (!content) { throw new Error('The new copy did not keep the caches of the previous copy'); } - fs.writeFileSync(newCopyPath, content); + FileSystem.writeFile(newCopyPath, content); return content; } @@ -491,7 +491,7 @@ describe(tryCarryOverGitIndexCaches.name, () => { .split('\n') .filter((line: string) => line) .map((line: string) => JSON.parse(line)); - fs.unlinkSync(tracePath); + FileSystem.deleteFile(tracePath, { throwIfNotExists: true }); const openedFolderCounts: number[] = events .filter(({ category, key }: ITrace2Event) => category === 'read_directory' && key === 'opendir') .map(({ value }: ITrace2Event) => Number(value)); @@ -518,7 +518,9 @@ describe(tryCarryOverGitIndexCaches.name, () => { ...getSignatures(index).filter((signature: string) => !replacedSignatures.has(signature)), 'UNTR' ]); - expect(getExtension(content, 'UNTR')).toEqual(getExtension(fs.readFileSync(copyPath), 'UNTR')); + expect(getExtension(content, 'UNTR')).toEqual( + getExtension(FileSystem.readFileToBuffer(copyPath), 'UNTR') + ); expect(content.subarray(-SHA1_OBJECT_ID_LENGTH)).toEqual( createHash('sha1').update(content.subarray(0, -SHA1_OBJECT_ID_LENGTH)).digest() ); @@ -538,7 +540,7 @@ describe(tryCarryOverGitIndexCaches.name, () => { const content: Buffer = carryOver(SHA256_OBJECT_ID_LENGTH); expect(getExtension(content, 'UNTR', SHA256_OBJECT_ID_LENGTH)).toEqual( - getExtension(fs.readFileSync(copyPath), 'UNTR', SHA256_OBJECT_ID_LENGTH) + getExtension(FileSystem.readFileToBuffer(copyPath), 'UNTR', SHA256_OBJECT_ID_LENGTH) ); expect(content.subarray(-SHA256_OBJECT_ID_LENGTH)).toEqual( createHash('sha256').update(content.subarray(0, -SHA256_OBJECT_ID_LENGTH)).digest() @@ -596,7 +598,7 @@ describe(tryCarryOverGitIndexCaches.name, () => { change(); expect(tryGetGitIndexEntryCount(readIndex())).toBe(entryCount); expect( - tryCarryOverGitIndexCaches(readIndex(), fs.readFileSync(copyPath), SHA1_OBJECT_ID_LENGTH) + tryCarryOverGitIndexCaches(readIndex(), FileSystem.readFileToBuffer(copyPath), SHA1_OBJECT_ID_LENGTH) ).toBeUndefined(); }); @@ -610,7 +612,7 @@ describe(tryCarryOverGitIndexCaches.name, () => { createRepoWithCopy(previousVersion); setIndexVersion(version); expect( - tryCarryOverGitIndexCaches(readIndex(), fs.readFileSync(copyPath), SHA1_OBJECT_ID_LENGTH) + tryCarryOverGitIndexCaches(readIndex(), FileSystem.readFileToBuffer(copyPath), SHA1_OBJECT_ID_LENGTH) ).toBeUndefined(); } ); @@ -618,7 +620,7 @@ describe(tryCarryOverGitIndexCaches.name, () => { it('returns undefined when the previous copy has no untracked cache', () => { createRepoWithCopy(4); runGitWithIndex(copyPath, '-c', 'core.untrackedCache=false', 'status', '--porcelain'); - const previousContent: Buffer = fs.readFileSync(copyPath); + const previousContent: Buffer = FileSystem.readFileToBuffer(copyPath); expect(getExtension(previousContent, 'UNTR')).toBeUndefined(); stageModifiedFile(); expect(tryCarryOverGitIndexCaches(readIndex(), previousContent, SHA1_OBJECT_ID_LENGTH)).toBeUndefined(); @@ -628,7 +630,7 @@ describe(tryCarryOverGitIndexCaches.name, () => { createRepoWithCopy(4); stageModifiedFile(); const index: Buffer = insertExtension(readIndex(), 'ZZZZ', Buffer.from('data')); - const previousContent: Buffer = fs.readFileSync(copyPath); + const previousContent: Buffer = FileSystem.readFileToBuffer(copyPath); const content: Buffer | undefined = tryCarryOverGitIndexCaches( index, previousContent, @@ -659,7 +661,7 @@ describe(tryCarryOverGitIndexCaches.name, () => { it('throws when the previous copy is not an index', () => { createRepoWithCopy(4); - const previousContent: Buffer = fs.readFileSync(copyPath); + const previousContent: Buffer = FileSystem.readFileToBuffer(copyPath); expect(() => tryCarryOverGitIndexCaches(readIndex(), previousContent.subarray(0, 100), SHA1_OBJECT_ID_LENGTH) ).toThrow('The Git index ends within an entry'); @@ -697,7 +699,10 @@ describe(tryCarryOverGitIndexCaches.name, () => { // Git asks the hook for every change, since the copy has no token, and then saves the token of the hook runGitWithFsmonitor(copyPath, 'status', '--porcelain'); runGitWithFsmonitor(copyPath, 'update-index', '--no-fsmonitor-valid', 'dir/b.txt'); - expect(readFsmonitorState(fs.readFileSync(copyPath))).toEqual({ token: 't:0', changedEntries: [1] }); + expect(readFsmonitorState(FileSystem.readFileToBuffer(copyPath))).toEqual({ + token: 't:0', + changedEntries: [1] + }); modifyFile('a.txt'); runGit('add', 'a.txt'); @@ -724,7 +729,7 @@ describe(tryCarryOverGitIndexCaches.name, () => { hook = createFsmonitorHook(path.join(repoPath, '.git')); runGitWithFsmonitor(copyPath, 'status', '--porcelain'); runGitWithFsmonitor(copyPath, 'update-index', '--no-fsmonitor-valid', ...filePaths); - const previousContent: Buffer = fs.readFileSync(copyPath); + const previousContent: Buffer = FileSystem.readFileToBuffer(copyPath); const previousState: IFsmonitorState = readFsmonitorState(previousContent); expect(previousState).toEqual({ token: 't:0', changedEntries: getRange(4, 204) }); @@ -783,7 +788,7 @@ describe(tryCarryOverGitIndexCaches.name, () => { hook = createFsmonitorHook(path.join(repoPath, '.git')); runGitWithFsmonitor(copyPath, 'status', '--porcelain'); stageModifiedFile(); - const previousContent: Buffer = fs.readFileSync(copyPath); + const previousContent: Buffer = FileSystem.readFileToBuffer(copyPath); expect(tryCarryOverGitIndexCaches(readIndex(), previousContent, SHA1_OBJECT_ID_LENGTH)).toBeDefined(); // An unknown version diff --git a/libraries/package-deps-hash/src/test/RepoStateCache.test.ts b/libraries/package-deps-hash/src/test/RepoStateCache.test.ts index 5dc19f1a50a..216f0cf8829 100644 --- a/libraries/package-deps-hash/src/test/RepoStateCache.test.ts +++ b/libraries/package-deps-hash/src/test/RepoStateCache.test.ts @@ -5,7 +5,7 @@ import { type ChildProcess, execFileSync } from 'node:child_process'; import * as fs from 'node:fs'; import * as path from 'node:path'; -import { Executable, type IExecutableSpawnOptions } from '@rushstack/node-core-library'; +import { Executable, FileSystem, type IExecutableSpawnOptions } from '@rushstack/node-core-library'; import * as GitIndexFile from '../GitIndexFile'; import { getDetailedRepoStateAsync, type IDetailedRepoState } from '../getRepoState'; @@ -114,11 +114,10 @@ describe(RepoStateCache.name, () => { } function writeFile(relativePath: string, content: string): void { - const filePath: string = path.join(repoPath, relativePath); - fs.mkdirSync(path.dirname(filePath), { recursive: true }); - fs.writeFileSync(filePath, content); + const filePath: string = `${repoPath}/${relativePath}`; + FileSystem.writeFile(filePath, content, { ensureFolderExists: true }); // The first read can update ctime on Windows. Settle that metadata before tests memoize the stamp. - fs.readFileSync(filePath); + FileSystem.readFileToBuffer(filePath); } function commit(): void { @@ -127,7 +126,7 @@ describe(RepoStateCache.name, () => { } function getPrivateIndexPath(): string { - const [folderName] = fs.readdirSync(temporaryFolderPath); + const [folderName] = FileSystem.readFolderItemNames(temporaryFolderPath); return path.join(temporaryFolderPath, folderName, 'index'); } @@ -144,7 +143,7 @@ describe(RepoStateCache.name, () => { // Changes the recorded times of a file, but not its content, so that "git status" saves the refreshed index function touchSettledFile(relativePath: string): void { const time: number = Math.floor(originalDateNow() / 1000) - 100; - fs.utimesSync(path.join(repoPath, relativePath), time, time); + FileSystem.updateTimes(path.join(repoPath, relativePath), { accessedTime: time, modifiedTime: time }); } function takeGitCommands(): IGitCommand[] { @@ -191,15 +190,18 @@ describe(RepoStateCache.name, () => { } beforeEach(() => { - fs.mkdirSync(TEST_ROOT, { recursive: true }); + FileSystem.ensureFolder(TEST_ROOT); const testFolder: string = fs.mkdtempSync(`${TEST_ROOT}/case-`); repoPath = `${testFolder}/repo`; temporaryFolderPath = `${testFolder}/private`; - fs.cpSync(`${FIXTURE_ROOT}/repo`, repoPath, { recursive: true }); - repoPath = fs.realpathSync.native(repoPath); - fs.mkdirSync(temporaryFolderPath); + FileSystem.copyFiles({ sourcePath: `${FIXTURE_ROOT}/repo`, destinationPath: repoPath }); + repoPath = FileSystem.getRealPath(repoPath); + FileSystem.ensureFolder(temporaryFolderPath); runGit('init', '--quiet'); - fs.appendFileSync(`${repoPath}/.git/config`, fs.readFileSync(`${FIXTURE_ROOT}/git-config`)); + FileSystem.appendToFile( + `${repoPath}/.git/config`, + FileSystem.readFileToBuffer(`${FIXTURE_ROOT}/git-config`) + ); commit(); cache = new RepoStateCache({ rootDirectory: repoPath, temporaryFolderPath }); @@ -255,7 +257,7 @@ describe(RepoStateCache.name, () => { for (const content of ['first\n', 'changed\n']) { writeFile('untracked.txt', content); const { ctimeNs } = fs.statSync(filePath, { bigint: true }); - fs.readFileSync(filePath); + FileSystem.readFileToBuffer(filePath); expect(fs.statSync(filePath, { bigint: true }).ctimeNs).toBe(ctimeNs); } }); @@ -287,9 +289,9 @@ describe(RepoStateCache.name, () => { () => writeFile('a.txt', 'modified\n'), () => writeFile('a.txt', 'modified again\n'), () => writeFile('new.txt', 'new\n'), - () => fs.unlinkSync(path.join(repoPath, 'b.txt')), + () => FileSystem.deleteFile(path.join(repoPath, 'b.txt'), { throwIfNotExists: true }), () => runGit('checkout', '--', 'b.txt'), - () => fs.unlinkSync(path.join(repoPath, 'new.txt')), + () => FileSystem.deleteFile(path.join(repoPath, 'new.txt'), { throwIfNotExists: true }), () => runGit('checkout', '--', 'a.txt') ]; for (const change of changes) { @@ -388,12 +390,12 @@ describe(RepoStateCache.name, () => { const filePath: string = path.join(repoPath, 'untracked.txt'); const time: number = Math.floor(originalDateNow() / 1000) - 100; writeFile('untracked.txt', 'one\n'); - fs.utimesSync(filePath, time, time); + FileSystem.updateTimes(filePath, { accessedTime: time, modifiedTime: time }); await getStateAsync(['untracked.txt']); // Only the change time of the file reveals the change, since userspace can't set it writeFile('untracked.txt', 'two\n'); - fs.utimesSync(filePath, time, time); + FileSystem.updateTimes(filePath, { accessedTime: time, modifiedTime: time }); takeGitCommands(); const state: IDetailedRepoState = await getStateAsync(['untracked.txt']); expect(takeGitCommandNames()).toEqual(['hash-object', 'status']); @@ -476,12 +478,12 @@ describe(RepoStateCache.name, () => { await getStateAsync(); const indexPath: string = path.join(repoPath, '.git', 'index'); - const indexInode: number = fs.statSync(indexPath).ino; + const indexInode: number = FileSystem.getStatistics(indexPath).ino; const time: number = Math.floor(originalDateNow() / 1000) - 100; - fs.utimesSync(path.join(repoPath, 'a.txt'), time, time); + FileSystem.updateTimes(path.join(repoPath, 'a.txt'), { accessedTime: time, modifiedTime: time }); runGit('status', '--porcelain'); // Git replaced the index - expect(fs.statSync(indexPath).ino).not.toBe(indexInode); + expect(FileSystem.getStatistics(indexPath).ino).not.toBe(indexInode); takeGitCommands(); const state: IDetailedRepoState = await getStateAsync(); @@ -496,12 +498,12 @@ describe(RepoStateCache.name, () => { runGit('config', 'core.checkStat', 'minimal'); const time: number = Math.floor(originalDateNow() / 1000) - 100; const filePath: string = path.join(repoPath, 'a.txt'); - fs.utimesSync(filePath, time, time); + FileSystem.updateTimes(filePath, { accessedTime: time, modifiedTime: time }); runGit('update-index', '--refresh'); // The index was saved in the same second as the file changed, so Git must not trust the recorded times - fs.utimesSync(path.join(repoPath, '.git', 'index'), time, time); - fs.writeFileSync(filePath, 'A\n'); - fs.utimesSync(filePath, time, time); + FileSystem.updateTimes(path.join(repoPath, '.git', 'index'), { accessedTime: time, modifiedTime: time }); + FileSystem.writeFile(filePath, 'A\n'); + FileSystem.updateTimes(filePath, { accessedTime: time, modifiedTime: time }); const state: IDetailedRepoState = await getStateAsync(); await expectUncachedStateAsync(state); @@ -513,13 +515,16 @@ describe(RepoStateCache.name, () => { runGit('config', 'core.checkStat', 'minimal'); const time: number = Math.floor(originalDateNow() / 1000) - 100; const filePath: string = path.join(repoPath, 'a.txt'); - fs.utimesSync(filePath, time, time); + FileSystem.updateTimes(filePath, { accessedTime: time, modifiedTime: time }); runGit('update-index', '--refresh'); // The index was saved a second after the file changed, so Git trusts the recorded times and size, and // getDetailedRepoStateAsync misses the change. The copy of the index is older. - fs.utimesSync(path.join(repoPath, '.git', 'index'), time + 1, time + 1); - fs.writeFileSync(filePath, 'A\n'); - fs.utimesSync(filePath, time, time); + FileSystem.updateTimes(path.join(repoPath, '.git', 'index'), { + accessedTime: time + 1, + modifiedTime: time + 1 + }); + FileSystem.writeFile(filePath, 'A\n'); + FileSystem.updateTimes(filePath, { accessedTime: time, modifiedTime: time }); const state: IDetailedRepoState = await getStateAsync(); expect(state.files.get('a.txt')).toBe(runGit('hash-object', 'a.txt').trim()); @@ -549,7 +554,7 @@ describe(RepoStateCache.name, () => { settleFiles(); runGit('config', 'core.autocrlf', 'true'); // Git writes the file with CRLF line endings - fs.unlinkSync(path.join(repoPath, 'a.txt')); + FileSystem.deleteFile(path.join(repoPath, 'a.txt'), { throwIfNotExists: true }); runGit('checkout', '--', 'a.txt'); await getStateAsync(); // Git refreshes the recorded times of the file in the copy of the index, but not in the index @@ -572,7 +577,7 @@ describe(RepoStateCache.name, () => { it('copies the index again on each call while the configuration of the repository may still change', async () => { runGit('config', 'core.autocrlf', 'true'); // Git writes the file with CRLF line endings - fs.unlinkSync(path.join(repoPath, 'a.txt')); + FileSystem.deleteFile(path.join(repoPath, 'a.txt'), { throwIfNotExists: true }); runGit('checkout', '--', 'a.txt'); // Git refreshes the recorded times of the file in the copy of the index, but not in the index touchSettledFile('a.txt'); @@ -665,7 +670,9 @@ describe(RepoStateCache.name, () => { commit(); runGit('update-index', flag, '--', attributesPath); runGit('update-index', `--index-version=${indexVersion}`); - expect(fs.readFileSync(path.join(repoPath, '.git', 'index')).readUInt32BE(4)).toBe(indexVersion); + expect(FileSystem.readFileToBuffer(path.join(repoPath, '.git', 'index')).readUInt32BE(4)).toBe( + indexVersion + ); await getStateAsync(); // Git refreshes the recorded times of the file in the copy of the index, but not in the index touchSettledFile('dir/crlf.txt'); @@ -753,7 +760,7 @@ describe(RepoStateCache.name, () => { writeFile('ignored/crlf.txt', 'a\r\n'); // The attributes file changes after the calls start, but "git status" doesn't list it const time: number = Math.floor(originalDateNow() / 1000) + 60; - fs.utimesSync(path.join(repoPath, '.gitattributes'), time, time); + FileSystem.updateTimes(path.join(repoPath, '.gitattributes'), { accessedTime: time, modifiedTime: time }); const additionalPaths: string[] = ['ignored/crlf.txt']; await getStateAsync(additionalPaths); takeGitCommands(); @@ -805,13 +812,13 @@ describe(RepoStateCache.name, () => { writeFile('a.txt', 'modified\n'); await getStateAsync(); const configurationPath: string = path.join(repoPath, '.git', 'config'); - const { ino } = fs.statSync(configurationPath); + const { ino } = FileSystem.getStatistics(configurationPath); const writeFileSpy: jest.SpyInstance = jest.spyOn(fs.promises, 'writeFile'); // Git writes a new file with the same content when it deletes a branch that has no configuration runGit('branch', 'other'); runGit('branch', '-D', 'other'); - expect(fs.statSync(configurationPath).ino).not.toBe(ino); + expect(FileSystem.getStatistics(configurationPath).ino).not.toBe(ino); takeGitCommands(); const state: IDetailedRepoState = await getStateAsync(); await expectUncachedStateAsync(state); @@ -839,7 +846,7 @@ describe(RepoStateCache.name, () => { writeFile('a.txt', 'modified\n'); // Git ignores a folder in place of the file const attributesPath: string = path.join(repoPath, '.git', 'info', 'attributes'); - fs.mkdirSync(attributesPath, { recursive: true }); + FileSystem.ensureFolder(attributesPath); await getStateAsync(); const writeFileSpy: jest.SpyInstance = jest.spyOn(fs.promises, 'writeFile'); takeGitCommands(); @@ -859,7 +866,7 @@ describe(RepoStateCache.name, () => { writeFile('a.txt', 'modified\r\n'); await getStateAsync(); const configurationPath: string = path.join(repoPath, '.git', 'config'); - const configuration: Buffer = fs.readFileSync(configurationPath); + const configuration: Buffer = FileSystem.readFileToBuffer(configurationPath); // The next call hashes the file under another configuration, which is gone again when the call ends writeFile('a.txt', 'changed\r\n'); beforeSpawn = ({ command }: IGitCommand) => { @@ -869,12 +876,12 @@ describe(RepoStateCache.name, () => { }; afterSpawn = ({ command }: IGitCommand, childProcess: ChildProcess) => { if (command === 'hash-object') { - childProcess.once('exit', () => fs.writeFileSync(configurationPath, configuration)); + childProcess.once('exit', () => FileSystem.writeFile(configurationPath, configuration)); } }; let state: IDetailedRepoState = await getStateAsync(); expect(state.files.get('a.txt')).toBe(hashText('changed\n')); - expect(fs.readFileSync(configurationPath)).toEqual(configuration); + expect(FileSystem.readFileToBuffer(configurationPath)).toEqual(configuration); beforeSpawn = undefined; afterSpawn = undefined; @@ -913,13 +920,13 @@ describe(RepoStateCache.name, () => { // The index changes after the calls start, but the configuration doesn't const indexPath: string = path.join(repoPath, '.git', 'index'); const futureTime: number = Math.floor(originalDateNow() / 1000) + 60; - fs.utimesSync(indexPath, futureTime, futureTime); + FileSystem.updateTimes(indexPath, { accessedTime: futureTime, modifiedTime: futureTime }); await getStateAsync(); await getStateAsync(); expect(summarizeSpy).toHaveBeenCalledTimes(2); const pastTime: number = Math.floor(originalDateNow() / 1000) - 100; - fs.utimesSync(indexPath, pastTime, pastTime); + FileSystem.updateTimes(indexPath, { accessedTime: pastTime, modifiedTime: pastTime }); await getStateAsync(); expect(summarizeSpy).toHaveBeenCalledTimes(3); await getStateAsync(); @@ -946,14 +953,14 @@ describe(RepoStateCache.name, () => { writeFile('.gitattributes', '*.txt -text\n'); commit(); writeFile('ignored/crlf.txt', 'a\r\n'); - fs.unlinkSync(path.join(repoPath, '.gitattributes')); + FileSystem.deleteFile(path.join(repoPath, '.gitattributes'), { throwIfNotExists: true }); const additionalPaths: string[] = ['ignored/crlf.txt']; await getStateAsync(additionalPaths); // "git status" uses the version in the index in place of the missing file, but "git hash-object" doesn't writeFile('attributes.tmp', '*.txt text eol=lf\n'); const objectId: string = runGit('hash-object', '-w', 'attributes.tmp').trim(); - fs.unlinkSync(path.join(repoPath, 'attributes.tmp')); + FileSystem.deleteFile(path.join(repoPath, 'attributes.tmp'), { throwIfNotExists: true }); runGit('update-index', '--cacheinfo', `100644,${objectId},.gitattributes`); takeGitCommands(); const state: IDetailedRepoState = await getStateAsync(additionalPaths); @@ -969,12 +976,15 @@ describe(RepoStateCache.name, () => { await getStateAsync(); await getStateAsync(); - fs.unlinkSync(getPrivateIndexPath()); + FileSystem.deleteFile(getPrivateIndexPath(), { throwIfNotExists: true }); await expectUncachedStateAsync(await getStateAsync()); expect(writeFileSpy).toHaveBeenCalledTimes(2); runGit('rm', '--cached', '--quiet', '-r', '.'); - fs.copyFileSync(path.join(repoPath, '.git', 'index'), getPrivateIndexPath()); + FileSystem.copyFile({ + sourcePath: path.join(repoPath, '.git', 'index'), + destinationPath: getPrivateIndexPath() + }); runGit('reset', '--quiet'); await expectUncachedStateAsync(await getStateAsync()); expect(writeFileSpy).toHaveBeenCalledTimes(3); @@ -989,23 +999,23 @@ describe(RepoStateCache.name, () => { expect(takeUsesPrivateIndex()).toBe(false); await expectUncachedStateAsync(await getStateAsync()); expect(takeUsesPrivateIndex()).toBe(true); - expect(fs.readdirSync(temporaryFolderPath)).toHaveLength(1); + expect(FileSystem.readFolderItemNames(temporaryFolderPath)).toHaveLength(1); }); it('creates the temporary folder', async () => { fs.rmSync(temporaryFolderPath, { recursive: true }); await getStateAsync(); expect(takeUsesPrivateIndex()).toBe(true); - expect(fs.readdirSync(temporaryFolderPath)).toHaveLength(1); + expect(FileSystem.readFolderItemNames(temporaryFolderPath)).toHaveLength(1); }); it('resolves a relative temporary folder path against the current working directory, since Git runs in the repository', async () => { // A file that Git takes from the index, since it isn't on disk runGit('update-index', '--assume-unchanged', 'b.txt'); - fs.unlinkSync(path.join(repoPath, 'b.txt')); + FileSystem.deleteFile(path.join(repoPath, 'b.txt'), { throwIfNotExists: true }); // The temp folder of the package is under the current working directory, and the repository isn't const packageTemporaryFolderPath: string = path.resolve(__dirname, '../../temp/test/RepoStateCache'); - fs.mkdirSync(packageTemporaryFolderPath, { recursive: true }); + FileSystem.ensureFolder(packageTemporaryFolderPath); const absoluteFolderPath: string = fs.mkdtempSync(path.join(packageTemporaryFolderPath, 'relative-')); const relativeFolderPath: string = path.relative(process.cwd(), absoluteFolderPath); expect(path.isAbsolute(relativeFolderPath)).toBe(false); @@ -1017,7 +1027,7 @@ describe(RepoStateCache.name, () => { try { const state: IDetailedRepoState = await relativeCache.getDetailedRepoStateAsync(); expect(takeUsesPrivateIndex()).toBe(true); - expect(fs.readdirSync(absoluteFolderPath)).toHaveLength(1); + expect(FileSystem.readFolderItemNames(absoluteFolderPath)).toHaveLength(1); // Only the copy of the index records the file that isn't on disk expect(state.files.has('b.txt')).toBe(true); expect(state.hasUncommittedChanges).toBe(false); @@ -1047,14 +1057,14 @@ describe(RepoStateCache.name, () => { it('removes a lock file that an interrupted "git status" left behind', async () => { await getStateAsync(); - const privateIndexContent: Buffer = fs.readFileSync(getPrivateIndexPath()); + const privateIndexContent: Buffer = FileSystem.readFileToBuffer(getPrivateIndexPath()); const lockPath: string = `${getPrivateIndexPath()}.lock`; - fs.writeFileSync(lockPath, ''); + FileSystem.writeFile(lockPath, ''); touchSettledFile('a.txt'); await expectUncachedStateAsync(await getStateAsync()); - expect(fs.existsSync(lockPath)).toBe(false); - expect(fs.readFileSync(getPrivateIndexPath())).not.toEqual(privateIndexContent); + expect(FileSystem.exists(lockPath)).toBe(false); + expect(FileSystem.readFileToBuffer(getPrivateIndexPath())).not.toEqual(privateIndexContent); }); it('starts "git status" before it examines the additional files', async () => { @@ -1079,11 +1089,11 @@ describe(RepoStateCache.name, () => { process.env.GIT_OPTIONAL_LOCKS = '0'; try { await getStateAsync(); - const privateIndexContent: Buffer = fs.readFileSync(getPrivateIndexPath()); + const privateIndexContent: Buffer = FileSystem.readFileToBuffer(getPrivateIndexPath()); touchSettledFile('a.txt'); await expectUncachedStateAsync(await getStateAsync()); - expect(fs.readFileSync(getPrivateIndexPath())).not.toEqual(privateIndexContent); + expect(FileSystem.readFileToBuffer(getPrivateIndexPath())).not.toEqual(privateIndexContent); } finally { if (optionalLocks === undefined) { delete process.env.GIT_OPTIONAL_LOCKS; @@ -1114,7 +1124,7 @@ describe(RepoStateCache.name, () => { }); it('computes the state of a repository without an index', async () => { - fs.unlinkSync(path.join(repoPath, '.git', 'index')); + FileSystem.deleteFile(path.join(repoPath, '.git', 'index'), { throwIfNotExists: true }); let state: IDetailedRepoState = await getStateAsync(); expect(takeUsesPrivateIndex()).toBe(false); await expectUncachedStateAsync(state); @@ -1130,7 +1140,7 @@ describe(RepoStateCache.name, () => { runGit('update-index', '--split-index'); writeFile('a.txt', 'modified\n'); await expectUncachedStateAsync(await getStateAsync()); - expect(fs.readdirSync(temporaryFolderPath)).toEqual([]); + expect(FileSystem.readFolderItemNames(temporaryFolderPath)).toEqual([]); runGit('update-index', '--no-split-index'); takeGitCommands(); @@ -1142,7 +1152,7 @@ describe(RepoStateCache.name, () => { it('stops using the cache for a repository with submodules', async () => { const submodulePath: string = fs.mkdtempSync(`${TEST_ROOT}/submodule-`); execFileSync('git', ['init', '--quiet'], { cwd: submodulePath, env: getGitEnvironment() }); - fs.writeFileSync(`${submodulePath}/inner.txt`, 'inner\n'); + FileSystem.writeFile(`${submodulePath}/inner.txt`, 'inner\n'); execFileSync('git', ['-c', 'core.autocrlf=false', 'add', '--all'], { cwd: submodulePath, env: getGitEnvironment() @@ -1159,7 +1169,7 @@ describe(RepoStateCache.name, () => { await expectUncachedStateAsync(state); expect(state.hasSubmodules).toBe(true); expect(state.files.has('sub/inner.txt')).toBe(true); - expect(fs.readdirSync(temporaryFolderPath)).toEqual([]); + expect(FileSystem.readFolderItemNames(temporaryFolderPath)).toEqual([]); }); it('falls back to getDetailedRepoStateAsync when it fails, and stops after repeated failures', async () => { @@ -1187,7 +1197,7 @@ describe(RepoStateCache.name, () => { await expectUncachedStateAsync(await getStateAsync()); expect(GitIndexFile.summarizeGitIndex).toHaveBeenCalledTimes(3); - expect(fs.readdirSync(temporaryFolderPath)).toEqual([]); + expect(FileSystem.readFolderItemNames(temporaryFolderPath)).toEqual([]); }); it('reports the error of getDetailedRepoStateAsync, without counting it as a failure of the cache', async () => { @@ -1209,11 +1219,11 @@ describe(RepoStateCache.name, () => { it('computes the state without the cache after it is disposed', async () => { const exitListenerCount: number = process.listenerCount('exit'); await getStateAsync(); - expect(fs.readdirSync(temporaryFolderPath)).toHaveLength(1); + expect(FileSystem.readFolderItemNames(temporaryFolderPath)).toHaveLength(1); expect(process.listenerCount('exit')).toBe(exitListenerCount + 1); cache.dispose(); - expect(fs.readdirSync(temporaryFolderPath)).toEqual([]); + expect(FileSystem.readFolderItemNames(temporaryFolderPath)).toEqual([]); expect(process.listenerCount('exit')).toBe(exitListenerCount); takeGitCommands(); @@ -1228,14 +1238,14 @@ describe(RepoStateCache.name, () => { try { await getStateAsync(); await otherCache.getDetailedRepoStateAsync(); - expect(fs.readdirSync(temporaryFolderPath)).toHaveLength(2); + expect(FileSystem.readFolderItemNames(temporaryFolderPath)).toHaveLength(2); const addedExitListeners: NodeJS.ExitListener[] = process .listeners('exit') .filter((listener: NodeJS.ExitListener) => !exitListeners.includes(listener)); expect(addedExitListeners).toHaveLength(1); addedExitListeners[0](0); - expect(fs.readdirSync(temporaryFolderPath)).toEqual([]); + expect(FileSystem.readFolderItemNames(temporaryFolderPath)).toEqual([]); cache.dispose(); expect(process.listenerCount('exit')).toBe(exitListeners.length + 1); @@ -1266,7 +1276,7 @@ describe(RepoStateCache.name, () => { await expectUncachedStateAsync(state); expect(state.symlinks.has('link')).toBe(true); - fs.unlinkSync(path.join(repoPath, 'link')); + FileSystem.deleteFile(path.join(repoPath, 'link'), { throwIfNotExists: true }); writeFile('link', 'not a link\n'); state = await getStateAsync(); await expectUncachedStateAsync(state); @@ -1282,7 +1292,7 @@ describe(RepoStateCache.name, () => { function settleFolders(...relativePaths: string[]): void { const time: number = Math.floor(originalDateNow() / 1000) - 100; for (const relativePath of relativePaths) { - fs.utimesSync(path.join(repoPath, relativePath), time, time); + FileSystem.updateTimes(path.join(repoPath, relativePath), { accessedTime: time, modifiedTime: time }); } } @@ -1307,7 +1317,7 @@ describe(RepoStateCache.name, () => { .split('\n') .filter((line: string) => line) .map((line: string) => JSON.parse(line)); - fs.unlinkSync(tracePath); + FileSystem.deleteFile(tracePath, { throwIfNotExists: true }); const openedFolderCounts: number[] = events .filter(({ category, key }: ITrace2Event) => category === 'read_directory' && key === 'opendir') .map(({ value }: ITrace2Event) => Number(value)); @@ -1325,11 +1335,11 @@ describe(RepoStateCache.name, () => { settleFolders('.', 'dir'); await getStateAsync(); const previousPath: string = getPrivateIndexPath(); - const previousContent: Buffer = fs.readFileSync(previousPath); + const previousContent: Buffer = FileSystem.readFileToBuffer(previousPath); expect(getExtension(previousContent, 'UNTR')).toBeDefined(); // Git saved the copy after the index const previousTime: number = Math.floor(originalDateNow() / 1000) - 50; - fs.utimesSync(previousPath, previousTime, previousTime); + FileSystem.updateTimes(previousPath, { accessedTime: previousTime, modifiedTime: previousTime }); writeFile('a.txt', 'modified\n'); runGit('add', 'a.txt'); @@ -1354,7 +1364,7 @@ describe(RepoStateCache.name, () => { await getStateAsync(); writeFile('dir/untracked.txt', 'untracked\n'); - fs.unlinkSync(path.join(repoPath, 'untracked.txt')); + FileSystem.deleteFile(path.join(repoPath, 'untracked.txt'), { throwIfNotExists: true }); writeFile('a.txt', 'modified\n'); runGit('add', 'a.txt'); const [state, openedFolderCounts] = await getStateAndOpenedFolderCountsAsync(); @@ -1392,7 +1402,7 @@ describe(RepoStateCache.name, () => { () => runGit('checkout', '--', 'a.txt'), () => writeFile('dir/sub/untracked.txt', 'untracked\n'), () => runGit('add', 'dir/sub/untracked.txt'), - () => fs.unlinkSync(path.join(repoPath, 'untracked.txt')), + () => FileSystem.deleteFile(path.join(repoPath, 'untracked.txt'), { throwIfNotExists: true }), () => runGit('rm', '--cached', '--quiet', 'b.txt'), () => runGit('mv', 'dir/c.txt', 'dir/d.txt'), () => writeFile('dir/d.txt', 'modified\n'), @@ -1419,7 +1429,10 @@ describe(RepoStateCache.name, () => { // older copy. Otherwise, if the second changed between this write and commit(), Git would examine it only in // the copy. const futureTime: number = Math.floor(originalDateNow() / 1000) + 3600; - fs.utimesSync(path.join(repoPath, 'crlf.txt'), futureTime, futureTime); + FileSystem.updateTimes(path.join(repoPath, 'crlf.txt'), { + accessedTime: futureTime, + modifiedTime: futureTime + }); commit(); await getStateAsync(); const writeFileSpy: jest.SpyInstance = jest.spyOn(fs.promises, 'writeFile'); diff --git a/libraries/rush-client-core/src/test/connectOrStartDaemon.test.ts b/libraries/rush-client-core/src/test/connectOrStartDaemon.test.ts index 2522bb58118..0f33190b16c 100644 --- a/libraries/rush-client-core/src/test/connectOrStartDaemon.test.ts +++ b/libraries/rush-client-core/src/test/connectOrStartDaemon.test.ts @@ -66,7 +66,7 @@ const RELAUNCH_DELAY_MS: number = 15000; const TEST_ROOT: string = `${__dirname}/../../temp`; // Leave room for Unix socket names on CI. function readIfPresent(filePath: string): string { - return fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : ''; + return FileSystem.exists(filePath) ? FileSystem.readFile(filePath) : ''; } describe('detached daemon startup', () => { @@ -77,8 +77,8 @@ describe('detached daemon startup', () => { beforeEach(() => { starterProcesses = []; - fs.mkdirSync(TEST_ROOT, { recursive: true }); - folder = fs.realpathSync.native(fs.mkdtempSync(`${TEST_ROOT}/s`)); + FileSystem.ensureFolder(TEST_ROOT); + folder = FileSystem.getRealPath(fs.mkdtempSync(`${TEST_ROOT}/s`)); paths = { runtimeDir: folder, socketPath: @@ -116,16 +116,16 @@ describe('detached daemon startup', () => { await closed; } } - if (fs.existsSync(path.join(folder, 'starts'))) { - fs.writeFileSync(path.join(folder, 'stop'), ''); - const pids: string[] = fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n'); + if (FileSystem.exists(path.join(folder, 'starts'))) { + FileSystem.writeFile(path.join(folder, 'stop'), ''); + const pids: string[] = FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n'); await Promise.all(pids.map((pid) => waitForTestProcessExitAsync(Number(pid)))); - expect(pids.every((pid) => fs.existsSync(path.join(folder, `stopped-${pid}`)))).toBe(true); + expect(pids.every((pid) => FileSystem.exists(path.join(folder, `stopped-${pid}`)))).toBe(true); } // A test that expects a fixture daemon to fail checks and removes this record. expect(readIfPresent(path.join(folder, 'failures'))).toBe(''); - if (fs.existsSync(path.join(folder, 'parents'))) { - const parents = new Set(fs.readFileSync(path.join(folder, 'parents'), 'utf8').trim().split('\n')); + if (FileSystem.exists(path.join(folder, 'parents'))) { + const parents = new Set(FileSystem.readFile(path.join(folder, 'parents')).trim().split('\n')); await Promise.all([...parents].map((pid) => waitForTestProcessExitAsync(Number(pid)))); } }); @@ -164,14 +164,14 @@ describe('detached daemon startup', () => { } async function killStarterBeforeBindAsync(): Promise { - fs.writeFileSync(path.join(folder, 'hold-prebind'), ''); + FileSystem.writeFile(path.join(folder, 'hold-prebind'), ''); const starter = startClient(); const barrier: string = path.join(folder, 'prebind'); const deadline: number = Date.now() + 5000; - while (!fs.existsSync(barrier) && Date.now() < deadline) await delayAsync(20); - expect(fs.existsSync(barrier)).toBe(true); - expect(fs.existsSync(paths.lockfilePath)).toBe(false); - const daemonPid: number = Number(fs.readFileSync(barrier, 'utf8')); + while (!FileSystem.exists(barrier) && Date.now() < deadline) await delayAsync(20); + expect(FileSystem.exists(barrier)).toBe(true); + expect(FileSystem.exists(paths.lockfilePath)).toBe(false); + const daemonPid: number = Number(FileSystem.readFile(barrier)); expect(Number.isSafeInteger(daemonPid)).toBe(true); expect(daemonPid).toBeGreaterThan(0); expect(starter.child.kill('SIGKILL')).toBe(true); @@ -188,20 +188,20 @@ describe('detached daemon startup', () => { function writeReservation(helperPid: number, helperStartedAt: string = new Date().toISOString()): string { const contents: string = JSON.stringify({ token: randomUUID(), helperPid, helperStartedAt }); - fs.writeFileSync(getDaemonStartupFilePath(paths), contents); + FileSystem.writeFile(getDaemonStartupFilePath(paths), contents); return contents; } /** Records the reservation's launch as one relaunch delay earlier, so that its relaunch time has passed. */ function ageReservation(): string { const record: { helperStartedAt: string } = JSON.parse( - fs.readFileSync(getDaemonStartupFilePath(paths), 'utf8') + FileSystem.readFile(getDaemonStartupFilePath(paths)) ); const helperStartedAt: string = new Date( Date.parse(record.helperStartedAt) - RELAUNCH_DELAY_MS ).toISOString(); const contents: string = JSON.stringify({ ...record, helperStartedAt }); - fs.writeFileSync(getDaemonStartupFilePath(paths), contents); + FileSystem.writeFile(getDaemonStartupFilePath(paths), contents); return helperStartedAt; } @@ -228,8 +228,8 @@ describe('detached daemon startup', () => { async function waitForFileAsync(filePath: string): Promise { const deadline: number = Date.now() + 5000; - while (!fs.existsSync(filePath) && Date.now() < deadline) await delayAsync(20); - return fs.readFileSync(filePath, 'utf8'); + while (!FileSystem.exists(filePath) && Date.now() < deadline) await delayAsync(20); + return FileSystem.readFile(filePath); } /** @@ -237,13 +237,13 @@ describe('detached daemon startup', () => { * reservation whose relaunch time has passed. */ async function abandonStartupBeforeBindAsync(): Promise<{ daemonPid: number; helperPid: number }> { - fs.writeFileSync(path.join(folder, 'hold-prebind'), ''); + FileSystem.writeFile(path.join(folder, 'hold-prebind'), ''); await expect(connectOrStartDaemonAsync({ ...options, startupTimeoutMs: 1000 })).rejects.toThrow( 'timed out awaiting hello/ping readiness' ); const daemonPid: number = Number(await waitForFileAsync(path.join(folder, 'prebind'))); - const { helperPid } = JSON.parse(fs.readFileSync(getDaemonStartupFilePath(paths), 'utf8')); - expect(fs.readFileSync(path.join(folder, 'parents'), 'utf8')).toBe(`${helperPid}\n`); + const { helperPid } = JSON.parse(FileSystem.readFile(getDaemonStartupFilePath(paths))); + expect(FileSystem.readFile(path.join(folder, 'parents'))).toBe(`${helperPid}\n`); // This test started the helper (through connectOrStartDaemonAsync), so it may signal that PID. process.kill(helperPid, 'SIGKILL'); await waitForProcessGoneAsync(helperPid); @@ -272,14 +272,14 @@ describe('detached daemon startup', () => { new RegExp(`^${loserPid} (Daemon process ${winnerPid} still owns |A live daemon already listens at )`) ); expect(readIfPresent(failuresPath).trim().split('\n')).toHaveLength(1); - fs.unlinkSync(failuresPath); + FileSystem.deleteFile(failuresPath, { throwIfNotExists: true }); } async function startFixtureDaemonAsync(): Promise { const client: DaemonClient = await connectOrStartDaemonAsync(options); const { pid } = await client.status; await client.closeAsync(); - expect(fs.existsSync(getDaemonStartupFilePath(paths))).toBe(false); + expect(FileSystem.exists(getDaemonStartupFilePath(paths))).toBe(false); return pid!; } @@ -293,10 +293,10 @@ describe('detached daemon startup', () => { expect( results.some(({ stderr }) => stderr.includes('is still waiting for the daemon to become ready')) ).toBe(true); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8')).toBe(`${daemonPid}\n`); - expect(fs.existsSync(paths.lockfilePath)).toBe(false); + expect(FileSystem.readFile(path.join(folder, 'starts'))).toBe(`${daemonPid}\n`); + expect(FileSystem.exists(paths.lockfilePath)).toBe(false); - fs.unlinkSync(path.join(folder, 'hold-prebind')); + FileSystem.deleteFile(path.join(folder, 'hold-prebind'), { throwIfNotExists: true }); const client = await connectOrStartDaemonAsync(options); expect((await client.status).pid).toBe(daemonPid); await client.closeAsync(); @@ -305,51 +305,51 @@ describe('detached daemon startup', () => { it('hands startup to the detached owner after the first client dies and reuses exactly one daemon', async () => { const daemonPid: number = await killStarterBeforeBindAsync(); const successors = Array.from({ length: 4 }, () => startClient()); - fs.unlinkSync(path.join(folder, 'hold-prebind')); + FileSystem.deleteFile(path.join(folder, 'hold-prebind'), { throwIfNotExists: true }); expect(await Promise.all(successors.map(({ result }) => result))).toEqual( Array.from({ length: 4 }, () => ({ code: 0, stderr: '' })) ); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8')).toBe(`${daemonPid}\n`); + expect(FileSystem.readFile(path.join(folder, 'starts'))).toBe(`${daemonPid}\n`); const client = await DaemonClient.connectAsync({ socketPath: paths.socketPath, expectedDaemonVersion: 'fixture' }); expect((await client.status).pid).toBe(daemonPid); await client.closeAsync(); - expect(fs.existsSync(getDaemonStartupFilePath(paths))).toBe(false); + expect(FileSystem.exists(getDaemonStartupFilePath(paths))).toBe(false); }, 15000); it('lets the detached helper finish a startup that outlasts the requesting client', async () => { - fs.writeFileSync(path.join(folder, 'hold-prebind'), ''); + FileSystem.writeFile(path.join(folder, 'hold-prebind'), ''); const first = startClient({ ...options, startupTimeoutMs: 1000 }); const barrier: string = path.join(folder, 'prebind'); const deadline: number = Date.now() + 5000; - while (!fs.existsSync(barrier) && Date.now() < deadline) await delayAsync(20); - const daemonPid: number = Number(fs.readFileSync(barrier, 'utf8')); + while (!FileSystem.exists(barrier) && Date.now() < deadline) await delayAsync(20); + const daemonPid: number = Number(FileSystem.readFile(barrier)); expect((await first.result).code).not.toBe(0); - expect(fs.existsSync(getDaemonStartupFilePath(paths))).toBe(true); + expect(FileSystem.exists(getDaemonStartupFilePath(paths))).toBe(true); // The launcher becomes ready only after the first client has given up. - fs.unlinkSync(path.join(folder, 'hold-prebind')); + FileSystem.deleteFile(path.join(folder, 'hold-prebind'), { throwIfNotExists: true }); const client = await connectOrStartDaemonAsync(options); expect((await client.status).pid).toBe(daemonPid); await client.closeAsync(); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8')).toBe(`${daemonPid}\n`); - expect(fs.existsSync(getDaemonStartupFilePath(paths))).toBe(false); + expect(FileSystem.readFile(path.join(folder, 'starts'))).toBe(`${daemonPid}\n`); + expect(FileSystem.exists(getDaemonStartupFilePath(paths))).toBe(false); }, 15000); it('preserves an unresolved startup reservation rather than trusting or reclaiming its contents', async () => { const startupPath: string = getDaemonStartupFilePath(paths); const contents: string = JSON.stringify({ pid: process.pid, startedAt: 'not an ownership contract' }); - fs.writeFileSync(startupPath, contents); + FileSystem.writeFile(startupPath, contents); const { result } = startClient({ ...options, startupTimeoutMs: 200 }); expect(await result).toMatchObject({ code: 1, stderr: expect.stringContaining('unresolved startup handoff') }); expect((await result).stderr).toContain('daemon stop --force'); - expect(fs.readFileSync(startupPath, 'utf8')).toBe(contents); - expect(fs.existsSync(path.join(folder, 'starts'))).toBe(false); + expect(FileSystem.readFile(startupPath)).toBe(contents); + expect(FileSystem.exists(path.join(folder, 'starts'))).toBe(false); }); it('does not infer safe retry from a launcher exiting before ownership publication', async () => { @@ -359,12 +359,12 @@ describe('detached daemon startup', () => { startCommand: { ...options.startCommand!, args: [path.join(folder, 'missing-entry.js')] } }; await expect(connectOrStartDaemonAsync(failing)).rejects.toThrow('Unable to start'); - const contents: string = fs.readFileSync(startupPath, 'utf8'); + const contents: string = FileSystem.readFile(startupPath); await expect(connectOrStartDaemonAsync({ ...options, startupTimeoutMs: 100 })).rejects.toThrow( 'unresolved startup handoff' ); - expect(fs.readFileSync(startupPath, 'utf8')).toBe(contents); - expect(fs.existsSync(path.join(folder, 'starts'))).toBe(false); + expect(FileSystem.readFile(startupPath)).toBe(contents); + expect(FileSystem.exists(path.join(folder, 'starts'))).toBe(false); }); it('refuses another launch at once after the startup helper exited, until the relaunch time', async () => { @@ -374,7 +374,7 @@ describe('detached daemon startup', () => { startCommand: { ...options.startCommand!, args: [path.join(folder, 'missing-entry.js')] } }; await expect(connectOrStartDaemonAsync(failing)).rejects.toThrow('Unable to start'); - const contents: string = fs.readFileSync(startupPath, 'utf8'); + const contents: string = FileSystem.readFile(startupPath); const { helperPid, helperStartedAt } = JSON.parse(contents); const relaunchAfter: string = new Date(Date.parse(helperStartedAt) + RELAUNCH_DELAY_MS).toISOString(); expect(inspectDaemonStartupReservation(paths)).toEqual({ @@ -393,14 +393,14 @@ describe('detached daemon startup', () => { `unresolved startup handoff at ${startupPath}: its startup helper (PID ${helperPid}) exited before the daemon became ready; refusing another launch until ${relaunchAfter}, so that a daemon that cannot start is not launched by every command.` ); expect(error.message).not.toContain('..'); - expect(fs.readFileSync(startupPath, 'utf8')).toBe(contents); - expect(fs.existsSync(path.join(folder, 'starts'))).toBe(false); + expect(FileSystem.readFile(startupPath)).toBe(contents); + expect(FileSystem.exists(path.join(folder, 'starts'))).toBe(false); expect(readTakeOverLines()).toEqual([]); // Once the relaunch time has passed, the next client takes the reservation over and starts the daemon. const agedStartedAt: string = ageReservation(); const daemonPid: number = await startFixtureDaemonAsync(); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8')).toBe(`${daemonPid}\n`); + expect(FileSystem.readFile(path.join(folder, 'starts'))).toBe(`${daemonPid}\n`); const takeOvers: string[] = readTakeOverLines(); expect(takeOvers).toHaveLength(1); expect(takeOvers[0]).toMatch(/^\d{4}-\d\d-\d\dT[\d:.]+Z rush-client /); @@ -428,9 +428,9 @@ describe('detached daemon startup', () => { 'Daemon startup failed: the daemon became ready but exited before this client connected' ); expect(Date.now() - started).toBeLessThan(3500); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(1); - expect(fs.existsSync(paths.lockfilePath)).toBe(false); - expect(fs.existsSync(getDaemonStartupFilePath(paths))).toBe(false); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(1); + expect(FileSystem.exists(paths.lockfilePath)).toBe(false); + expect(FileSystem.exists(getDaemonStartupFilePath(paths))).toBe(false); }, 15000); it('waits out its deadline for a daemon that became ready and still has its lockfile', async () => { @@ -446,8 +446,8 @@ describe('detached daemon startup', () => { ); expect(error.message).toContain('Daemon startup timed out awaiting hello/ping readiness.'); expect(Date.now() - started).toBeGreaterThanOrEqual(3000); - expect(fs.existsSync(paths.lockfilePath)).toBe(true); - expect(fs.existsSync(getDaemonStartupFilePath(paths))).toBe(false); + expect(FileSystem.exists(paths.lockfilePath)).toBe(true); + expect(FileSystem.exists(getDaemonStartupFilePath(paths))).toBe(false); }, 15000); it('waits out its deadline while another startup is reserved after the daemon that became ready exited', async () => { @@ -468,10 +468,10 @@ describe('detached daemon startup', () => { ); expect(error.message).toContain('Daemon startup timed out awaiting hello/ping readiness.'); expect(Date.now() - started).toBeGreaterThanOrEqual(3000); - const daemonPids: string[] = fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n'); + const daemonPids: string[] = FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n'); expect(daemonPids).toHaveLength(1); - expect(fs.existsSync(paths.lockfilePath)).toBe(false); - expect(JSON.parse(fs.readFileSync(getDaemonStartupFilePath(paths), 'utf8'))).toMatchObject({ + expect(FileSystem.exists(paths.lockfilePath)).toBe(false); + expect(JSON.parse(FileSystem.readFile(getDaemonStartupFilePath(paths)))).toMatchObject({ helperPid: Number(daemonPids[0]) }); }, 15000); @@ -505,8 +505,8 @@ describe('detached daemon startup', () => { `its startup helper (PID ${helperPid}) exited before the daemon became ready, but a process still accepts connections at ${paths.socketPath}; refusing another launch.` ); expect(error.message).toContain('daemon stop --force'); - expect(fs.readFileSync(getDaemonStartupFilePath(paths), 'utf8')).toBe(contents); - expect(fs.existsSync(path.join(folder, 'starts'))).toBe(false); + expect(FileSystem.readFile(getDaemonStartupFilePath(paths))).toBe(contents); + expect(FileSystem.exists(path.join(folder, 'starts'))).toBe(false); expect(readTakeOverLines()).toEqual([]); } finally { for (const socket of sockets) socket.destroy(); @@ -524,8 +524,8 @@ describe('detached daemon startup', () => { await expect(connectOrStartDaemonAsync({ ...options, startupTimeoutMs: 500 })).rejects.toThrow( `its startup helper (PID ${process.pid}) is still waiting for the daemon to become ready; refusing another launch` ); - expect(fs.readFileSync(getDaemonStartupFilePath(paths), 'utf8')).toBe(contents); - expect(fs.existsSync(path.join(folder, 'starts'))).toBe(false); + expect(FileSystem.readFile(getDaemonStartupFilePath(paths))).toBe(contents); + expect(FileSystem.exists(path.join(folder, 'starts'))).toBe(false); expect(readTakeOverLines()).toEqual([]); }, 30000); @@ -536,13 +536,13 @@ describe('detached daemon startup', () => { // After the caller read it, the reservation was replaced by one whose helper still runs. const replacement: string = writeReservation(process.pid); expect(await tryTakeOverAbandonedStartupReservationAsync(paths, abandoned)).toBe(false); - expect(fs.readFileSync(startupPath, 'utf8')).toBe(replacement); + expect(FileSystem.readFile(startupPath)).toBe(replacement); // Unchanged, the same reservation is taken over. - fs.writeFileSync(startupPath, abandoned.contents!); + FileSystem.writeFile(startupPath, abandoned.contents!); expect(await tryTakeOverAbandonedStartupReservationAsync(paths, abandoned)).toBe(true); - expect(fs.existsSync(startupPath)).toBe(false); - expect(fs.existsSync(path.join(folder, 'starts'))).toBe(false); + expect(FileSystem.exists(startupPath)).toBe(false); + expect(FileSystem.exists(path.join(folder, 'starts'))).toBe(false); }); it('lets exactly one of several clients take over a reservation whose helper exited', async () => { @@ -550,8 +550,8 @@ describe('detached daemon startup', () => { writeReservation(helperPid, new Date(Date.now() - 2 * RELAUNCH_DELAY_MS).toISOString()); const results = await Promise.all(Array.from({ length: 4 }, () => startClient().result)); expect(results).toEqual(Array.from({ length: 4 }, () => ({ code: 0, stderr: '' }))); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(1); - expect(fs.existsSync(getDaemonStartupFilePath(paths))).toBe(false); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(1); + expect(FileSystem.exists(getDaemonStartupFilePath(paths))).toBe(false); const takeOvers: string[] = readTakeOverLines(); expect(takeOvers).toHaveLength(1); expect(takeOvers[0]).toContain(`took over the startup reservation of startup helper PID ${helperPid} `); @@ -567,13 +567,13 @@ describe('detached daemon startup', () => { await client.closeAsync(); } expect(successorPid).not.toBe(daemonPid); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8')).toBe(`${daemonPid}\n${successorPid}\n`); - expect(fs.existsSync(getDaemonStartupFilePath(paths))).toBe(false); + expect(FileSystem.readFile(path.join(folder, 'starts'))).toBe(`${daemonPid}\n${successorPid}\n`); + expect(FileSystem.exists(getDaemonStartupFilePath(paths))).toBe(false); expect(readTakeOverLines()).toHaveLength(1); expect(readTakeOverLines()[0]).toContain(`startup helper PID ${helperPid} `); // The first daemon finds the successor at the endpoint and exits. - fs.unlinkSync(path.join(folder, 'hold-prebind')); + FileSystem.deleteFile(path.join(folder, 'hold-prebind'), { throwIfNotExists: true }); await expectLostEndpointRaceAsync(daemonPid, successorPid); const next: DaemonClient = await connectOrStartDaemonAsync(options); try { @@ -585,24 +585,24 @@ describe('detached daemon startup', () => { it('keeps one daemon when the daemon of a killed startup helper outpaces the relaunch', async () => { const { daemonPid } = await abandonStartupBeforeBindAsync(); - fs.writeFileSync(path.join(folder, 'hold-prebind-b'), ''); + FileSystem.writeFile(path.join(folder, 'hold-prebind-b'), ''); const relaunch: Promise = connectOrStartDaemonAsync(getSecondDaemonOptions()); const successorPid: number = Number(await waitForFileAsync(path.join(folder, 'prebind-b'))); expect(successorPid).not.toBe(daemonPid); // The first daemon publishes the endpoint first, so the relaunch's helper finds it ready. - fs.unlinkSync(path.join(folder, 'hold-prebind')); + FileSystem.deleteFile(path.join(folder, 'hold-prebind'), { throwIfNotExists: true }); const client: DaemonClient = await relaunch; try { expect((await client.status).pid).toBe(daemonPid); } finally { await client.closeAsync(); } - expect(fs.existsSync(getDaemonStartupFilePath(paths))).toBe(false); + expect(FileSystem.exists(getDaemonStartupFilePath(paths))).toBe(false); - fs.unlinkSync(path.join(folder, 'hold-prebind-b')); + FileSystem.deleteFile(path.join(folder, 'hold-prebind-b'), { throwIfNotExists: true }); await expectLostEndpointRaceAsync(successorPid, daemonPid); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8')).toBe(`${daemonPid}\n${successorPid}\n`); + expect(FileSystem.readFile(path.join(folder, 'starts'))).toBe(`${daemonPid}\n${successorPid}\n`); const next: DaemonClient = await connectOrStartDaemonAsync(options); try { expect((await next.status).pid).toBe(daemonPid); @@ -616,7 +616,7 @@ describe('detached daemon startup', () => { async (kind) => { const daemonPid: number = await startFixtureDaemonAsync(); if (kind === 'legacy') { - fs.writeFileSync(getDaemonStartupFilePath(paths), randomUUID()); + FileSystem.writeFile(getDaemonStartupFilePath(paths), randomUUID()); } else { writeReservation(await getExitedPidAsync()); } @@ -630,14 +630,14 @@ describe('detached daemon startup', () => { await client.closeAsync(); } expect(Date.now() - started).toBeLessThan(3000); - expect(fs.existsSync(getDaemonStartupFilePath(paths))).toBe(false); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8')).toBe(`${daemonPid}\n`); + expect(FileSystem.exists(getDaemonStartupFilePath(paths))).toBe(false); + expect(FileSystem.readFile(path.join(folder, 'starts'))).toBe(`${daemonPid}\n`); } ); it('resolves a retained startup reservation before replacing a mismatched ready daemon', async () => { const daemonPid: number = await startFixtureDaemonAsync(); - fs.writeFileSync(getDaemonStartupFilePath(paths), randomUUID()); + FileSystem.writeFile(getDaemonStartupFilePath(paths), randomUUID()); const replacement: DaemonClient = await connectOrStartDaemonAsync({ ...options, expectedDaemonVersion: 'replacement', @@ -650,14 +650,14 @@ describe('detached daemon startup', () => { } finally { await replacement.closeAsync(); } - expect(fs.existsSync(getDaemonStartupFilePath(paths))).toBe(false); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(2); + expect(FileSystem.exists(getDaemonStartupFilePath(paths))).toBe(false); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(2); }); it('keeps a startup reservation next to a ready daemon that is not the attested owner', async () => { await startFixtureDaemonAsync(); - const owner: string = fs.readFileSync(paths.lockfilePath, 'utf8'); - fs.writeFileSync(paths.lockfilePath, JSON.stringify({ ...JSON.parse(owner), pid: process.pid })); + const owner: string = FileSystem.readFile(paths.lockfilePath); + FileSystem.writeFile(paths.lockfilePath, JSON.stringify({ ...JSON.parse(owner), pid: process.pid })); const contents: string = writeReservation(await getExitedPidAsync()); try { await expect(connectOrStartDaemonAsync({ ...options, startupTimeoutMs: 2000 })).rejects.toThrow( @@ -666,11 +666,11 @@ describe('detached daemon startup', () => { await expect(connectOrStartDaemonAsync({ paths, expectedDaemonVersion: 'fixture' })).rejects.toThrow( 'auto-start is disabled' ); - expect(fs.readFileSync(getDaemonStartupFilePath(paths), 'utf8')).toBe(contents); + expect(FileSystem.readFile(getDaemonStartupFilePath(paths))).toBe(contents); } finally { - fs.writeFileSync(paths.lockfilePath, owner); + FileSystem.writeFile(paths.lockfilePath, owner); } - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(1); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(1); }); it('resolves a retained startup reservation before shutdown so that a successor can start', async () => { @@ -681,14 +681,14 @@ describe('detached daemon startup', () => { running.closeAsync() ); expect(previousDaemon.pid).toBe(daemonPid); - expect(fs.existsSync(getDaemonStartupFilePath(paths))).toBe(false); + expect(FileSystem.exists(getDaemonStartupFilePath(paths))).toBe(false); const successor: DaemonClient = await connectOrStartDaemonAsync({ ...options, previousDaemon }); try { expect((await successor.status).pid).not.toBe(daemonPid); } finally { await successor.closeAsync(); } - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(2); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(2); }); it('does not request shutdown while the start lock keeps a startup reservation unresolved', async () => { @@ -705,14 +705,14 @@ describe('detached daemon startup', () => { await running.closeAsync(); await lock!.releaseAsync(); } - expect(fs.readFileSync(getDaemonStartupFilePath(paths), 'utf8')).toBe(contents); + expect(FileSystem.readFile(getDaemonStartupFilePath(paths))).toBe(contents); const client: DaemonClient = await connectOrStartDaemonAsync(options); try { expect((await client.status).pid).toBe(daemonPid); } finally { await client.closeAsync(); } - expect(fs.existsSync(getDaemonStartupFilePath(paths))).toBe(false); + expect(FileSystem.exists(getDaemonStartupFilePath(paths))).toBe(false); }); it('resolves a startup reservation before a plain stop only for the attested ready daemon', async () => { @@ -728,16 +728,16 @@ describe('detached daemon startup', () => { } finally { await lock!.releaseAsync(); } - const owner: string = fs.readFileSync(paths.lockfilePath, 'utf8'); - fs.writeFileSync(paths.lockfilePath, JSON.stringify({ ...JSON.parse(owner), pid: process.pid })); + const owner: string = FileSystem.readFile(paths.lockfilePath); + FileSystem.writeFile(paths.lockfilePath, JSON.stringify({ ...JSON.parse(owner), pid: process.pid })); try { await expect(resolveDaemonStartupReservationAsync(running, paths)).resolves.toBe(false); } finally { - fs.writeFileSync(paths.lockfilePath, owner); + FileSystem.writeFile(paths.lockfilePath, owner); } - expect(fs.readFileSync(getDaemonStartupFilePath(paths), 'utf8')).toBe(contents); + expect(FileSystem.readFile(getDaemonStartupFilePath(paths))).toBe(contents); await expect(resolveDaemonStartupReservationAsync(running, paths)).resolves.toBe(true); - expect(fs.existsSync(getDaemonStartupFilePath(paths))).toBe(false); + expect(FileSystem.exists(getDaemonStartupFilePath(paths))).toBe(false); await running.shutdownAsync(); } finally { await running.closeAsync(); @@ -750,13 +750,13 @@ describe('detached daemon startup', () => { } finally { await successor.closeAsync(); } - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(2); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(2); }); it('reports a startup reservation and whether its helper can still release it', async () => { const startupPath: string = getDaemonStartupFilePath(paths); expect(inspectDaemonStartupReservation(paths)).toBeUndefined(); - fs.writeFileSync(startupPath, randomUUID()); + FileSystem.writeFile(startupPath, randomUUID()); expect(inspectDaemonStartupReservation(paths)).toEqual({ path: startupPath, helperState: 'unknown' }); writeReservation(process.pid); expect(inspectDaemonStartupReservation(paths)).toEqual({ @@ -778,11 +778,11 @@ describe('detached daemon startup', () => { writeReservation(process.pid, new Date(Date.now() - 3600000).toISOString()); expect(inspectDaemonStartupReservation(paths)).toMatchObject({ helperState: 'exited' }); } - fs.unlinkSync(startupPath); - fs.mkdirSync(startupPath); + FileSystem.deleteFile(startupPath, { throwIfNotExists: true }); + FileSystem.ensureFolder(startupPath); expect(inspectDaemonStartupReservation(paths)).toEqual({ path: startupPath, helperState: 'unknown' }); fs.rmdirSync(startupPath); - expect(fs.existsSync(path.join(folder, 'starts'))).toBe(false); + expect(FileSystem.exists(path.join(folder, 'starts'))).toBe(false); }); it('lets a startup helper release only its own reservation, tolerating one already resolved', () => { @@ -791,11 +791,11 @@ describe('detached daemon startup', () => { const token: string = reserveDaemonStartup(paths, helper); expect(() => reserveDaemonStartup(paths, helper)).toThrow('EEXIST'); expect(() => releaseDaemonStartup(paths, randomUUID())).toThrow('changed ownership'); - expect(fs.existsSync(startupPath)).toBe(true); + expect(FileSystem.exists(startupPath)).toBe(true); releaseDaemonStartup(paths, token); - expect(fs.existsSync(startupPath)).toBe(false); + expect(FileSystem.exists(startupPath)).toBe(false); releaseDaemonStartup(paths, token); - expect(fs.existsSync(startupPath)).toBe(false); + expect(FileSystem.exists(startupPath)).toBe(false); }); it.each([false, true])( @@ -814,7 +814,7 @@ describe('detached daemon startup', () => { environment: { ...options.startCommand!.environment, FIXTURE_VALUE: 'explicit environment' } } }); - expect(JSON.parse(fs.readFileSync(path.join(folder, 'launcher-options'), 'utf8'))).toEqual({ + expect(JSON.parse(FileSystem.readFile(path.join(folder, 'launcher-options')))).toEqual({ cwd: folder, argument: 'an argument with spaces', environment: 'explicit environment' @@ -890,8 +890,8 @@ describe('detached daemon startup', () => { expect(helper?.pid).toBeDefined(); await waitForTestProcessExitAsync(helper!.pid!); exited = true; - expect(fs.existsSync(getDaemonStartupFilePath(paths))).toBe(true); - expect(fs.existsSync(path.join(folder, 'starts'))).toBe(false); + expect(FileSystem.exists(getDaemonStartupFilePath(paths))).toBe(true); + expect(FileSystem.exists(path.join(folder, 'starts'))).toBe(false); } finally { observer.mockRestore(); if (!exited && helper?.pid !== undefined) { @@ -918,7 +918,7 @@ describe('detached daemon startup', () => { }) ); expect(results).toEqual(Array.from({ length: 4 }, () => ({ code: 0, stderr: '' }))); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(1); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(1); const client = await DaemonClient.connectAsync({ socketPath: paths.socketPath, expectedDaemonVersion: 'fixture' @@ -933,11 +933,11 @@ describe('detached daemon startup', () => { 'connects 32 concurrent clients to a daemon that takes 8 seconds to start, running "ps" once per client', async () => { const clientCount: number = 32; - fs.writeFileSync(path.join(folder, 'startup-delay-ms'), '8000'); + FileSystem.writeFile(path.join(folder, 'startup-delay-ms'), '8000'); // A "ps" script ahead of the real one on the PATH records the client that runs each "ps" command. const binFolder: string = path.join(folder, 'bin'); const psCallsPath: string = path.join(folder, 'ps-calls'); - fs.mkdirSync(binFolder); + FileSystem.ensureFolder(binFolder); fs.writeFileSync( path.join(binFolder, 'ps'), `#!/bin/sh\necho "$PPID" >> '${psCallsPath}'\nPATH='${process.env.PATH}' exec ps "$@"\n`, @@ -965,9 +965,9 @@ describe('detached daemon startup', () => { ); expect(results).toEqual(Array.from({ length: clientCount }, () => ({ code: 0, stderr: '' }))); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(1); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(1); // Each client runs "ps" once, for its own start time. Lockfiles of other clients are checked with /proc. - const psCalls: number = fs.readFileSync(psCallsPath, 'utf8').trim().split('\n').length; + const psCalls: number = FileSystem.readFile(psCallsPath).trim().split('\n').length; expect(psCalls).toBeGreaterThan(0); expect(psCalls).toBeLessThan(2 * clientCount); }, @@ -991,8 +991,8 @@ describe('detached daemon startup', () => { expect(statuses.every((status) => status.daemonVersion === 'replacement')).toBe(true); expect(new Set(statuses.map((status) => status.pid)).size).toBe(1); expect(statuses[0].pid).not.toBe(previous.pid); - expect(fs.existsSync(path.join(folder, `stopped-${previous.pid}`))).toBe(true); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(2); + expect(FileSystem.exists(path.join(folder, `stopped-${previous.pid}`))).toBe(true); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(2); const request = captureDaemonRequest({ argv: ['test'], commandName: 'test', @@ -1005,7 +1005,7 @@ describe('detached daemon startup', () => { kind: 'result', result: { exitCode: 0 } }); - expect(fs.readFileSync(path.join(folder, 'requests'), 'utf8')).toBe('replacement\n'); + expect(FileSystem.readFile(path.join(folder, 'requests'))).toBe('replacement\n'); } finally { await Promise.all(clients.map((client) => client.closeAsync())); } @@ -1025,7 +1025,7 @@ describe('detached daemon startup', () => { expectedDaemonVersion: 'fixture' }); await original.closeAsync(); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(1); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(1); }); it('resolves a lazy start command only when no compatible daemon is ready', async () => { @@ -1047,7 +1047,7 @@ describe('detached daemon startup', () => { }); expect((await replaced.status).daemonVersion).toBe('replacement'); await replaced.closeAsync(); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(2); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(2); }); it.each(['restart-once', 'restart-twice', 'restart-always', 'restart-held'])( @@ -1081,7 +1081,7 @@ describe('detached daemon startup', () => { if (mode === 'restart-once' || mode === 'restart-twice') { const restarts: number = mode === 'restart-once' ? 1 : 2; expect(await pending).toMatchObject({ kind: 'result', result: { exitCode: 0 } }); - const waits = fs.readFileSync(path.join(folder, 'waits'), 'utf8').trim().split('\n').map(Number); + const waits = FileSystem.readFile(path.join(folder, 'waits')).trim().split('\n').map(Number); expect(waits).toHaveLength(restarts + 1); expect(waits[0]).toBe(waitTimeoutMs); for (let index: number = 1; index <= restarts; index++) { @@ -1090,13 +1090,13 @@ describe('detached daemon startup', () => { expect(waits[index]).toBeGreaterThanOrEqual(0); } expect(request.admission?.waitTimeoutMs).toBe(waitTimeoutMs); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength( + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength( restarts + 1 ); } else if (mode === 'restart-always') { // Every successor asks again: a limited number of retries inside the admission deadline, then a fallback. expect(await pending).toMatchObject({ kind: 'fallback', reason: 'restartRetriesExhausted' }); - const starts: number = fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n').length; + const starts: number = FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n').length; expect(starts).toBeGreaterThanOrEqual(2); expect(starts).toBeLessThanOrEqual(7); // The deadline may expire after the last successor started but before the request was resubmitted. @@ -1108,8 +1108,8 @@ describe('detached daemon startup', () => { expect(requests).toBeLessThanOrEqual(starts); } else { await expect(pending).rejects.toThrow('previous daemon still owns'); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(1); - expect(fs.readFileSync(path.join(folder, 'requests'), 'utf8').trim().split('\n')).toHaveLength(1); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(1); + expect(FileSystem.readFile(path.join(folder, 'requests')).trim().split('\n')).toHaveLength(1); } }, 15000 @@ -1137,7 +1137,7 @@ describe('detached daemon startup', () => { request, onRestartAsync: async (notice) => { // The successor has not received the request yet. - expect(fs.readFileSync(path.join(folder, 'requests'), 'utf8').trim().split('\n')).toHaveLength(1); + expect(FileSystem.readFile(path.join(folder, 'requests')).trim().split('\n')).toHaveLength(1); notices.push(notice); } }); @@ -1209,8 +1209,8 @@ describe('detached daemon startup', () => { } else { expect(error).not.toBeInstanceOf(DaemonRestartFailedError); } - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(1); - expect(fs.readFileSync(path.join(folder, 'requests'), 'utf8').trim().split('\n')).toHaveLength(1); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(1); + expect(FileSystem.readFile(path.join(folder, 'requests')).trim().split('\n')).toHaveLength(1); } ); @@ -1243,7 +1243,7 @@ describe('detached daemon startup', () => { { request, abortSignal: source === 'execution' ? abort.signal : undefined } ) ).toMatchObject({ kind: 'result', result: { exitCode: 130, aborted: true } }); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(1); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(1); } finally { clearTimeout(timer); } @@ -1275,8 +1275,8 @@ describe('detached daemon startup', () => { reason: 'restartRetriesExhausted' }); expect(Date.now() - startedAt).toBeLessThan(5000); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(1); - expect(fs.readFileSync(path.join(folder, 'requests'), 'utf8').trim().split('\n')).toHaveLength(1); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(1); + expect(FileSystem.readFile(path.join(folder, 'requests')).trim().split('\n')).toHaveLength(1); }); it.each([ @@ -1284,7 +1284,7 @@ describe('detached daemon startup', () => { ['not an explicit timeout', false] ])('follows a restart that takes longer than %s', async (name, isDefault) => { // The first daemon answers only after the timeout, like one that restarts after a long build. - fs.writeFileSync(path.join(folder, 'drain-ms'), '800'); + FileSystem.writeFile(path.join(folder, 'drain-ms'), '800'); const connection: IConnectOrStartDaemonOptions = { ...options, startCommand: { @@ -1303,13 +1303,13 @@ describe('detached daemon startup', () => { admission: isDefault ? { waitTimeoutMs: 300, waitTimeoutIsDefault: true } : { waitTimeoutMs: 300 } }); const outcome = await executeWithDaemonRestartAsync(client, connection, { request }); - const starts: string[] = fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n'); - const waits: string[] = fs.readFileSync(path.join(folder, 'waits'), 'utf8').trim().split('\n'); + const starts: string[] = FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n'); + const waits: string[] = FileSystem.readFile(path.join(folder, 'waits')).trim().split('\n'); if (isDefault) { expect(outcome).toMatchObject({ kind: 'result', result: { exitCode: 0 } }); expect(starts).toHaveLength(2); expect(waits).toEqual(['300', '300']); - expect(fs.readFileSync(path.join(folder, 'default-waits'), 'utf8').trim().split('\n')).toHaveLength(2); + expect(FileSystem.readFile(path.join(folder, 'default-waits')).trim().split('\n')).toHaveLength(2); } else { expect(outcome).toMatchObject({ kind: 'fallback', reason: 'restartRetriesExhausted' }); expect(starts).toHaveLength(1); @@ -1326,8 +1326,8 @@ describe('detached daemon startup', () => { } }; const client = await connectOrStartDaemonAsync(connection); - const owner = JSON.parse(fs.readFileSync(paths.lockfilePath, 'utf8')); - fs.writeFileSync(paths.lockfilePath, JSON.stringify({ ...owner, pid: process.pid })); + const owner = JSON.parse(FileSystem.readFile(paths.lockfilePath)); + FileSystem.writeFile(paths.lockfilePath, JSON.stringify({ ...owner, pid: process.pid })); const request = captureDaemonRequest({ argv: ['test'], commandName: 'test', @@ -1341,7 +1341,7 @@ describe('detached daemon startup', () => { 'Cannot attest' ); } finally { - fs.writeFileSync(paths.lockfilePath, JSON.stringify(owner)); + FileSystem.writeFile(paths.lockfilePath, JSON.stringify(owner)); } }); @@ -1372,8 +1372,8 @@ describe('detached daemon startup', () => { async function waitForRequestAsync(): Promise { const deadline: number = Date.now() + 5000; - while (!fs.existsSync(path.join(folder, 'requests')) && Date.now() < deadline) await delayAsync(20); - expect(fs.existsSync(path.join(folder, 'requests'))).toBe(true); + while (!FileSystem.exists(path.join(folder, 'requests')) && Date.now() < deadline) await delayAsync(20); + expect(FileSystem.exists(path.join(folder, 'requests'))).toBe(true); } it('says that rushd exited and quotes the error it logged, without retrying', async () => { @@ -1390,8 +1390,8 @@ describe('detached daemon startup', () => { `${exitedMessage(pid!, true)}\n` + 'The daemon log reports: Error: fixture daemon crash while running the request' }); - expect(fs.readFileSync(path.join(folder, 'requests'), 'utf8')).toBe('fixture\n'); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8')).toBe(`${pid}\n`); + expect(FileSystem.readFile(path.join(folder, 'requests'))).toBe('fixture\n'); + expect(FileSystem.readFile(path.join(folder, 'starts'))).toBe(`${pid}\n`); }); it('ignores log output from before the request and names the rushx client', async () => { @@ -1406,14 +1406,14 @@ describe('detached daemon startup', () => { 'Node.js v22.0.0', '' ].join('\n'); - fs.writeFileSync(getDaemonLogFilePath(paths), earlierCrash); + FileSystem.writeFile(getDaemonLogFilePath(paths), earlierCrash); const connection: IConnectOrStartDaemonOptions = withMode('kill-on-request'); const client: DaemonClient = await connectOrStartDaemonAsync(connection); const { pid } = await client.status; await expect( executeWithDaemonRestartAsync(client, connection, { request: captureRequest('rushx') }) ).rejects.toMatchObject({ code: 'disconnected', message: exitedMessage(pid!, false, 'rushx-client') }); - expect(fs.readFileSync(getDaemonLogFilePath(paths), 'utf8')).toContain(earlierCrash); + expect(FileSystem.readFile(getDaemonLogFilePath(paths))).toContain(earlierCrash); }); (process.platform === 'linux' ? it : it.skip)( @@ -1431,11 +1431,11 @@ describe('detached daemon startup', () => { await expect( executeWithDaemonRestartAsync(client, connection, { request: captureRequest() }) ).rejects.toMatchObject({ code: 'disconnected', message: exitedMessage(pid!, false) }); - expect(isRunning(Number(fs.readFileSync(operationsPath, 'utf8')))).toBe(false); + expect(isRunning(Number(FileSystem.readFile(operationsPath)))).toBe(false); expect(reaps).toEqual([{ daemonPid: pid, processGroupIds: [pid], outcome: 'terminated' }]); } finally { - if (fs.existsSync(operationsPath)) { - stopOperationIfRunning(Number(fs.readFileSync(operationsPath, 'utf8'))); + if (FileSystem.exists(operationsPath)) { + stopOperationIfRunning(Number(FileSystem.readFile(operationsPath))); } } } @@ -1451,7 +1451,7 @@ describe('detached daemon startup', () => { code: 'disconnected', message: `${DAEMON_DISCONNECTED_MESSAGE} The connection to rushd (PID ${pid}) closed, but the daemon is still running; run the command again.` }); - expect(fs.existsSync(path.join(folder, `stopped-${pid}`))).toBe(false); + expect(FileSystem.exists(path.join(folder, `stopped-${pid}`))).toBe(false); }); it('keeps the plain text after the request was cancelled', async () => { @@ -1499,8 +1499,8 @@ describe('detached daemon startup', () => { const replacement = await connectOrStartDaemonAsync(options); try { expect((await replacement.status).pid).not.toBe(previous.pid); - expect(fs.existsSync(path.join(folder, `stopped-${previous.pid}`))).toBe(true); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(2); + expect(FileSystem.exists(path.join(folder, `stopped-${previous.pid}`))).toBe(true); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(2); } finally { await replacement.closeAsync(); } @@ -1508,7 +1508,7 @@ describe('detached daemon startup', () => { it('waits for an externally started successor without enabling auto-start', async () => { const running = await connectOrStartDaemonAsync(options); - const previous = JSON.parse(fs.readFileSync(paths.lockfilePath, 'utf8')) as IDaemonLockfile; + const previous = JSON.parse(FileSystem.readFile(paths.lockfilePath)) as IDaemonLockfile; await running.shutdownAsync(); const waiting = connectOrStartDaemonAsync({ paths, @@ -1521,7 +1521,7 @@ describe('detached daemon startup', () => { const passive = await waiting; expect((await passive.status).pid).toBe((await starter.status).pid); await passive.closeAsync(); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(2); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(2); } finally { await starter.closeAsync(); } @@ -1529,8 +1529,8 @@ describe('detached daemon startup', () => { it('lets a restarting daemon start its planned successor while the clients that follow it only connect', async () => { // The old daemon launches only after both clients could have started one, so a race would always be lost. - fs.writeFileSync(path.join(folder, 'planned-requests'), '2'); - fs.writeFileSync(path.join(folder, 'planned-launch-delay-ms'), '1500'); + FileSystem.writeFile(path.join(folder, 'planned-requests'), '2'); + FileSystem.writeFile(path.join(folder, 'planned-launch-delay-ms'), '1500'); const planned: IConnectOrStartDaemonOptions = { ...options, startCommand: { @@ -1565,10 +1565,10 @@ describe('detached daemon startup', () => { ]); // The restarting daemon exits only after it attests the successor it launched. await waitForTestProcessExitAsync(restartingPid!); - const identities: string[] = fs.readFileSync(path.join(folder, 'identities'), 'utf8').trim().split('\n'); + const identities: string[] = FileSystem.readFile(path.join(folder, 'identities')).trim().split('\n'); expect(identities.map((line) => line.split(' ')[1])).toEqual(['client', 'planned']); - expect(fs.readFileSync(path.join(folder, 'planned-successor'), 'utf8')).toBe(identities[1].split(' ')[0]); - expect(fs.readFileSync(path.join(folder, 'requests'), 'utf8').trim().split('\n')).toHaveLength(4); + expect(FileSystem.readFile(path.join(folder, 'planned-successor'))).toBe(identities[1].split(' ')[0]); + expect(FileSystem.readFile(path.join(folder, 'requests')).trim().split('\n')).toHaveLength(4); }, 15000); it('connects to the successor that another process starts while the restarting predecessor lives', async () => { @@ -1577,13 +1577,13 @@ describe('detached daemon startup', () => { previousDaemon: { pid: process.pid, startedAt: new Date().toISOString() } }); await delayAsync(300); - expect(fs.existsSync(path.join(folder, 'starts'))).toBe(false); + expect(FileSystem.exists(path.join(folder, 'starts'))).toBe(false); const starter = await connectOrStartDaemonAsync(options); try { const follower = await waiting; expect((await follower.status).pid).toBe((await starter.status).pid); await follower.closeAsync(); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(1); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(1); } finally { await starter.closeAsync(); } @@ -1597,7 +1597,7 @@ describe('detached daemon startup', () => { startupTimeoutMs: 300 }) ).rejects.toThrow(`timed out waiting for the successor that the previous daemon (PID ${process.pid})`); - expect(fs.existsSync(path.join(folder, 'starts'))).toBe(false); + expect(FileSystem.exists(path.join(folder, 'starts'))).toBe(false); }); it('starts a daemon once the restarting predecessor exits without a successor', async () => { @@ -1613,20 +1613,20 @@ describe('detached daemon startup', () => { }); try { await delayAsync(300); - expect(fs.existsSync(path.join(folder, 'starts'))).toBe(false); + expect(FileSystem.exists(path.join(folder, 'starts'))).toBe(false); } finally { predecessor.stdin!.end(); } await exited; const client = await pending; await client.closeAsync(); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(1); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(1); }); it('does not stop a mismatched daemon with unverifiable ownership', async () => { const running = await connectOrStartDaemonAsync(options); await running.closeAsync(); - fs.writeFileSync(paths.lockfilePath, 'corrupt'); + FileSystem.writeFile(paths.lockfilePath, 'corrupt'); await expect( connectOrStartDaemonAsync({ ...options, @@ -1638,13 +1638,13 @@ describe('detached daemon startup', () => { expectedDaemonVersion: 'fixture' }); await original.closeAsync(); - expect(fs.readFileSync(paths.lockfilePath, 'utf8')).toBe('corrupt'); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(1); + expect(FileSystem.readFile(paths.lockfilePath)).toBe('corrupt'); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(1); }); it('does not start when auto-start is absent', async () => { await expect(connectOrStartDaemonAsync({ paths })).rejects.toThrow('auto-start is disabled'); - expect(fs.existsSync(path.join(folder, 'starts'))).toBe(false); + expect(FileSystem.exists(path.join(folder, 'starts'))).toBe(false); }); it('appends both child streams to the private workspace launcher log', async () => { @@ -1653,7 +1653,7 @@ describe('detached daemon startup', () => { if (process.platform !== 'win32') fs.chmodSync(logFilePath, 0o644); const client = await connectOrStartDaemonAsync(options); await client.closeAsync(); - const log: string = fs.readFileSync(logFilePath, 'utf8'); + const log: string = FileSystem.readFile(logFilePath); expect(log).toContain('previous startup\n'); expect(log).toContain('launcher stdout\n'); expect(log).toContain('launcher stderr\n'); @@ -1673,13 +1673,13 @@ describe('detached daemon startup', () => { } }) ).rejects.toThrow(logFilePath); - expect(fs.readFileSync(logFilePath, 'utf8')).toContain('Cannot find module'); + expect(FileSystem.readFile(logFilePath)).toContain('Cannot find module'); }); it('tells the daemon it starts which runtime folder its clients look in', async () => { const client = await connectOrStartDaemonAsync(options); await client.closeAsync(); - expect(fs.readFileSync(path.join(folder, 'runtime-base'), 'utf8')).toBe(path.dirname(folder)); + expect(FileSystem.readFile(path.join(folder, 'runtime-base'))).toBe(path.dirname(folder)); }); (process.platform === 'win32' ? it.skip : it)( @@ -1701,9 +1701,9 @@ describe('detached daemon startup', () => { await expect(failure).rejects.toThrow( `The daemon runtime folder ${link} is unsafe: it is a symbolic link` ); - expect(fs.existsSync(path.join(folder, 'starts'))).toBe(false); + expect(FileSystem.exists(path.join(folder, 'starts'))).toBe(false); } finally { - fs.unlinkSync(link); + FileSystem.deleteFile(link, { throwIfNotExists: true }); } } ); @@ -1728,8 +1728,8 @@ describe('detached daemon startup', () => { await expect(failure).rejects.toThrow( /^The daemon socket path .*\/d\.sock is \d+ bytes long, but this platform allows at most 10[48]\. Set RUSHD_RUNTIME_DIR to an absolute path of at most \d+ bytes, or unset it\.$/ ); - expect(fs.existsSync(base)).toBe(false); - expect(fs.existsSync(path.join(folder, 'starts'))).toBe(false); + expect(FileSystem.exists(base)).toBe(false); + expect(FileSystem.exists(path.join(folder, 'starts'))).toBe(false); } ); @@ -1745,12 +1745,12 @@ describe('detached daemon startup', () => { code: 'startupFailed', cause: { code: 'ELOOP' } }); - fs.unlinkSync(logFilePath); + FileSystem.deleteFile(logFilePath, { throwIfNotExists: true }); fs.linkSync(target, logFilePath); await expect(connectOrStartDaemonAsync(options)).rejects.toThrow('regular, unshared file'); - expect(fs.readFileSync(target, 'utf8')).toBe('unchanged'); + expect(FileSystem.readFile(target)).toBe('unchanged'); expect(FileSystem.formatPosixModeBits(FileSystem.getPosixModeBits(target))).toBe('-rw-r--r--'); - expect(fs.existsSync(path.join(folder, 'starts'))).toBe(false); + expect(FileSystem.exists(path.join(folder, 'starts'))).toBe(false); } ); @@ -1761,7 +1761,7 @@ describe('detached daemon startup', () => { startedAt: 'invalid', socketPath: paths.socketPath }); - fs.writeFileSync(paths.lockfilePath, record); + FileSystem.writeFile(paths.lockfilePath, record); const started: number = Date.now(); const client = await connectOrStartDaemonAsync(options); await client.closeAsync(); @@ -1772,7 +1772,7 @@ describe('detached daemon startup', () => { (process.platform === 'win32' ? it.skip : it)( 'force reset waits for a listener to release the endpoint', async () => { - fs.writeFileSync(getDaemonStartupFilePath(paths), 'abandoned'); + FileSystem.writeFile(getDaemonStartupFilePath(paths), 'abandoned'); const listener: net.Server = net.createServer((socket) => socket.destroy()); await new Promise((resolve) => listener.listen(paths.socketPath, resolve)); await expect(resetDaemonArtifactsAsync(paths)).rejects.toThrow('still listening'); @@ -1790,28 +1790,28 @@ describe('detached daemon startup', () => { it('never reclaims a live PID that may still own the record', async () => { const record: string = JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() }); - fs.writeFileSync(paths.lockfilePath, record); + FileSystem.writeFile(paths.lockfilePath, record); // The error names that process and says when removing the record is safe. await expect(connectOrStartDaemonAsync(options)).rejects.toThrow(`PID ${process.pid}`); await expect(connectOrStartDaemonAsync(options)).rejects.toThrow(`delete ${paths.lockfilePath}`); - expect(fs.readFileSync(paths.lockfilePath, 'utf8')).toBe(record); + expect(FileSystem.readFile(paths.lockfilePath)).toBe(record); await expect(resetDaemonArtifactsAsync(paths)).rejects.toThrow(`still owns ${paths.lockfilePath}`); await expect(resetDaemonArtifactsAsync(paths)).rejects.toThrow('No process was killed.'); - expect(fs.readFileSync(paths.lockfilePath, 'utf8')).toBe(record); + expect(FileSystem.readFile(paths.lockfilePath)).toBe(record); }); it('reclaims a corrupt ownership record once the endpoint refuses connections', async () => { - fs.writeFileSync(paths.lockfilePath, 'not json'); + FileSystem.writeFile(paths.lockfilePath, 'not json'); const client = await connectOrStartDaemonAsync(options); await client.closeAsync(); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(1); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(1); expect(readDaemonLockfile(paths.lockfilePath)?.pid).toBe( - Number(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim()) + Number(FileSystem.readFile(path.join(folder, 'starts')).trim()) ); }); it('fails closed on a corrupt ownership record while something still listens', async () => { - fs.writeFileSync(paths.lockfilePath, 'not json'); + FileSystem.writeFile(paths.lockfilePath, 'not json'); const listener: net.Server = net.createServer((socket) => socket.destroy()); await new Promise((resolve) => listener.listen(paths.socketPath, resolve)); try { @@ -1819,8 +1819,8 @@ describe('detached daemon startup', () => { 'did not refuse a connection' ); await expect(resetDaemonArtifactsAsync(paths)).rejects.toThrow('still listening'); - expect(fs.readFileSync(paths.lockfilePath, 'utf8')).toBe('not json'); - expect(fs.existsSync(path.join(folder, 'starts'))).toBe(false); + expect(FileSystem.readFile(paths.lockfilePath)).toBe('not json'); + expect(FileSystem.exists(path.join(folder, 'starts'))).toBe(false); } finally { await new Promise((resolve) => listener.close(() => resolve())); } @@ -1830,10 +1830,10 @@ describe('detached daemon startup', () => { 'reclaims a socket without an ownership record once it refuses connections', async () => { await leaveStaleSocketAsync(); - expect(fs.existsSync(paths.socketPath)).toBe(true); + expect(FileSystem.exists(paths.socketPath)).toBe(true); const client = await connectOrStartDaemonAsync(options); await client.closeAsync(); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(1); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(1); } ); @@ -1864,7 +1864,7 @@ describe('detached daemon startup', () => { describeGroupLeftRunning(daemonPid, other, 'leaderChanged') ]); expect(warning).not.toHaveBeenCalled(); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(1); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(1); } finally { warning.mockRestore(); operationPids.forEach(stopOperationIfRunning); @@ -1881,7 +1881,7 @@ describe('detached daemon startup', () => { await once(unrelated, 'spawn'); try { await leaveStaleSocketAsync(); - fs.writeFileSync( + FileSystem.writeFile( paths.lockfilePath, JSON.stringify({ pid: unrelated.pid, @@ -1909,13 +1909,13 @@ describe('detached daemon startup', () => { 'force reset removes stale artifacts without starting a daemon', async () => { await leaveStaleSocketAsync(); - fs.writeFileSync(paths.lockfilePath, 'garbage{'); - fs.writeFileSync(getDaemonStartupFilePath(paths), 'abandoned'); + FileSystem.writeFile(paths.lockfilePath, 'garbage{'); + FileSystem.writeFile(getDaemonStartupFilePath(paths), 'abandoned'); expect(await resetDaemonArtifactsAsync(paths)).toEqual({ removedPaths: [paths.lockfilePath, getDaemonStartupFilePath(paths), paths.socketPath] }); expect(await resetDaemonArtifactsAsync(paths)).toEqual({ removedPaths: [] }); - expect(fs.existsSync(path.join(folder, 'starts'))).toBe(false); + expect(FileSystem.exists(path.join(folder, 'starts'))).toBe(false); } ); @@ -1925,13 +1925,13 @@ describe('detached daemon startup', () => { previousDaemon: { pid: process.pid, startedAt: new Date().toISOString() } }); await client.closeAsync(); - expect(fs.existsSync(path.join(folder, 'starts'))).toBe(true); + expect(FileSystem.exists(path.join(folder, 'starts'))).toBe(true); }); it('preserves a live predecessor lock when restart times out', async () => { const previousDaemon = { pid: process.pid, startedAt: new Date().toISOString() }; const record: string = JSON.stringify(previousDaemon); - fs.writeFileSync(paths.lockfilePath, record); + FileSystem.writeFile(paths.lockfilePath, record); await expect( connectOrStartDaemonAsync({ ...options, @@ -1939,16 +1939,16 @@ describe('detached daemon startup', () => { startupTimeoutMs: 40 }) ).rejects.toThrow('previous daemon still owns'); - expect(fs.readFileSync(paths.lockfilePath, 'utf8')).toBe(record); + expect(FileSystem.readFile(paths.lockfilePath)).toBe(record); }); it('waits for disposal to release the original lock before starting', async () => { const previousDaemon = { pid: process.pid, startedAt: new Date().toISOString() }; - fs.writeFileSync(paths.lockfilePath, JSON.stringify(previousDaemon)); + FileSystem.writeFile(paths.lockfilePath, JSON.stringify(previousDaemon)); const pending = connectOrStartDaemonAsync({ ...options, previousDaemon }); await delayAsync(100); - expect(fs.existsSync(path.join(folder, 'starts'))).toBe(false); - fs.unlinkSync(paths.lockfilePath); + expect(FileSystem.exists(path.join(folder, 'starts'))).toBe(false); + FileSystem.deleteFile(paths.lockfilePath, { throwIfNotExists: true }); const client = await pending; await client.closeAsync(); }); @@ -1956,7 +1956,7 @@ describe('detached daemon startup', () => { it('reconnects to a new owner even if it uses the same PID as the predecessor', async () => { const first = await connectOrStartDaemonAsync(options); await first.closeAsync(); - const owner: IDaemonLockfile = JSON.parse(fs.readFileSync(paths.lockfilePath, 'utf8')); + const owner: IDaemonLockfile = JSON.parse(FileSystem.readFile(paths.lockfilePath)); const client = await connectOrStartDaemonAsync({ ...options, previousDaemon: { @@ -1965,27 +1965,27 @@ describe('detached daemon startup', () => { } }); await client.closeAsync(); - expect(fs.readFileSync(path.join(folder, 'starts'), 'utf8').trim().split('\n')).toHaveLength(1); + expect(FileSystem.readFile(path.join(folder, 'starts')).trim().split('\n')).toHaveLength(1); }); it('safely reclaims a dead predecessor without requiring lockfile removal', async () => { const exited: ChildProcess = spawn(process.execPath, ['-e', ''], { stdio: 'ignore' }); const previousDaemon = { pid: exited.pid!, startedAt: new Date().toISOString() }; await once(exited, 'exit'); - fs.writeFileSync(paths.lockfilePath, JSON.stringify(previousDaemon)); + FileSystem.writeFile(paths.lockfilePath, JSON.stringify(previousDaemon)); const client = await connectOrStartDaemonAsync({ ...options, previousDaemon }); await client.closeAsync(); }); it('does not treat an unreadable ownership record as released', async () => { - fs.writeFileSync(paths.lockfilePath, 'corrupt'); + FileSystem.writeFile(paths.lockfilePath, 'corrupt'); await expect( connectOrStartDaemonAsync({ ...options, previousDaemon: { pid: process.pid, startedAt: new Date().toISOString() } }) ).rejects.toThrow('Cannot safely read'); - expect(fs.readFileSync(paths.lockfilePath, 'utf8')).toBe('corrupt'); + expect(FileSystem.readFile(paths.lockfilePath)).toBe('corrupt'); }); it('reports spawn failures and releases the start lock for another invocation', async () => { diff --git a/libraries/rush-daemon/src/test/DaemonGraphFixturePaths.test.ts b/libraries/rush-daemon/src/test/DaemonGraphFixturePaths.test.ts index 46324e370cb..393340414ed 100644 --- a/libraries/rush-daemon/src/test/DaemonGraphFixturePaths.test.ts +++ b/libraries/rush-daemon/src/test/DaemonGraphFixturePaths.test.ts @@ -4,21 +4,23 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; +import { FileSystem } from '@rushstack/node-core-library'; + import { DaemonGraphTestFixture } from './DaemonGraphTestFixture'; it('uses the physical fixture folder even when the temporary root is reached through an alias', async () => { const testRoot: string = `${__dirname}/../../temp/test/graph-paths`; - fs.mkdirSync(testRoot, { recursive: true }); + FileSystem.ensureFolder(testRoot); const root: string = fs.mkdtempSync(`${testRoot}/case-`); const physical: string = `${root}/physical temporary directory`; const alias: string = `${root}/alias`; let fixture: DaemonGraphTestFixture | undefined; try { - fs.mkdirSync(physical); + FileSystem.ensureFolder(physical); fs.symlinkSync(physical, alias, process.platform === 'win32' ? 'junction' : 'dir'); fixture = new DaemonGraphTestFixture(alias); - expect(fixture.folder).toBe(fs.realpathSync.native(fixture.folder)); - expect(path.dirname(fixture.folder)).toBe(fs.realpathSync.native(physical)); + expect(fixture.folder).toBe(FileSystem.getRealPath(fixture.folder)); + expect(path.dirname(fixture.folder)).toBe(FileSystem.getRealPath(physical)); } finally { await fixture?.[Symbol.asyncDispose](); } @@ -28,19 +30,19 @@ it('copies immutable inputs into independent project-local workspaces and retain const first: DaemonGraphTestFixture = await DaemonGraphTestFixture.createAsync(); let second: DaemonGraphTestFixture | undefined; try { - const root: string = fs.realpathSync.native(`${__dirname}/../../temp/test/graph`); - const fixtureInput: string = fs.readFileSync(`${__dirname}/fixtures/graph/a/input.txt`, 'utf8'); + const root: string = FileSystem.getRealPath(`${__dirname}/../../temp/test/graph`); + const fixtureInput: string = FileSystem.readFile(`${__dirname}/fixtures/graph/a/input.txt`); expect(path.dirname(first.folder)).toBe(root); first.write('a/input.txt', 'changed'); await first[Symbol.asyncDispose](); - expect(fs.readFileSync(`${first.folder}/a/input.txt`, 'utf8')).toBe('changed'); - expect(fs.existsSync(first.host.paths.lockfilePath)).toBe(false); + expect(FileSystem.readFile(`${first.folder}/a/input.txt`)).toBe('changed'); + expect(FileSystem.exists(first.host.paths.lockfilePath)).toBe(false); second = await DaemonGraphTestFixture.createAsync(); expect(path.dirname(second.folder)).toBe(root); expect(second.folder).not.toBe(first.folder); - expect(fs.readFileSync(`${second.folder}/a/input.txt`, 'utf8')).toBe(fixtureInput); - expect(fs.readFileSync(`${__dirname}/fixtures/graph/a/input.txt`, 'utf8')).toBe(fixtureInput); + expect(FileSystem.readFile(`${second.folder}/a/input.txt`)).toBe(fixtureInput); + expect(FileSystem.readFile(`${__dirname}/fixtures/graph/a/input.txt`)).toBe(fixtureInput); } finally { await second?.[Symbol.asyncDispose](); await first[Symbol.asyncDispose](); diff --git a/libraries/rush-daemon/src/test/DaemonGraphFixtureSetup.test.ts b/libraries/rush-daemon/src/test/DaemonGraphFixtureSetup.test.ts index 5f6978d0ecb..9410096df70 100644 --- a/libraries/rush-daemon/src/test/DaemonGraphFixtureSetup.test.ts +++ b/libraries/rush-daemon/src/test/DaemonGraphFixtureSetup.test.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import * as fs from 'node:fs'; +import { FileSystem } from '@rushstack/node-core-library'; import { RushDaemonHost } from '../RushDaemonHost'; import { DaemonGraphTestFixture } from './DaemonGraphTestFixture'; @@ -64,14 +64,14 @@ describe('daemon graph fixture initialization ownership', () => { await Promise.resolve(); expect(settled).toBe(false); expect(closed).toBe(false); - expect(fs.existsSync(captured!.folder)).toBe(true); + expect(FileSystem.exists(captured!.folder)).toBe(true); // A fixture holds the whole process environment, so a failure prints only a boolean. expect(published === undefined).toBe(true); release.resolve(); expect(await joined).toEqual([{ status: 'rejected', reason: controller.signal.reason }]); expect(closed).toBe(true); - expect(fs.existsSync(captured!.folder)).toBe(true); - expect(fs.existsSync(host.paths.lockfilePath)).toBe(false); + expect(FileSystem.exists(captured!.folder)).toBe(true); + expect(FileSystem.exists(host.paths.lockfilePath)).toBe(false); expect(published === undefined).toBe(true); } finally { await cleanupAsync(); @@ -89,7 +89,7 @@ describe('daemon graph fixture initialization ownership', () => { }) ) ).rejects.toBe(failure); - expect(fs.existsSync(captured!.folder)).toBe(true); + expect(FileSystem.exists(captured!.folder)).toBe(true); expect(captured!.host).toBeUndefined(); }); @@ -109,7 +109,7 @@ describe('daemon graph fixture initialization ownership', () => { }) ) ).rejects.toMatchObject({ errors: [failure, cleanupFailure] }); - expect(fs.existsSync(captured!.folder)).toBe(true); + expect(FileSystem.exists(captured!.folder)).toBe(true); } finally { dispose.mockRestore(); if (captured) await captured[Symbol.asyncDispose](); @@ -134,7 +134,7 @@ describe('daemon graph fixture initialization ownership', () => { ) ).rejects.toBe(controller.signal.reason); expect(start).not.toHaveBeenCalled(); - expect(fs.existsSync(captured!.folder)).toBe(true); + expect(FileSystem.exists(captured!.folder)).toBe(true); } finally { start.mockRestore(); } diff --git a/libraries/rush-daemon/src/test/DaemonGraphTestFixture.ts b/libraries/rush-daemon/src/test/DaemonGraphTestFixture.ts index ad2be9dad71..b7f2a4f5bb0 100644 --- a/libraries/rush-daemon/src/test/DaemonGraphTestFixture.ts +++ b/libraries/rush-daemon/src/test/DaemonGraphTestFixture.ts @@ -3,9 +3,9 @@ import { execFileSync } from 'node:child_process'; import * as fs from 'node:fs'; -import * as path from 'node:path'; import { Rush } from '@microsoft/rush-lib'; +import { FileSystem } from '@rushstack/node-core-library'; import { DaemonFrameType, decodeDaemonEventFrame, @@ -102,8 +102,8 @@ export class DaemonGraphTestFixture implements AsyncDisposable { #lifecycle: boolean = true; public constructor(root: string = `${__dirname}/../../temp/test/graph`) { - fs.mkdirSync(root, { recursive: true }); - this.folder = fs.realpathSync.native(fs.mkdtempSync(`${root}/case-`)); + FileSystem.ensureFolder(root); + this.folder = FileSystem.getRealPath(fs.mkdtempSync(`${root}/case-`)); } public static async createAsync( @@ -115,10 +115,13 @@ export class DaemonGraphTestFixture implements AsyncDisposable { fixture.#lifecycle = lifecycle; try { signal?.throwIfAborted(); - fs.cpSync(`${__dirname}/fixtures/graph`, fixture.folder, { recursive: true }); - fs.renameSync(`${fixture.folder}/gitignore`, `${fixture.folder}/.gitignore`); + FileSystem.copyFiles({ sourcePath: `${__dirname}/fixtures/graph`, destinationPath: fixture.folder }); + FileSystem.move({ + sourcePath: `${fixture.folder}/gitignore`, + destinationPath: `${fixture.folder}/.gitignore` + }); const rushJson: { rushVersion: string } = JSON.parse( - fs.readFileSync(`${fixture.folder}/rush.json`, 'utf8') + FileSystem.readFile(`${fixture.folder}/rush.json`) ); rushJson.rushVersion = Rush.version; fixture.write('rush.json', JSON.stringify(rushJson)); @@ -199,14 +202,12 @@ export class DaemonGraphTestFixture implements AsyncDisposable { } public write(name: string, text: string): void { - const filename: string = `${this.folder}/${name}`; - fs.mkdirSync(path.dirname(filename), { recursive: true }); - fs.writeFileSync(filename, text); + FileSystem.writeFile(`${this.folder}/${name}`, text, { ensureFolderExists: true }); } public runs(): string[] { const filename: string = `${this.folder}/runs.txt`; - return fs.existsSync(filename) ? fs.readFileSync(filename, 'utf8').trim().split('\n') : []; + return FileSystem.exists(filename) ? FileSystem.readFile(filename).trim().split('\n') : []; } public async connectAsync(): Promise {