1 | 'use strict';
|
---|
2 | const path = require('path');
|
---|
3 | const globby = require('globby');
|
---|
4 | const isPathCwd = require('is-path-cwd');
|
---|
5 | const isPathInCwd = require('is-path-in-cwd');
|
---|
6 | const pify = require('pify');
|
---|
7 | const rimraf = require('rimraf');
|
---|
8 | const pMap = require('p-map');
|
---|
9 |
|
---|
10 | const rimrafP = pify(rimraf);
|
---|
11 |
|
---|
12 | function safeCheck(file) {
|
---|
13 | if (isPathCwd(file)) {
|
---|
14 | throw new Error('Cannot delete the current working directory. Can be overridden with the `force` option.');
|
---|
15 | }
|
---|
16 |
|
---|
17 | if (!isPathInCwd(file)) {
|
---|
18 | throw new Error('Cannot delete files/folders outside the current working directory. Can be overridden with the `force` option.');
|
---|
19 | }
|
---|
20 | }
|
---|
21 |
|
---|
22 | const del = (patterns, options) => {
|
---|
23 | options = Object.assign({}, options);
|
---|
24 |
|
---|
25 | const {force, dryRun} = options;
|
---|
26 | delete options.force;
|
---|
27 | delete options.dryRun;
|
---|
28 |
|
---|
29 | const mapper = file => {
|
---|
30 | if (!force) {
|
---|
31 | safeCheck(file);
|
---|
32 | }
|
---|
33 |
|
---|
34 | file = path.resolve(options.cwd || '', file);
|
---|
35 |
|
---|
36 | if (dryRun) {
|
---|
37 | return file;
|
---|
38 | }
|
---|
39 |
|
---|
40 | return rimrafP(file, {glob: false}).then(() => file);
|
---|
41 | };
|
---|
42 |
|
---|
43 | return globby(patterns, options).then(files => pMap(files, mapper, options));
|
---|
44 | };
|
---|
45 |
|
---|
46 | module.exports = del;
|
---|
47 | // TODO: Remove this for the next major release
|
---|
48 | module.exports.default = del;
|
---|
49 |
|
---|
50 | module.exports.sync = (patterns, options) => {
|
---|
51 | options = Object.assign({}, options);
|
---|
52 |
|
---|
53 | const {force, dryRun} = options;
|
---|
54 | delete options.force;
|
---|
55 | delete options.dryRun;
|
---|
56 |
|
---|
57 | return globby.sync(patterns, options).map(file => {
|
---|
58 | if (!force) {
|
---|
59 | safeCheck(file);
|
---|
60 | }
|
---|
61 |
|
---|
62 | file = path.resolve(options.cwd || '', file);
|
---|
63 |
|
---|
64 | if (!dryRun) {
|
---|
65 | rimraf.sync(file, {glob: false});
|
---|
66 | }
|
---|
67 |
|
---|
68 | return file;
|
---|
69 | });
|
---|
70 | };
|
---|