@zenfs/devel 0.1.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/bin/make-index.js +37 -74
  2. package/dist/bin/node-compat.d.ts +2 -0
  3. package/dist/bin/node-compat.js +340 -0
  4. package/dist/bin/zci.js +33 -44
  5. package/dist/bin/zenfs-test.js +45 -78
  6. package/dist/index.d.ts +1 -0
  7. package/dist/index.js +1 -0
  8. package/dist/make_index.d.ts +20 -0
  9. package/dist/make_index.js +49 -0
  10. package/dist/node_compat/analysis.d.ts +53 -0
  11. package/dist/node_compat/analysis.js +60 -0
  12. package/dist/node_compat/changelog.d.ts +25 -0
  13. package/dist/node_compat/changelog.js +60 -0
  14. package/dist/node_compat/commits.d.ts +26 -0
  15. package/dist/node_compat/commits.js +66 -0
  16. package/dist/node_compat/config.d.ts +6 -0
  17. package/dist/node_compat/config.js +18 -0
  18. package/dist/node_compat/docs.d.ts +58 -0
  19. package/dist/node_compat/docs.js +213 -0
  20. package/dist/node_compat/git.d.ts +22 -0
  21. package/dist/node_compat/git.js +74 -0
  22. package/dist/node_compat/index.d.ts +10 -0
  23. package/dist/node_compat/index.js +11 -0
  24. package/dist/node_compat/node.d.ts +42 -0
  25. package/dist/node_compat/node.js +84 -0
  26. package/dist/node_compat/output.d.ts +29 -0
  27. package/dist/node_compat/output.js +95 -0
  28. package/dist/node_compat/pr.d.ts +59 -0
  29. package/dist/node_compat/pr.js +125 -0
  30. package/dist/node_compat/state.d.ts +18 -0
  31. package/dist/node_compat/state.js +12 -0
  32. package/dist/node_compat/versions.d.ts +5 -0
  33. package/dist/node_compat/versions.js +13 -0
  34. package/dist/node_compat/zenfs.d.ts +3 -0
  35. package/dist/node_compat/zenfs.js +108 -0
  36. package/dist/tests/fs/callbacks.test.d.ts +1 -0
  37. package/dist/tests/fs/callbacks.test.js +41 -0
  38. package/dist/tests/fs/cp.test.d.ts +1 -0
  39. package/dist/tests/fs/cp.test.js +186 -0
  40. package/dist/tests/fs/dir.test.js +40 -0
  41. package/dist/tests/fs/directory.test.js +42 -0
  42. package/dist/tests/fs/links.test.js +36 -0
  43. package/dist/tests/fs/open.test.js +15 -0
  44. package/dist/tests/fs/read.test.js +139 -2
  45. package/dist/tests/fs/readFile.test.js +159 -0
  46. package/dist/tests/fs/stat.test.js +67 -0
  47. package/dist/tests/fs/streams.test.js +178 -0
  48. package/dist/tests/fs/tempdir.test.js +8 -0
  49. package/dist/tests/fs/truncate.test.js +89 -0
  50. package/dist/tests/fs/watch.test.js +131 -6
  51. package/dist/tests/fs/write.test.js +182 -0
  52. package/package.json +8 -3
