From 78e705cfe46357229f89951a731b8a9bc4c021ed Mon Sep 17 00:00:00 2001 From: Medusalix <8124898+medusalix@users.noreply.github.com> Date: Mon, 1 Apr 2019 10:43:06 +0200 Subject: [PATCH] Fix glob for nested directories (#80) --- index.js | 28 ++++++++++++++++------------ package.json | 1 + test.js | 28 ++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 12 deletions(-) diff --git a/index.js b/index.js index 7a26349..2d6d12f 100644 --- a/index.js +++ b/index.js @@ -3,6 +3,7 @@ const fs = require('fs'); const path = require('path'); const globby = require('globby'); const pTry = require('p-try'); +const isPathInside = require('is-path-inside'); const macos = require('./lib/macos'); const linux = require('./lib/linux'); const windows = require('./lib/windows'); @@ -24,19 +25,22 @@ const trash = (paths, options) => pTry(() => { }); } - paths = paths - .map(filePath => path.resolve(filePath)) - .filter(filePath => { - try { - return fs.lstatSync(filePath); - } catch (error) { - if (error.code === 'ENOENT') { - return false; - } - - throw error; + paths = paths.map(filePath => path.resolve(filePath)); + paths = paths.filter(filePath => { + if (paths.some(otherPath => isPathInside(filePath, otherPath))) { + return false; + } + + try { + return fs.lstatSync(filePath); + } catch (error) { + if (error.code === 'ENOENT') { + return false; } - }); + + throw error; + } + }); if (paths.length === 0) { return; diff --git a/package.json b/package.json index 44007da..3cf75b6 100644 --- a/package.json +++ b/package.json @@ -42,6 +42,7 @@ "dependencies": { "escape-string-applescript": "^2.0.0", "globby": "^7.1.1", + "is-path-inside": "^2.0.0", "make-dir": "^1.3.0", "move-file": "^1.1.0", "p-map": "^2.0.0", diff --git a/test.js b/test.js index 48364e3..0e781ac 100644 --- a/test.js +++ b/test.js @@ -169,3 +169,31 @@ test('non-existent files', async t => { t.false(fs.existsSync('fixture-enoent')); await t.notThrowsAsync(trash('fixture-enoent')); }); + +test('glob with nested directories', async t => { + const dir1 = 'foo'; + const file1 = path.join('foo', 'bar.txt'); + const file2 = path.join('foo', 'baz.txt'); + const dir2 = path.join('foo', 'bar'); + const dir3 = path.join('foo', 'baz'); + const file3 = path.join(dir1, 'foo.txt'); + const file4 = path.join(dir2, 'bar.txt'); + + fs.mkdirSync(dir1); + fs.mkdirSync(dir2); + fs.mkdirSync(dir3); + fs.writeFileSync(file1, ''); + fs.writeFileSync(file2, ''); + fs.writeFileSync(file3, ''); + fs.writeFileSync(file4, ''); + t.true(fs.existsSync(file1)); + t.true(fs.existsSync(file2)); + t.true(fs.existsSync(file3)); + t.true(fs.existsSync(file4)); + + await trash(`${dir1}/**`, {glob: true}); + + t.false(fs.existsSync(dir1)); + t.false(fs.existsSync(dir2)); + t.false(fs.existsSync(dir3)); +});