Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stat + statSync fix when thowIfNoEntry:false #780

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,19 +64,20 @@
"fs-monkey": "^1.0.0"
},
"devDependencies": {
"@jest/globals": "^29.7.0",
"@semantic-release/changelog": "^6.0.1",
"@semantic-release/git": "^10.0.1",
"@semantic-release/npm": "^9.0.1",
"@types/jest": "^29.0.0",
"@types/node": "^11.15.54",
"@types/node": "^15.3.0",
"jest": "^29.0.0",
"memfs": "^4.0.0",
"memory-fs": "^0.5.0",
"prettier": "^3.0.0",
"semantic-release": "^19.0.3",
"source-map-support": "^0.5.21",
"ts-jest": "^29.0.0",
"ts-node": "^10.8.1",
"typescript": "^5.0.0"
"ts-node": "^10.9.2",
"typescript": "^5.3.3"
}
}
75 changes: 75 additions & 0 deletions src/__tests__/union.test.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,90 @@
import { describe, expect, it } from '@jest/globals';
import { Union } from '..';
import { Volume, createFsFromVolume } from 'memfs';
import * as fs from 'fs';


function sleep(millisec: number): Promise<void> {
return new Promise<void>((resolve, reject) => {
setTimeout(resolve, millisec);
});
}


// fs.statSync(path[, options])#
// History
// path <string> | <Buffer> | <URL>
// options <Object>
// bigint <boolean> Whether the numeric values in the returned <fs.Stats> object should be bigint. Default: false.
// throwIfNoEntry <boolean> Whether an exception will be thrown if no file system entry exists, rather than returning undefined. Default: true.
// Returns: <fs.Stats>
// Retrieves the <fs.Stats> for the path.
describe('union', () => {
describe('Union', () => {
describe('special handling of stat*', () => {

it('statSync when file is missing', () => {
const vol = Volume.fromJSON({});

const ufs = new Union();
ufs.use(vol as any);

expect(() => ufs.statSync('/does-not-exist.file')).toThrow();
expect(() => ufs.statSync('/does-not-exist.file', undefined)).toThrow();
expect(() => ufs.statSync('/does-not-exist.file', { throwIfNoEntry: true })).toThrow();
expect(ufs.statSync('/does-not-exist.file', { throwIfNoEntry: false })).toBe(undefined);
});

it('statSync with unioned fs - throwIfNoEntry', () => {
const vol_layer0 = Volume.fromJSON({ "/exists.in.layer0.file": "contents" });
const vol_layer1 = Volume.fromJSON({ "/exists.in.layer1.file": "contents" });

const ufs = new Union();
ufs.use(vol_layer0 as any);
ufs.use(vol_layer1 as any);

expect(ufs.statSync('/exists.in.layer0.file', { throwIfNoEntry: false })).not.toBeUndefined()
expect(ufs.statSync('/exists.in.layer1.file', { throwIfNoEntry: false })).not.toBeUndefined()
expect(ufs.statSync('/does-not-exist.file', { throwIfNoEntry: false })).toBeUndefined()

expect(() => ufs.statSync('/does-not-exist.file')).toThrow();
expect(() => ufs.statSync('/does-not-exist.file', undefined)).toThrow();
expect(() => ufs.statSync('/does-not-exist.file', { throwIfNoEntry: true })).toThrow();
});


it('stat with unioned fs - throwIfNoEntry', async () => {
const vol_layer0 = Volume.fromJSON({ "/exists.in.layer0.file": "contents" });
const vol_layer1 = Volume.fromJSON({ "/exists.in.layer1.file": "contents" });

const ufs = new Union();
ufs.use(vol_layer0 as any);
ufs.use(vol_layer1 as any);

await (new Promise((resolve) => {
ufs.stat('/exists.in.layer0.file', { throwIfNoEntry: false }, (err, stats) => {
expect(err).toBeNull();
expect(stats).not.toBeUndefined();
resolve(null);
});
}));
await (new Promise((resolve) => {
ufs.stat('/exists.in.layer1.file', { throwIfNoEntry: false }, (err, stats) => {
expect(err).toBeNull();
expect(stats).not.toBeUndefined();
resolve(null);
});
}));
await (new Promise((resolve) => {
ufs.stat('/does-not-exist.file', { throwIfNoEntry: false }, (err, stats) => {
expect(err).toBeNull();
expect(stats).toBeUndefined();
resolve(null);
});
}));
});
})

describe('sync methods', () => {
it('Basic one file system', () => {
const vol = Volume.fromJSON({ '/foo': 'bar' });
Expand Down
6 changes: 4 additions & 2 deletions src/fs.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Writable, Readable } from 'stream';
import * as fs from 'fs';
import type { Writable, Readable } from 'stream';
import type * as fs from 'fs';

type FSMethods =
| 'renameSync'
Expand Down Expand Up @@ -78,3 +78,5 @@ export interface IFS extends FS {
WriteStream: typeof Writable | (new (...args: any[]) => Writable);
ReadStream: typeof Readable | (new (...args: any[]) => Readable);
}

export type StatOptions = fs.StatOptions;
48 changes: 42 additions & 6 deletions src/union.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { FSWatcher, Dirent } from 'fs';
import { IFS } from './fs';
import type { FSWatcher, Dirent, StatOptions, Stats } from 'fs';
import type { IFS } from './fs';
import { Readable, Writable } from 'stream';
const { fsAsyncMethods, fsSyncMethods } = require('fs-monkey/lib/util/lists');

Expand All @@ -18,6 +18,8 @@ const SPECIAL_METHODS = new Set([
'watch',
'watchFile',
'unwatchFile',
'statSync',
'stat',
]);

const createFSProxy = (watchers: FSWatcher[]) =>
Expand Down Expand Up @@ -76,6 +78,9 @@ const fsPromisesMethods = [
'readFile',
] as const;


type DiscardResult = (idx: number, result: any) => any;

/**
* Union object represents a stack of filesystems
*/
Expand Down Expand Up @@ -153,6 +158,27 @@ export class Union {
}
};

public stat(path: string, options: StatOptions | undefined, cb) {
const discardResult: DiscardResult = (idx: number, result: [any, Stats]) => {
return idx && result[1] === undefined && options?.throwIfNoEntry === false;
}

if (typeof options === 'function') {
cb = options;
options = undefined;
}

return this.asyncMethod("stat", [path, options, cb], discardResult);
}

public statSync = (path: string, options: StatOptions) => {
const discardResult: DiscardResult = (idx: number, result: Stats) => {
return idx && result === undefined && options?.throwIfNoEntry === false;
}

return this.syncMethod("statSync", [path, options], discardResult);
}

public existsSync = (path: string) => {
for (const fs of this.fss) {
try {
Expand Down Expand Up @@ -348,13 +374,17 @@ export class Union {
return this;
}

private syncMethod(method: string, args: any[]) {
private syncMethod(method: string, args: any[], discardResult?: DiscardResult) {
let lastError: IUnionFsError | null = null;
for (let i = this.fss.length - 1; i >= 0; i--) {
const fs = this.fss[i];
try {
if (!fs[method]) throw Error(`Method not supported: "${method}" with args "${args}"`);
return fs[method].apply(fs, args);
const result = fs[method].apply(fs, args);
if (discardResult && i && discardResult(i, result)) {
continue;
}
return result
} catch (err) {
err.prev = lastError;
lastError = err;
Expand All @@ -369,7 +399,7 @@ export class Union {
}
}

private asyncMethod(method: string, args: any[]) {
private asyncMethod(method: string, args: any[], discardResult?: DiscardResult) {
let lastarg = args.length - 1;
let cb = args[lastarg];
if (typeof cb !== 'function') {
Expand All @@ -394,7 +424,12 @@ export class Union {
// Replace `callback` with our intermediate function.
args[lastarg] = function (err) {
if (err) return iterate(i + 1, err);
if (cb) cb.apply(cb, arguments);
if (cb) {
if (discardResult && j && discardResult(j, arguments)) {
return iterate(i + 1, err);
}
cb.apply(cb, arguments);
}
};

const j = this.fss.length - i - 1;
Expand All @@ -404,6 +439,7 @@ export class Union {
if (!func) iterate(i + 1, Error('Method not supported: ' + method));
else func.apply(fs, args);
};

iterate();
}

Expand Down
19 changes: 14 additions & 5 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,18 +1,27 @@
{
"compilerOptions": {
"target": "es5",
"lib": ["es2015"],
"lib": [
"es2015"
],
"outDir": "lib",
"module": "commonjs",
"removeComments": false,
"noImplicitAny": false,
"sourceMap": false,
"sourceMap": true,
"strictNullChecks": true,
"strictBindCallApply": true,
"strictPropertyInitialization": true,
"downlevelIteration": true,
"declaration": true
},
"include": ["src"],
"exclude": ["src/__tests__", "node_modules", "demo", "lib"]
}
"include": [
"src"
],
"exclude": [
"src/__tests__",
"node_modules",
"demo",
"lib"
]
}
Loading