Skip to content

Commit

Permalink
fix(rmdir): support recursive option
Browse files Browse the repository at this point in the history
  • Loading branch information
imsnif committed Dec 24, 2019
1 parent e8b9758 commit 1e943ae
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
6 changes: 6 additions & 0 deletions src/__tests__/volume.test.ts
Expand Up @@ -954,6 +954,12 @@ describe('volume', () => {
vol.rmdirSync('/dir');
expect(!!vol.root.getChild('dir')).toBe(false);
});
it('Remove dir /dir1/dir2/dir3 recursively', () => {
const vol = new Volume();
vol.mkdirSync('/dir1/dir2/dir3', { recursive: true });
vol.rmdirSync('/dir1', { recursive: true });
expect(!!vol.root.getChild('/dir1')).toBe(false);
});
});
describe('.rmdir(path, callback)', () => {
xit('Remove single dir', () => {});
Expand Down
26 changes: 21 additions & 5 deletions src/volume.ts
Expand Up @@ -342,6 +342,17 @@ const getMkdirOptions = (options): IMkdirOptions => {
return extend({}, mkdirDefaults, options);
};

// Options for `fs.rmdir` and `fs.rmdirSync`
export interface IRmdirOptions {
recursive?: boolean;
}
const rmdirDefaults: IRmdirOptions = {
recursive: false,
};
const getRmdirOptions = (options): IRmdirOptions => {
return extend({}, rmdirDefaults, options);
};

// Options for `fs.readdir` and `fs.readdirSync`
export interface IReaddirOptions extends IOptions {
withFileTypes?: boolean;
Expand Down Expand Up @@ -1901,20 +1912,25 @@ export class Volume {
this.wrapAsync(this.mkdtempBase, [prefix, encoding], callback);
}

private rmdirBase(filename: string) {
private rmdirBase(filename: string, options?: IRmdirOptions) {
const opts = getRmdirOptions(options);
const link = this.getLinkAsDirOrThrow(filename, 'rmdir');

// Check directory is empty.
if (link.length) throw createError(ENOTEMPTY, 'rmdir', filename);
if (link.length && !opts.recursive) throw createError(ENOTEMPTY, 'rmdir', filename);

this.deleteLink(link);
}

rmdirSync(path: TFilePath) {
this.rmdirBase(pathToFilename(path));
rmdirSync(path: TFilePath, options?: IRmdirOptions) {
this.rmdirBase(pathToFilename(path), options);
}

rmdir(path: TFilePath, callback: TCallback<void>) {
rmdir(path: TFilePath, callback: TCallback<void>);
rmdir(path: TFilePath, options: IRmdirOptions, callback: TCallback<void>);
rmdir(path: TFilePath, a: TCallback<void> | IRmdirOptions, b?: TCallback<void>) {
const opts: IRmdirOptions = getRmdirOptions(a);
const callback: TCallback<void> = validateCallback(typeof a === 'function' ? a : b);
this.wrapAsync(this.rmdirBase, [pathToFilename(path)], callback);
}

Expand Down

0 comments on commit 1e943ae

Please sign in to comment.