Skip to content

Commit 78e705c

Browse files
medusalixsindresorhus
authored andcommittedApr 1, 2019
Fix glob for nested directories (#80)
1 parent 08723b1 commit 78e705c

File tree

3 files changed

+45
-12
lines changed

3 files changed

+45
-12
lines changed
 

‎index.js

+16-12
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ const fs = require('fs');
33
const path = require('path');
44
const globby = require('globby');
55
const pTry = require('p-try');
6+
const isPathInside = require('is-path-inside');
67
const macos = require('./lib/macos');
78
const linux = require('./lib/linux');
89
const windows = require('./lib/windows');
@@ -24,19 +25,22 @@ const trash = (paths, options) => pTry(() => {
2425
});
2526
}
2627

27-
paths = paths
28-
.map(filePath => path.resolve(filePath))
29-
.filter(filePath => {
30-
try {
31-
return fs.lstatSync(filePath);
32-
} catch (error) {
33-
if (error.code === 'ENOENT') {
34-
return false;
35-
}
36-
37-
throw error;
28+
paths = paths.map(filePath => path.resolve(filePath));
29+
paths = paths.filter(filePath => {
30+
if (paths.some(otherPath => isPathInside(filePath, otherPath))) {
31+
return false;
32+
}
33+
34+
try {
35+
return fs.lstatSync(filePath);
36+
} catch (error) {
37+
if (error.code === 'ENOENT') {
38+
return false;
3839
}
39-
});
40+
41+
throw error;
42+
}
43+
});
4044

4145
if (paths.length === 0) {
4246
return;

‎package.json

+1
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
"dependencies": {
4343
"escape-string-applescript": "^2.0.0",
4444
"globby": "^7.1.1",
45+
"is-path-inside": "^2.0.0",
4546
"make-dir": "^1.3.0",
4647
"move-file": "^1.1.0",
4748
"p-map": "^2.0.0",

‎test.js

+28
Original file line numberDiff line numberDiff line change
@@ -169,3 +169,31 @@ test('non-existent files', async t => {
169169
t.false(fs.existsSync('fixture-enoent'));
170170
await t.notThrowsAsync(trash('fixture-enoent'));
171171
});
172+
173+
test('glob with nested directories', async t => {
174+
const dir1 = 'foo';
175+
const file1 = path.join('foo', 'bar.txt');
176+
const file2 = path.join('foo', 'baz.txt');
177+
const dir2 = path.join('foo', 'bar');
178+
const dir3 = path.join('foo', 'baz');
179+
const file3 = path.join(dir1, 'foo.txt');
180+
const file4 = path.join(dir2, 'bar.txt');
181+
182+
fs.mkdirSync(dir1);
183+
fs.mkdirSync(dir2);
184+
fs.mkdirSync(dir3);
185+
fs.writeFileSync(file1, '');
186+
fs.writeFileSync(file2, '');
187+
fs.writeFileSync(file3, '');
188+
fs.writeFileSync(file4, '');
189+
t.true(fs.existsSync(file1));
190+
t.true(fs.existsSync(file2));
191+
t.true(fs.existsSync(file3));
192+
t.true(fs.existsSync(file4));
193+
194+
await trash(`${dir1}/**`, {glob: true});
195+
196+
t.false(fs.existsSync(dir1));
197+
t.false(fs.existsSync(dir2));
198+
t.false(fs.existsSync(dir3));
199+
});

0 commit comments

Comments
 (0)
Please sign in to comment.