forked from sindresorhus/del
/
index.js
84 lines (64 loc) · 1.81 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
'use strict';
const {promisify} = require('util');
const path = require('path');
const globby = require('globby');
const isPathCwd = require('is-path-cwd');
const isPathInside = require('is-path-inside');
const rimraf = require('rimraf');
const pMap = require('p-map');
const rimrafP = promisify(rimraf);
function safeCheck(file, cwd) {
if (isPathCwd(file)) {
throw new Error('Cannot delete the current working directory. Can be overridden with the `force` option.');
}
if (!isPathInside(file, cwd)) {
throw new Error('Cannot delete files/directories outside the current working directory. Can be overridden with the `force` option.');
}
}
module.exports = async (patterns, {force, dryRun, cwd = process.cwd(), ...options} = {}) => {
options = {
expandDirectories: false,
onlyFiles: false,
followSymbolicLinks: false,
cwd,
...options
};
const files = (await globby(patterns, options))
.sort((a, b) => b.localeCompare(a));
const mapper = async file => {
file = path.resolve(cwd, file);
if (!force) {
safeCheck(file, cwd);
}
if (!dryRun) {
await rimrafP(file, {glob: false});
}
return file;
};
const removedFiles = await pMap(files, mapper, options);
removedFiles.sort((a, b) => a.localeCompare(b));
return removedFiles;
};
module.exports.sync = (patterns, {force, dryRun, cwd = process.cwd(), ...options} = {}) => {
options = {
expandDirectories: false,
onlyFiles: false,
followSymbolicLinks: false,
cwd,
...options
};
const files = globby.sync(patterns, options)
.sort((a, b) => b.localeCompare(a));
const removedFiles = files.map(file => {
file = path.resolve(cwd, file);
if (!force) {
safeCheck(file, cwd);
}
if (!dryRun) {
rimraf.sync(file, {glob: false});
}
return file;
});
removedFiles.sort((a, b) => a.localeCompare(b));
return removedFiles;
};