@@ -0,0 +1,125 @@
1
+ import { parseSubject } from './commits.js';
2
+ import { compareVersions } from './versions.js';
3
+ export class PR {
4
+ number;
5
+ title = '';
6
+ subsystems = [];
7
+ author = '';
8
+ semver = 'unreleased';
9
+ revert = false;
10
+ /** Commits on the tracked ref, oldest first */
11
+ commits = [];
12
+ /** Every release that lists the PR, ascending */
13
+ releases = [];
14
+ /** Affected APIs, by ID */
15
+ apis = { added: [], removed: [], changed: [] };
16
+ constructor(number) {
17
+ this.number = number;
18
+ }
19
+ get url() {
20
+ return `https://github.com/nodejs/node/pull/${this.number}`;
21
+ }
22
+ /** Key for marks */
23
+ get key() {
24
+ return '#' + this.number;
25
+ }
26
+ /** Earliest version in each release line, ascending */
27
+ get versions() {
28
+ const earliest = new Map();
29
+ for (const release of this.releases)
30
+ if (!earliest.has(release.line))
31
+ earliest.set(release.line, release.version);
32
+ return [...earliest.values()];
33
+ }
34
+ /** Top-level directories touched */
35
+ get areas() {
36
+ return [...new Set(this.commits.flatMap(commit => commit.files.map(file => file.split('/')[0])))].sort();
37
+ }
38
+ /** Heuristic labels derived from the title and touched areas */
39
+ get tags() {
40
+ const tags = [];
41
+ const title = this.title.toLowerCase();
42
+ const { areas } = this;
43
+ if (this.revert)
44
+ tags.push('revert');
45
+ if (!this.commits.length)
46
+ tags.push('backport');
47
+ if (areas.length) {
48
+ if (!areas.includes('lib'))
49
+ tags.push(areas.includes('src') ? 'native' : areas.every(area => area == 'doc') ? 'docs' : 'internal');
50
+ if (areas.every(area => area == 'test' || area == 'doc'))
51
+ tags.push('test');
52
+ }
53
+ if (/\bwin(dows|32)?\b/.test(title) || this.subsystems.includes('win'))
54
+ tags.push('windows');
55
+ if (/\b(perf|performance|faster|optimi[sz]e|speed up|allocations?)\b/.test(title))
56
+ tags.push('perf');
57
+ if (/\b(experimental|stabilize|stable)\b/.test(title))
58
+ tags.push('stability');
59
+ if (/\b(deprecat|eol|end-of-life)/.test(title))
60
+ tags.push('deprecation');
61
+ return tags;
62
+ }
63
+ /** ISO date the PR landed on the tracked ref, or of its first release */
64
+ get date() {
65
+ return this.commits[0]?.date ?? this.releases[0]?.date ?? '';
66
+ }
67
+ /**
68
+ * Adds a commit in chronological order, along with the APIs it added or removed.
69
+ */
70
+ addCommit(commit, history) {
71
+ this.commits.push(commit);
72
+ const subject = parseSubject(commit.subject);
73
+ if (!this.title && subject) {
74
+ this.title = subject.title;
75
+ this.subsystems = subject.subsystems;
76
+ this.revert = subject.revert;
77
+ this.author = commit.author;
78
+ }
79
+ for (const id of history?.added ?? [])
80
+ toggle(this.apis.added, this.apis.removed, id);
81
+ for (const id of history?.removed ?? [])
82
+ toggle(this.apis.removed, this.apis.added, id);
83
+ }
84
+ addRelease(entry) {
85
+ if (!this.releases.some(release => release.version == entry.release.version)) {
86
+ this.releases.push(entry.release);
87
+ this.releases.sort((left, right) => compareVersions(left.version, right.version));
88
+ }
89
+ if (this.semver == 'unreleased' || entry.semver == 'major' || (entry.semver == 'minor' && this.semver == 'patch'))
90
+ this.semver = entry.semver;
91
+ if (this.title)
92
+ return;
93
+ this.title = entry.title;
94
+ this.subsystems = entry.subsystems;
95
+ this.revert = entry.revert;
96
+ this.author = entry.author;
97
+ }
98
+ toJSON() {
99
+ return {
100
+ number: this.number,
101
+ url: this.url,
102
+ title: this.title,
103
+ subsystems: this.subsystems,
104
+ author: this.author,
105
+ semver: this.semver,
106
+ revert: this.revert,
107
+ commits: this.commits.map(({ hash, date, author, subject, files }) => ({ hash, date, author, subject, files })),
108
+ releases: this.releases,
109
+ versions: this.versions,
110
+ areas: this.areas,
111
+ tags: this.tags,
112
+ apis: this.apis,
113
+ };
114
+ }
115
+ }
116
+ /**
117
+ * Adds `id` to `target`, unless it is in `opposite`, in which case the two cancel out.
118
+ */
119
+ function toggle(target, opposite, id) {
120
+ const index = opposite.indexOf(id);
121
+ if (index != -1)
122
+ opposite.splice(index, 1);
123
+ else if (!target.includes(id))
124
+ target.push(id);
125
+ }
@@ -0,0 +1,18 @@
1
+ import { JSONFileMap } from 'utilium/fs';
2
+ export type Mark = 'resolved' | 'ignored';
3
+ export type MarkEntry = {
4
+ status: Mark;
5
+ note?: string;
6
+ /** ISO date */
7
+ date: string;
8
+ };
9
+ /**
10
+ * Manual marks on PRs (`#<number>`) and APIs (by ID), backed by a JSON file.
11
+ */
12
+ export type Marks = Map<string, MarkEntry>;
13
+ export declare const defaultMarksPath = "node-compat.json";
14
+ /**
15
+ * Opens a marks file, creating it if needed.
16
+ */
17
+ export declare function openMarks(path?: string): JSONFileMap<MarkEntry>;
18
+ export declare function createMark(status: Mark, note?: string): MarkEntry;
@@ -0,0 +1,12 @@
1
+ // SPDX-License-Identifier: LGPL-3.0-or-later
2
+ import { JSONFileMap } from 'utilium/fs';
3
+ export const defaultMarksPath = 'node-compat.json';
4
+ /**
5
+ * Opens a marks file, creating it if needed.
6
+ */
7
+ export function openMarks(path = defaultMarksPath) {
8
+ return new JSONFileMap(path, { overwrite_invalid: false, pretty: true });
9
+ }
10
+ export function createMark(status, note) {
11
+ return { status, ...(note && { note }), date: new Date().toISOString().slice(0, 10) };
12
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @param version A full or partial version, optionally prefixed with `v`
3
+ */
4
+ export declare function parseVersion(version: string): [major: number, minor: number, patch: number];
5
+ export declare function compareVersions(left: string, right: string): number;
@@ -0,0 +1,13 @@
1
+ // SPDX-License-Identifier: LGPL-3.0-or-later
2
+ /**
3
+ * @param version A full or partial version, optionally prefixed with `v`
4
+ */
5
+ export function parseVersion(version) {
6
+ const [major = 0, minor = 0, patch = 0] = version.replace(/^v/, '').split('.').map(Number);
7
+ return [major, minor, patch];
8
+ }
9
+ export function compareVersions(left, right) {
10
+ const [leftMajor, leftMinor, leftPatch] = parseVersion(left);
11
+ const [rightMajor, rightMinor, rightPatch] = parseVersion(right);
12
+ return leftMajor - rightMajor || leftMinor - rightMinor || leftPatch - rightPatch;
13
+ }
@@ -0,0 +1,3 @@
1
+ import type { Api } from './docs.js';
2
+ export declare const version: string;
3
+ export declare function has(api: Api): boolean;
@@ -0,0 +1,108 @@
1
+ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
2
+ if (value !== null && value !== void 0) {
3
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
4
+ var dispose, inner;
5
+ if (async) {
6
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
7
+ dispose = value[Symbol.asyncDispose];
8
+ }
9
+ if (dispose === void 0) {
10
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
11
+ dispose = value[Symbol.dispose];
12
+ if (async) inner = dispose;
13
+ }
14
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
15
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
16
+ env.stack.push({ value: value, dispose: dispose, async: async });
17
+ }
18
+ else if (async) {
19
+ env.stack.push({ async: true });
20
+ }
21
+ return value;
22
+ };
23
+ var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
24
+ return function (env) {
25
+ function fail(e) {
26
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
27
+ env.hasError = true;
28
+ }
29
+ var r, s = 0;
30
+ function next() {
31
+ while (r = env.stack.pop()) {
32
+ try {
33
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
34
+ if (r.dispose) {
35
+ var result = r.dispose.call(r.value);
36
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
37
+ }
38
+ else s |= 1;
39
+ }
40
+ catch (e) {
41
+ fail(e);
42
+ }
43
+ }
44
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
45
+ if (env.hasError) throw env.error;
46
+ }
47
+ return next();
48
+ };
49
+ })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
50
+ var e = new Error(message);
51
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
52
+ });
53
+ // SPDX-License-Identifier: LGPL-3.0-or-later
54
+ import * as zenfs from '@zenfs/core';
55
+ function attempt(create) {
56
+ try {
57
+ return create();
58
+ }
59
+ catch {
60
+ return undefined;
61
+ }
62
+ }
63
+ export const version = zenfs._version;
64
+ export function has(api) {
65
+ let target = targets[api.owner];
66
+ if (target == null)
67
+ return false;
68
+ for (const key of api.path) {
69
+ if ((typeof target != 'object' && typeof target != 'function') || target === null || !(key in target))
70
+ return false;
71
+ target = target[key];
72
+ }
73
+ return true;
74
+ }
75
+ var stack, dir, file, targets;
76
+ const env_1 = { stack: [], error: void 0, hasError: false };
77
+ try {
78
+ stack = __addDisposableResource(env_1, new AsyncDisposableStack(), true);
79
+ dir = '/.node-compat-probe';
80
+ file = dir + '/file';
81
+ zenfs.rmSync(dir, { recursive: true, force: true });
82
+ zenfs.mkdirSync(dir, { recursive: true });
83
+ stack.defer(() => zenfs.rmSync(dir, { recursive: true, force: true }));
84
+ zenfs.writeFileSync(file, 'probe');
85
+ targets = {
86
+ fs: zenfs,
87
+ fsPromises: zenfs.promises,
88
+ FileHandle: stack.use(await zenfs.promises.open(file).catch(() => undefined)),
89
+ Dir: stack.use(attempt(() => zenfs.opendirSync(dir))),
90
+ Dirent: attempt(() => zenfs.readdirSync(dir, { withFileTypes: true })[0]),
91
+ FSWatcher: stack.adopt(attempt(() => zenfs.watch(dir)), watcher => watcher?.close()),
92
+ StatWatcher: stack.adopt(attempt(() => zenfs.watchFile(file, () => { })), () => zenfs.unwatchFile(file)),
93
+ ReadStream: stack.use(attempt(() => zenfs.createReadStream(file))),
94
+ WriteStream: stack.use(attempt(() => zenfs.createWriteStream(dir + '/write'))),
95
+ Stats: attempt(() => zenfs.statSync(file)),
96
+ StatFs: attempt(() => zenfs.statfsSync(dir)),
97
+ Utf8Stream: stack.use(attempt(() => new zenfs.Utf8Stream({ dest: dir + '/utf8', sync: true }))),
98
+ };
99
+ }
100
+ catch (e_1) {
101
+ env_1.error = e_1;
102
+ env_1.hasError = true;
103
+ }
104
+ finally {
105
+ const result_1 = __disposeResources(env_1);
106
+ if (result_1)
107
+ await result_1;
108
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,41 @@
1
+ // SPDX-License-Identifier: LGPL-3.0-or-later
2
+ import assert from 'node:assert/strict';
3
+ import { suite, test } from 'node:test';
4
+ import { config, fs } from '../common.js';
5
+ /**
6
+ * Runs `run` with the process' error listeners replaced, collecting errors that escape callbacks.
7
+ */
8
+ async function collectEscaped(run) {
9
+ const events = ['uncaughtException', 'unhandledRejection'];
10
+ const saved = events.map(event => [event, process.rawListeners(event)]);
11
+ const escaped = [];
12
+ const collect = (error) => escaped.push(error);
13
+ for (const event of events) {
14
+ process.removeAllListeners(event);
15
+ process.on(event, collect);
16
+ }
17
+ try {
18
+ run();
19
+ await new Promise(resolve => setTimeout(resolve, 50));
20
+ }
21
+ finally {
22
+ for (const [event, listeners] of saved) {
23
+ process.removeAllListeners(event);
24
+ for (const listener of listeners)
25
+ process.on(event, listener);
26
+ }
27
+ }
28
+ return escaped;
29
+ }
30
+ suite('Callbacks', config('async'), () => {
31
+ test('a callback that throws is only called once', async () => {
32
+ let calls = 0;
33
+ const thrown = new Error('thrown by callback');
34
+ const escaped = await collectEscaped(() => fs.stat('/', () => {
35
+ calls++;
36
+ throw thrown;
37
+ }));
38
+ assert.equal(calls, 1);
39
+ assert.deepEqual(escaped, [thrown]);
40
+ });
41
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,186 @@
1
+ // SPDX-License-Identifier: LGPL-3.0-or-later
2
+ import assert from 'node:assert/strict';
3
+ import { suite, test } from 'node:test';
4
+ import { config, fs } from '../common.js';
5
+ /** Creates an empty directory for a test, replacing any previous one */
6
+ function fresh(name) {
7
+ const path = '/cp-' + name;
8
+ fs.rmSync(path, { recursive: true, force: true });
9
+ fs.mkdirSync(path);
10
+ return path;
11
+ }
12
+ suite('cp', () => {
13
+ test('errorOnExist throws for an existing directory when force is false', config('sync'), async () => {
14
+ const root = fresh('error-on-exist');
15
+ fs.mkdirSync(root + '/source');
16
+ fs.mkdirSync(root + '/destination');
17
+ const options = { recursive: true, errorOnExist: true, force: false };
18
+ assert.throws(() => fs.cpSync(root + '/source', root + '/destination', options), { code: /EEXIST/ });
19
+ await assert.rejects(fs.promises.cp(root + '/source', root + '/destination', options), { code: /EEXIST/ });
20
+ });
21
+ test('errorOnExist is ignored when force is true', config('sync'), async () => {
22
+ const root = fresh('error-on-exist-force');
23
+ fs.mkdirSync(root + '/source');
24
+ fs.writeFileSync(root + '/source/file', 'new');
25
+ fs.mkdirSync(root + '/destination');
26
+ fs.writeFileSync(root + '/destination/file', 'old');
27
+ fs.cpSync(root + '/source', root + '/destination', { recursive: true, errorOnExist: true });
28
+ assert.equal(fs.readFileSync(root + '/destination/file', 'utf8'), 'new');
29
+ fs.writeFileSync(root + '/destination/file', 'old');
30
+ await fs.promises.cp(root + '/source', root + '/destination', { recursive: true, errorOnExist: true, force: true });
31
+ assert.equal(fs.readFileSync(root + '/destination/file', 'utf8'), 'new');
32
+ });
33
+ test('filter applies to the source itself', config('sync'), async () => {
34
+ const root = fresh('filter-root');
35
+ fs.mkdirSync(root + '/source');
36
+ fs.writeFileSync(root + '/source/file', '');
37
+ fs.cpSync(root + '/source', root + '/sync', { recursive: true, filter: () => false });
38
+ assert(!fs.existsSync(root + '/sync'));
39
+ await fs.promises.cp(root + '/source', root + '/async', { recursive: true, filter: () => false });
40
+ assert(!fs.existsSync(root + '/async'));
41
+ });
42
+ test('filter is called once per entry', config('sync'), () => {
43
+ const root = fresh('filter-calls');
44
+ fs.mkdirSync(root + '/source/nested', { recursive: true });
45
+ fs.writeFileSync(root + '/source/nested/file', '');
46
+ const sources = [];
47
+ fs.cpSync(root + '/source', root + '/destination', {
48
+ recursive: true,
49
+ filter: source => (sources.push(source), true),
50
+ });
51
+ assert.deepEqual(sources.map(source => source.slice(source.indexOf(root))), [root + '/source', root + '/source/nested', root + '/source/nested/file']);
52
+ });
53
+ test('cp awaits asynchronous filters', config('sync'), async () => {
54
+ const root = fresh('filter-async');
55
+ fs.mkdirSync(root + '/source');
56
+ fs.writeFileSync(root + '/source/kept', '');
57
+ fs.writeFileSync(root + '/source/skipped', '');
58
+ await fs.promises.cp(root + '/source', root + '/destination', {
59
+ recursive: true,
60
+ filter: async (source) => !source.endsWith('skipped'),
61
+ });
62
+ assert.deepEqual(fs.readdirSync(root + '/destination'), ['kept']);
63
+ });
64
+ test('cpSync rejects asynchronous filters', config('sync'), () => {
65
+ const root = fresh('filter-async-sync');
66
+ fs.mkdirSync(root + '/source');
67
+ assert.throws(() => fs.cpSync(root + '/source', root + '/destination', { recursive: true, filter: (async () => true) }), {
68
+ code: 'ERR_INVALID_RETURN_VALUE',
69
+ });
70
+ });
71
+ test('created directories get the source directory mode', config('sync', 'permissions'), async () => {
72
+ const root = fresh('directory-mode');
73
+ fs.mkdirSync(root + '/source/nested', { recursive: true, mode: 0o750 });
74
+ fs.writeFileSync(root + '/source/nested/file', '');
75
+ fs.chmodSync(root + '/source/nested', 0o550);
76
+ fs.chmodSync(root + '/source', 0o700);
77
+ fs.cpSync(root + '/source', root + '/sync', { recursive: true });
78
+ assert.equal(fs.statSync(root + '/sync').mode & 0o777, 0o700);
79
+ assert.equal(fs.statSync(root + '/sync/nested').mode & 0o777, 0o550);
80
+ assert(fs.existsSync(root + '/sync/nested/file'));
81
+ await fs.promises.cp(root + '/source', root + '/async', { recursive: true });
82
+ assert.equal(fs.statSync(root + '/async').mode & 0o777, 0o700);
83
+ assert.equal(fs.statSync(root + '/async/nested').mode & 0o777, 0o550);
84
+ assert(fs.existsSync(root + '/async/nested/file'));
85
+ for (const path of ['/source/nested', '/sync/nested', '/async/nested'])
86
+ fs.chmodSync(root + path, 0o750);
87
+ });
88
+ test('existing symlinks at the destination are replaced', config('sync', 'symlinks'), async () => {
89
+ const root = fresh('existing-symlink');
90
+ fs.mkdirSync(root + '/source');
91
+ fs.mkdirSync(root + '/sync');
92
+ fs.mkdirSync(root + '/async');
93
+ fs.writeFileSync(root + '/old', '');
94
+ fs.writeFileSync(root + '/new', '');
95
+ fs.symlinkSync(root + '/new', root + '/source/link');
96
+ fs.symlinkSync(root + '/old', root + '/sync/link');
97
+ fs.symlinkSync(root + '/old', root + '/async/link');
98
+ fs.cpSync(root + '/source', root + '/sync', { recursive: true });
99
+ assert(fs.readlinkSync(root + '/sync/link', 'utf8').endsWith('/new'));
100
+ await fs.promises.cp(root + '/source', root + '/async', { recursive: true });
101
+ assert(fs.readlinkSync(root + '/async/link', 'utf8').endsWith('/new'));
102
+ });
103
+ test('existing files are kept when force is false', config('sync'), async () => {
104
+ const root = fresh('no-force');
105
+ fs.mkdirSync(root + '/source');
106
+ fs.writeFileSync(root + '/source/existing', 'new');
107
+ fs.writeFileSync(root + '/source/added', 'added');
108
+ fs.utimesSync(root + '/source/existing', 1000, 1000);
109
+ for (const name of ['sync', 'async']) {
110
+ fs.mkdirSync(root + '/' + name);
111
+ fs.writeFileSync(root + '/' + name + '/existing', 'old');
112
+ fs.utimesSync(root + '/' + name + '/existing', 2000, 2000);
113
+ }
114
+ const options = { recursive: true, force: false, preserveTimestamps: true };
115
+ fs.cpSync(root + '/source', root + '/sync', options);
116
+ await fs.promises.cp(root + '/source', root + '/async', options);
117
+ for (const name of ['sync', 'async']) {
118
+ assert.equal(fs.readFileSync(root + '/' + name + '/existing', 'utf8'), 'old');
119
+ assert.equal(fs.statSync(root + '/' + name + '/existing').mtimeMs, 2_000_000);
120
+ assert.equal(fs.readFileSync(root + '/' + name + '/added', 'utf8'), 'added');
121
+ }
122
+ });
123
+ test('dereference copies the targets of symlinks', config('sync', 'symlinks'), async () => {
124
+ const root = fresh('dereference');
125
+ fs.mkdirSync(root + '/directory');
126
+ fs.writeFileSync(root + '/directory/file', 'content');
127
+ fs.writeFileSync(root + '/file', 'content');
128
+ fs.mkdirSync(root + '/source');
129
+ fs.symlinkSync(root + '/directory', root + '/source/directory-link');
130
+ fs.symlinkSync(root + '/file', root + '/source/file-link');
131
+ const options = { recursive: true, dereference: true };
132
+ fs.cpSync(root + '/source', root + '/sync', options);
133
+ await fs.promises.cp(root + '/source', root + '/async', options);
134
+ for (const name of ['sync', 'async']) {
135
+ assert(fs.lstatSync(`${root}/${name}/directory-link`).isDirectory());
136
+ assert.equal(fs.readFileSync(`${root}/${name}/directory-link/file`, 'utf8'), 'content');
137
+ assert(fs.lstatSync(`${root}/${name}/file-link`).isFile());
138
+ }
139
+ fs.cpSync(root + '/source/directory-link', root + '/top-level', options);
140
+ assert(fs.lstatSync(root + '/top-level').isDirectory());
141
+ });
142
+ test('existing destination files are replaced, not written through', config('sync', 'symlinks'), async () => {
143
+ const root = fresh('replace');
144
+ fs.writeFileSync(root + '/source', 'new');
145
+ fs.writeFileSync(root + '/target', 'target');
146
+ for (const name of ['sync', 'async'])
147
+ fs.symlinkSync(root + '/target', `${root}/${name}`);
148
+ const options = { mode: fs.constants.COPYFILE_EXCL };
149
+ fs.cpSync(root + '/source', root + '/sync', options);
150
+ await fs.promises.cp(root + '/source', root + '/async', options);
151
+ for (const name of ['sync', 'async']) {
152
+ assert(fs.lstatSync(`${root}/${name}`).isFile());
153
+ assert.equal(fs.readFileSync(`${root}/${name}`, 'utf8'), 'new');
154
+ }
155
+ assert.equal(fs.readFileSync(root + '/target', 'utf8'), 'target');
156
+ });
157
+ test('copying between directories and non-directories throws', config('sync'), async () => {
158
+ const root = fresh('type-mismatch');
159
+ fs.mkdirSync(root + '/directory');
160
+ fs.writeFileSync(root + '/file', '');
161
+ const toFile = { code: 'ERR_FS_CP_DIR_TO_NON_DIR' };
162
+ assert.throws(() => fs.cpSync(root + '/directory', root + '/file', { recursive: true }), toFile);
163
+ await assert.rejects(fs.promises.cp(root + '/directory', root + '/file', { recursive: true }), toFile);
164
+ const toDirectory = { code: 'ERR_FS_CP_NON_DIR_TO_DIR' };
165
+ assert.throws(() => fs.cpSync(root + '/file', root + '/directory'), toDirectory);
166
+ await assert.rejects(fs.promises.cp(root + '/file', root + '/directory'), toDirectory);
167
+ });
168
+ test('invalid copies throw Node error codes', config('sync'), async () => {
169
+ const root = fresh('errors');
170
+ fs.mkdirSync(root + '/directory');
171
+ fs.writeFileSync(root + '/file', 'contents');
172
+ fs.writeFileSync(root + '/existing', '');
173
+ const cases = [
174
+ ['same file', [root + '/file', root + '/file'], { code: 'ERR_FS_CP_EINVAL', errno: 22 }],
175
+ ['subdirectory of self', [root + '/directory', root + '/directory/sub', { recursive: true }], { code: 'ERR_FS_CP_EINVAL', errno: 22 }],
176
+ ['directory without recursive', [root + '/directory', root + '/copy'], { code: 'ERR_FS_EISDIR', errno: 21 }],
177
+ ['errorOnExist', [root + '/file', root + '/existing', { force: false, errorOnExist: true }], { code: 'ERR_FS_CP_EEXIST', errno: 17 }],
178
+ ];
179
+ for (const [name, args, expected] of cases) {
180
+ assert.throws(() => fs.cpSync(...args), { code: expected.code }, name);
181
+ await assert.rejects(fs.promises.cp(...args), { name: 'SystemError', syscall: 'cp', ...expected }, name);
182
+ }
183
+ assert.equal(fs.readFileSync(root + '/file', 'utf8'), 'contents');
184
+ assert(!fs.existsSync(root + '/directory/sub'));
185
+ });
186
+ });
@@ -60,11 +60,40 @@ suite('Dir', config('directories'), () => {
60
60
  assert(testFiles.includes(dirents[0].name));
61
61
  assert(testFiles.includes(dirents[1].name));
62
62
  });
63
+ test('recursive', async () => {
64
+ fs.mkdirSync('dir-recursive/nested', { recursive: true });
65
+ fs.writeFileSync('dir-recursive/top.txt', '');
66
+ fs.writeFileSync('dir-recursive/nested/deep.txt', '');
67
+ const expected = ['nested', 'nested/deep.txt', 'top.txt'];
68
+ const relative = (dirent) => (dirent.parentPath.endsWith('nested') ? 'nested/' : '') + dirent.name;
69
+ const dir = fs.opendirSync('dir-recursive', { recursive: true });
70
+ const names = [];
71
+ for (let dirent; (dirent = dir.readSync());)
72
+ names.push(relative(dirent));
73
+ dir.closeSync();
74
+ assert.deepEqual(names.sort(), expected);
75
+ const asyncNames = [];
76
+ for await (const dirent of await fs.promises.opendir('dir-recursive', { recursive: true, bufferSize: 1 }))
77
+ asyncNames.push(relative(dirent));
78
+ assert.deepEqual(asyncNames.sort(), expected);
79
+ });
63
80
  test('read after directory is closed', config('async'), async () => {
64
81
  const dir = fs.opendirSync(testDirPath);
65
82
  await dir.close();
66
83
  await assert.rejects(dir.read());
67
84
  });
85
+ test('read with a callback', config('async'), async () => {
86
+ const dir = fs.opendirSync(testDirPath);
87
+ const { promise, resolve, reject } = Promise.withResolvers();
88
+ dir.read((error, dirent) => (error ? reject(error) : resolve(dirent)));
89
+ assert(testFiles.includes((await promise).name));
90
+ await dir.close();
91
+ });
92
+ test('read with a callback after directory is closed', config('async'), async () => {
93
+ const dir = fs.opendirSync(testDirPath);
94
+ await dir.close();
95
+ assert.throws(() => dir.read(() => { }), { code: 'ERR_DIR_CLOSED' });
96
+ });
68
97
  test('readSync after directory is closed', config('sync'), () => {
69
98
  const dir = fs.opendirSync(testDirPath);
70
99
  dir.closeSync();
@@ -75,6 +104,17 @@ suite('Dir', config('directories'), () => {
75
104
  await dir.close();
76
105
  await assert.rejects(dir.close(), { code: 'ERR_DIR_CLOSED' });
77
106
  });
107
+ test('close with a callback multiple times', config('async'), async () => {
108
+ const dir = fs.opendirSync(testDirPath);
109
+ dir.closeSync();
110
+ let isSync = true;
111
+ const { promise, resolve } = Promise.withResolvers();
112
+ dir.close(error => resolve([error, isSync]));
113
+ isSync = false;
114
+ const [error, calledSynchronously] = await promise;
115
+ assert.equal(error?.code, 'ERR_DIR_CLOSED');
116
+ assert(!calledSynchronously);
117
+ });
78
118
  test('closeSync multiple times', config('sync'), () => {
79
119
  const dir = fs.opendirSync(testDirPath);
80
120
  dir.closeSync();
@@ -57,6 +57,13 @@ suite('Directories', config('directories'), () => {
57
57
  assert.throws(() => fs.mkdirSync('/recursiveSF', { recursive: true }), { code: 'EEXIST', path: '/recursiveSF' });
58
58
  assert.throws(() => fs.mkdirSync('/recursiveSF/A/B', { recursive: true }), { code: 'ENOTDIR', path: '/recursiveSF/A/B' });
59
59
  });
60
+ test('rmdir with options and a callback', config('async'), async () => {
61
+ await fs.promises.mkdir('/rmdir-callback');
62
+ const { promise, resolve } = Promise.withResolvers();
63
+ fs.rmdir('/rmdir-callback', {}, resolve);
64
+ assert.equal(await promise, null);
65
+ assert(!fs.existsSync('/rmdir-callback'));
66
+ });
60
67
  test('rmdir (non-empty)', config('async'), async () => {
61
68
  await fs.promises.mkdir('/rmdirTest');
62
69
  await fs.promises.mkdir('/rmdirTest/rmdirTest2');
@@ -80,6 +87,28 @@ suite('Directories', config('directories'), () => {
80
87
  await fs.promises.writeFile('/rmDirRecursively/rmDirNested/test.txt', 'hello world!');
81
88
  await fs.promises.rm('/rmDirRecursively', { recursive: true });
82
89
  });
90
+ test('rm on a directory without recursive', async () => {
91
+ const path = '/rm-directory';
92
+ fs.mkdirSync(path);
93
+ const expected = {
94
+ name: 'SystemError',
95
+ code: 'ERR_FS_EISDIR',
96
+ errno: 21,
97
+ syscall: 'rm',
98
+ path,
99
+ message: `Path is a directory: rm returned EISDIR (is a directory) ${path}`,
100
+ };
101
+ assert.throws(() => fs.rmSync(path), expected);
102
+ assert.throws(() => fs.rmSync(path, { force: true }), expected);
103
+ await assert.rejects(fs.promises.rm(path), expected);
104
+ const { promise, resolve } = Promise.withResolvers();
105
+ fs.rm(path, resolve);
106
+ const error = await promise;
107
+ assert.throws(() => {
108
+ throw error;
109
+ }, expected);
110
+ assert(fs.statSync(path).isDirectory());
111
+ });
83
112
  test('rmSync recursively', config('sync'), () => {
84
113
  fs.mkdirSync('/rmDirRecursively');
85
114
  fs.mkdirSync('/rmDirRecursively/rmDirNested');
@@ -133,6 +162,19 @@ suite('Directories', config('directories'), () => {
133
162
  assert.deepEqual(values[4], ['/' + testDir + '/subdir1', 'file4.txt']);
134
163
  assert.deepEqual(values[8], ['/' + testDir + '/subdir2', 'file5.txt']);
135
164
  });
165
+ test('readdir is not affected by mutating options after the call', config('async'), async () => {
166
+ const options = { recursive: true, withFileTypes: false };
167
+ const promise = fs.promises.readdir(testDir, options);
168
+ options.recursive = false;
169
+ options.withFileTypes = true;
170
+ const entries = await promise;
171
+ assert(entries.includes('subdir1/file4.txt'));
172
+ assert(entries.every(entry => typeof entry == 'string'));
173
+ });
174
+ test('Dirent does not have path', config('sync'), () => {
175
+ const [entry] = fs.readdirSync(testDir, { withFileTypes: true });
176
+ assert(!('path' in entry));
177
+ });
136
178
  test('readdirSync returns files recursively', config('sync'), () => {
137
179
  const entries = fs.readdirSync(testDir, { recursive: true }).sort();
138
180
  assert.equal(entries[0], 'file1.txt');