Skip to content

Commit

Permalink
Fix glob for nested directories (#80)
Browse files Browse the repository at this point in the history
  • Loading branch information
medusalix authored and sindresorhus committed Apr 1, 2019
1 parent 08723b1 commit 78e705c
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 12 deletions.
28 changes: 16 additions & 12 deletions index.js
Expand Up @@ -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');
Expand All @@ -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;
Expand Down
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -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",
Expand Down
28 changes: 28 additions & 0 deletions test.js
Expand Up @@ -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));
});

0 comments on commit 78e705c

Please sign in to comment.