UNPKG

2.7 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.del = void 0;
4const js_lib_1 = require("@naturalcycles/js-lib");
5const fs = require("fs-extra");
6const colors_1 = require("../colors");
7const index_1 = require("../index");
8const DEF_OPT = {
9 patterns: [],
10 concurrency: Number.POSITIVE_INFINITY,
11};
12/**
13 * Delete files that match input patterns.
14 *
15 * @experimental
16 */
17async function del(_opt) {
18 const started = Date.now();
19 // Convert DelSingleOption to DelOptions
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 // 1. glob only files, expand dirs, delete
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 // 2. glob only dirs, expand, delete only empty!
47 let dirnames = await (0, index_1.globby)(patterns, {
48 dot: true,
49 expandDirectories: true,
50 onlyDirectories: true,
51 });
52 // Add original patterns (if any of them are dirs)
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 // console.log({ dirnamesSorted })
58 const deletedDirs = [];
59 for await (const dirpath of dirnamesSorted) {
60 if (await isEmptyDir(dirpath)) {
61 // console.log(`empty dir: ${dirpath}`)
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}
72exports.del = del;
73// Improved algorithm:
74// 1. glob only files, expand dirs, delete
75// 2. glob only dirs, expand, delete only empty!
76// 3. test each original pattern, if it exists and is directory and is empty - delete
77async function isEmptyDir(dir) {
78 return (await fs.readdir(dir)).length === 0;
79}