1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.del = void 0;
|
4 | const js_lib_1 = require("@naturalcycles/js-lib");
|
5 | const fs = require("fs-extra");
|
6 | const colors_1 = require("../colors");
|
7 | const index_1 = require("../index");
|
8 | const DEF_OPT = {
|
9 | patterns: [],
|
10 | concurrency: Number.POSITIVE_INFINITY,
|
11 | };
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | async function del(_opt) {
|
18 | const started = Date.now();
|
19 |
|
20 | if (typeof _opt === 'string') {
|
21 | _opt = {
|
22 | patterns: [_opt],
|
23 | };
|
24 | }
|
25 | const opt = {
|
26 | ...DEF_OPT,
|
27 | ..._opt,
|
28 | concurrency: _opt.concurrency || DEF_OPT.concurrency,
|
29 | };
|
30 | const { patterns, concurrency, verbose, silent, debug, dry } = opt;
|
31 | if (debug) {
|
32 | console.log(opt);
|
33 | }
|
34 |
|
35 | const filenames = await (0, index_1.globby)(patterns, {
|
36 | dot: true,
|
37 | expandDirectories: true,
|
38 | onlyFiles: true,
|
39 | });
|
40 | if (verbose || debug || dry) {
|
41 | console.log(`Will delete ${(0, colors_1.yellow)(filenames.length)} files:`, filenames);
|
42 | }
|
43 | if (dry)
|
44 | return;
|
45 | await (0, js_lib_1.pMap)(filenames, filepath => fs.remove(filepath), { concurrency });
|
46 |
|
47 | let dirnames = await (0, index_1.globby)(patterns, {
|
48 | dot: true,
|
49 | expandDirectories: true,
|
50 | onlyDirectories: true,
|
51 | });
|
52 |
|
53 | dirnames = dirnames.concat(await (0, js_lib_1.pFilter)(patterns, async (pattern) => {
|
54 | return (await fs.pathExists(pattern)) && (await fs.lstat(pattern)).isDirectory();
|
55 | }));
|
56 | const dirnamesSorted = dirnames.sort().reverse();
|
57 |
|
58 | const deletedDirs = [];
|
59 | for await (const dirpath of dirnamesSorted) {
|
60 | if (await isEmptyDir(dirpath)) {
|
61 |
|
62 | await fs.remove(dirpath);
|
63 | deletedDirs.push(dirpath);
|
64 | }
|
65 | }
|
66 | if (verbose || debug)
|
67 | console.log({ deletedDirs });
|
68 | if (!silent) {
|
69 | console.log(`del deleted ${(0, colors_1.yellow)(filenames.length)} files and ${(0, colors_1.yellow)(deletedDirs.length)} dirs ${(0, colors_1.dimGrey)((0, js_lib_1._since)(started))}`);
|
70 | }
|
71 | }
|
72 | exports.del = del;
|
73 |
|
74 |
|
75 |
|
76 |
|
77 | async function isEmptyDir(dir) {
|
78 | return (await fs.readdir(dir)).length === 0;
|
79 | }
|