-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathmodclean.js
executable file
·285 lines (229 loc) · 9.6 KB
/
modclean.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
#!/usr/bin/env node
"use strict";
const chalk = require('chalk');
const program = require('commander');
const notifier = require('update-notifier');
const clui = require('clui');
const path = require('path');
const os = require('os');
const pkg = require('../package.json');
const utils = require('./utils');
const modclean = require('../lib/modclean');
const ModClean = modclean.ModClean;
notifier({ pkg }).notify();
function list(val) {
return val.split(',');
}
process.on('SIGINT', function() {
process.stdin.destroy();
process.exit();
});
program
.version(pkg.version)
.description('Remove unwanted files and directories from your node_modules folder')
.usage('modclean [options]')
.option('-t, --test', 'Run modclean and return results without deleting files')
.option('-p, --path <path>', 'Path to run modclean on (defaults to current directory)')
.option('-D, --modules-dir <name>', 'Modules directory name (defaults to "node_modules")')
.option('-s, --case-sensitive', 'Matches are case sensitive')
.option('-i, --interactive', 'Each deleted file/folder requires confirmation')
.option('-P, --no-progress', 'Hide progress bar')
.option('-e, --error-halt', 'Halt script on error')
.option('-v, --verbose', 'Run in verbose mode')
.option('-f, --follow-symlink', 'Clean symlinked packages as well')
.option('-r, --run', 'Run immediately without warning')
.option('-n, --patterns <list>', 'Patterns plugins/rules to use (defaults to "default:safe")', list)
.option('-a, --additional-patterns <list>', 'Additional glob patterns to search for', list)
.option('-I, --ignore <list>', 'Comma separated list of patterns to ignore', list)
.option('--no-dirs', 'Exclude directories from being removed')
.option('--no-dotfiles', 'Exclude dot files from being removed')
.option('-k, --keep-empty', 'Keep empty directories')
.parse(process.argv);
class ModClean_CLI {
constructor() {
this.log = utils.initLog(program.verbose);
// Display CLI header
console.log(
"\n" +
chalk.yellow.bold('MODCLEAN ') +
chalk.gray(' Version ' + pkg.version) + "\n"
);
// Display "running in test mode" message
if(program.test) {
console.log(
chalk.cyan.bold('RUNNING IN TEST MODE') + "\n" +
chalk.gray('When running in test mode, files will not be deleted from the file system.') + "\n"
);
}
// Display warning message and confirmation prompt
if(!program.run && !program.test) {
console.log(
chalk.red.bold('WARNING:') + "\n" +
chalk.gray(utils.warningMsg) + "\n"
);
return utils.confirm('Are you sure you want to continue?', (res) => {
if(!res) return process.exit(0);
this.start();
});
}
this.start();
}
start() {
let self = this,
platform = os.platform();
this.stats = {
current: 0,
total: 0,
skipped: [],
currentEmpty: 0,
totalEmpty: 0
};
// Disable progress bar in interactive mode
if(program.interactive) program.progress = false;
let options = {
cwd: program.path || process.cwd(),
modulesDir: program.modulesDir || 'node_modules',
patterns: program.patterns && program.patterns.length? program.patterns : ['default:safe'],
additionalPatterns: program.additionalPatterns || [],
ignorePatterns: program.ignore || [],
noDirs: !program.dirs,
dotFiles: !!program.dotfiles,
errorHalt: !!program.errorHalt,
removeEmptyDirs: !program.keepEmpty,
ignoreCase: !program.caseSensitive,
test: !!program.test,
followSymlink: !!program.followSymlink,
process: function(file, cb) {
self.stats.current += 1;
if(!program.interactive) return cb(true);
let name = path.relative(options.cwd, file);
if(platform === 'win32') name = name.replace(/\\+/g, '/');
utils.confirm(
chalk.gray(`(${self.stats.current}/${self.stats.total})`) +
`${name} ${chalk.gray(' - ')} ${chalk.yellow.bold('Delete File?')}`,
function(res) {
if(!res) self.stats.skipped.push(file);
cb(res);
});
}
};
this.modclean = new ModClean(options);
this.initEvents();
this.modclean.clean(this.done.bind(this));
}
initEvents() {
var inst = this.modclean;
let progressBar = new clui.Progress(40),
spinner = new clui.Spinner('Loading...'),
showProgress = true;
if(!process.stdout.isTTY || program.interactive || !program.progress || program.verbose) showProgress = false;
function updateProgress(current, total) {
if(showProgress) {
process.stdout.cursorTo(0);
process.stdout.write(progressBar.update(current, total));
process.stdout.clearLine(1);
}
}
function showSpinner(msg) {
if(!process.stdout.isTTY || program.verbose || !program.progress) {
console.log(msg);
} else {
spinner.message(msg);
spinner.start();
}
}
// Start Event (searching for files)
inst.on('start', () => {
this.log('event', 'start');
this.log('verbose', '\n' + JSON.stringify(inst.options, null, 4));
showSpinner(`Searching for files in ${inst.options.cwd}...`);
});
// Files Event (file list after searching complete)
inst.on('files', (files) => {
this.log('event', 'files');
if(process.stdout.isTTY) spinner.stop();
this.stats.total = files.length;
console.log(`Found ${chalk.green.bold(files.length)} files/folders to remove\n`);
});
inst.on('process', (files) => {
this.log('event', 'process');
if(!showProgress && !program.interactive && !program.verbose)
console.log('Deleting files, please wait...');
updateProgress(0, files.length);
});
// Deleted Event (called for each file deleted)
inst.on('deleted', (file) => {
updateProgress(this.stats.current, this.stats.total);
this.log(
'verbose',
`${chalk.yellow.bold('DELETED')} (${this.stats.current}/${this.stats.total}) ${chalk.gray(file)}`
);
});
inst.on('beforeEmptyDirs', () => {
this.log('event', 'beforeEmptyDirs');
showSpinner(`Searching for empty directories in ${inst.options.cwd}...`);
});
inst.on('emptyDirs', (dirs) => {
this.log('event', 'emptyDirs');
if(process.stdout.isTTY) spinner.stop();
this.stats.totalEmpty = dirs.length;
console.log(`\nFound ${chalk.green.bold(dirs.length)} empty directories to remove\n`);
if(!dirs.length) return;
if(!showProgress && !program.interactive && !program.verbose)
console.log('Deleting empty directories, please wait...');
updateProgress(0, dirs.length);
});
inst.on('deletedEmptyDir', (dir) => {
this.stats.currentEmpty += 1;
updateProgress(this.stats.currentEmpty, this.stats.totalEmpty);
this.log(
'verbose',
`${chalk.yellow.bold('DELETED EMPTY DIR')} (${this.stats.currentEmpty}/${this.stats.totalEmpty}) ${chalk.gray(dir)}`
);
});
inst.on('afterEmptyDirs', () => {
if(showProgress) process.stdout.write('\n');
this.log('event', 'afterEmptyDirs');
});
// Error Event (called as soon as an error is encountered)
inst.on('error', (err) => {
this.log('event', 'error');
this.log('error', err.error);
});
// FileError Event (called when there was an error deleting a file)
inst.on('fileError', (err) => {
this.log('event', 'fileError');
this.log('error', `${chalk.red.bold('FILE ERROR:')} ${err.error}\n${chalk.gray(err.file)}`);
});
// Finish Event (once processing/deleting all files is complete)
inst.on('finish', (results) => {
if(showProgress) process.stdout.write('\n');
this.log('event', 'finish');
this.log(
'verbose',
`${chalk.green('FINISH')} Deleted ${chalk.yellow.bold(results.length)} files/folders of ${chalk.yellow.bold(this.stats.total)}`
);
});
// Complete Event (once everything has completed)
inst.on('complete', () => {
this.log('event', 'complete');
});
}
done(err, results) {
console.log(
"\n" + chalk.green.bold('FILES/FOLDERS DELETED') + "\n" +
` ${chalk.yellow.bold('Total: ')} ${results.length}\n` +
` ${chalk.yellow.bold('Skipped: ')} ${this.stats.skipped.length}\n` +
` ${chalk.yellow.bold('Empty: ')} ${this.stats.totalEmpty}\n`
);
setTimeout(() => {
process.stdin.destroy();
if(err) {
this.log('error', err);
return process.exit(1);
}
process.exit(0);
}, 500);
}
}
new ModClean_CLI();