-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclean.ts
318 lines (274 loc) · 8.09 KB
/
clean.ts
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import child_process from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { Args, Flags } from '@oclif/core';
import chalk from 'chalk';
import enquirer from 'enquirer';
import { WithConfig } from '../base-commands/WithConfig.js';
import { pathToPosix } from '../utils/misc.js';
import { WPMonorepo } from '../utils/wp-monorepo.js';
type CleanArgs = {
path: string;
include?: string[];
all?: boolean;
};
export default class Clean extends WithConfig {
static description = 'Cleans up the given path(s) in this monorepo.';
static examples = [
'<%= config.bin %> <%= command.id %> plugins/wptelegram --include=ignored --include=node_modules',
'<%= config.bin %> <%= command.id %> --all',
];
static flags = {
include: Flags.string({
char: 'i',
description: 'Type of files to delete',
options: ['ignored', 'node_modules', 'composer.lock', 'vendor'],
multiple: true,
}),
all: Flags.boolean({
description: 'Clean everything',
}),
};
static args = {
path: Args.string({
description: 'Path to clean. Relative to root directory',
}),
};
getInput() {
return this.parse(Clean);
}
public async run(): Promise<void> {
const { args: _args, flags } = await this.getInput();
const args: CleanArgs = {
path: _args.path ?? '',
all: flags.all,
include: flags.include,
};
if (args.all) {
args.path = '.';
args.include = ['ignored', 'node_modules', 'composer.lock', 'vendor'];
} else if (!args.path) {
args.path = '.';
}
try {
const toDelete = args.include
? args.include
: await this.promptForClean(args);
const allFiles = await this.collectAllFiles(toDelete, args);
const filesToDelete = this.collectCleanFiles(allFiles, toDelete);
if (!filesToDelete.length) {
this.log(chalk.green('No files to delete!'));
return;
}
// Confirm the deletion.
const runConfirm = await this.confirmRemove(args, filesToDelete);
if (!runConfirm.confirm) {
this.log(chalk.red('Cancelling clean up.'));
return;
}
await this.cleanFiles(filesToDelete, args);
} catch (error) {
if (
typeof error === 'object' &&
error &&
'message' in error &&
error.message
) {
this.log(chalk.red(error.message));
}
process.exitCode = 1;
}
}
async promptForClean(args: CleanArgs) {
let promptPath = args.path;
if (args.path === '.' || args.path === 'all') {
promptPath = 'everywhere';
} else {
promptPath = `at ${promptPath}`;
}
const response = await enquirer.prompt<{
toDelete: Array<string>;
}>([
{
type: 'multiselect',
name: 'toDelete',
message: `What file types should be deleted ${promptPath}?`,
choices: [
{
message: 'Files ignored by git',
value: 'ignored',
name: 'ignored',
},
{
value: 'node_modules',
name: 'node_modules',
},
{
value: 'composer.lock',
name: 'composer.lock',
},
{
value: 'vendor',
name: 'vendor',
},
],
},
]);
return response.toDelete;
}
async cleanFiles(filesToDelete: Array<string>, args: CleanArgs) {
console.error(chalk.green('Cleaning files! You may grab a coffee...'));
for (const file of filesToDelete) {
try {
this.log(`Cleaning ${file}`);
fs.rmSync(file, { recursive: true, force: true });
} catch (e) {
console.error(chalk.red((e as { message: string }).message));
process.exitCode = 1;
return;
}
}
const nodeModulesDirs = filesToDelete.filter((file) =>
file.match(/(^|\/)node_modules\/$/),
);
if (nodeModulesDirs.length) {
process.on('exit', () => {
for (const file of nodeModulesDirs) {
fs.rmSync(file, { recursive: true, force: true });
}
});
}
this.log(
chalk.green(
`Clean completed! ${
args.path === '.' ? 'Everything' : args.path
} cleans up so nicely, doesn't it?`,
),
);
}
collectCleanFiles(
allFiles: Record<string, Array<string>>,
toDelete: Array<string>,
) {
let filesToDelete = new Set<string>();
for (const file of toDelete) {
switch (file) {
case 'node_modules':
filesToDelete = new Set([...filesToDelete, ...allFiles.node_modules]);
break;
case 'composer.lock':
filesToDelete = new Set([...filesToDelete, ...allFiles.composerLock]);
break;
case 'vendor':
filesToDelete = new Set([...filesToDelete, ...allFiles.vendor]);
break;
case 'ignored':
filesToDelete = new Set([...filesToDelete, ...allFiles.other]);
break;
}
}
// Ensure that node_modules/ at root is deleted last.
if (filesToDelete.has('node_modules/')) {
filesToDelete.delete('node_modules/');
/**
* TODO fix this
*
* Deletion of node_modules/ fails with this error on Windows:
*
* EPERM: operation not permitted, unlink '.pnpm\@[email protected]\node_modules\@rollup\rollup-win32-x64-msvc\rollup.win32-x64-msvc.node
*/
filesToDelete.add('node_modules/');
}
return [...filesToDelete].filter(Boolean);
}
async collectAllFiles(toDelete: Array<string>, args: CleanArgs) {
const allFiles: Record<string, Array<string>> = {
node_modules: [],
vendor: [],
composerLock: [],
other: [],
};
const ignoredFiles = child_process.execSync(
`git -c core.quotepath=off ls-files ${args.path} --exclude-standard --directory --ignored --other`,
);
const ignoredFileNames = ignoredFiles.toString().trim().split('\n');
// If we want to clean up a checked in composer.lock file, ls-files won't work and we have to filter the files manually.
if (toDelete.includes('composer.lock')) {
const files = child_process.execSync(
'git -c core.quotepath=off ls-files **/*/composer.lock',
);
const composerLockFiles = files.toString().trim().split('\n');
allFiles.composerLock.push(...composerLockFiles);
}
const filesToSkip = new Set<string>();
if (this.cliConfig.operationMode === 'wp-monorepo') {
// Skip the premium folder
filesToSkip.add('premium/');
const wpMonorepo = new WPMonorepo(this.cliConfig);
// It's possible that the connected project may be a git repo
// So the above git commands won't work for nested git repos
const connectedProjects = await wpMonorepo.getProjects({
connected: true,
});
for (const [name, project] of connectedProjects) {
const files = child_process.execSync(
`git -C ${project.dir} -c core.quotepath=off ls-files --exclude-standard --directory --ignored --other`,
);
const connectedProjectFiles = files
.toString()
.trim()
.split('\n')
.map((file) => pathToPosix(path.join(project.relativeDir, file)));
ignoredFileNames.push(...connectedProjectFiles);
if (
toDelete.includes('composer.lock') &&
fs.existsSync(path.join(project.dir, 'composer.lock'))
) {
allFiles.composerLock.push(
path.join(project.relativeDir, 'composer.lock'),
);
}
}
// We do not want to delete any of the project directories in the monorepo.
for (const [name, project] of await wpMonorepo.getAllProjects()) {
const entry = // We need posix paths for git
pathToPosix(project.relativeDir)
// Ensure that the path ends with a slash.
.replace(/\/?$/, '/');
filesToSkip.add(entry);
}
}
for (const file of ignoredFileNames) {
if (filesToSkip.has(file) || file.endsWith('.env')) {
continue;
}
if (file.match(/(^|\/)node_modules\/$/)) {
allFiles.node_modules.push(file);
} else if (file.match(/(^|\/)vendor\/$/)) {
allFiles.vendor.push(file);
} else if (file.match(/(^|\/)composer\.lock$/)) {
allFiles.composerLock.push(file);
} else {
allFiles.other.push(file);
}
}
return allFiles;
}
async confirmRemove(args: CleanArgs, filesToDelete: Array<string>) {
for (const file of filesToDelete) {
this.log(file);
}
let confirmMessage = 'Okay to delete the above files/folders?';
if (args.all) {
confirmMessage =
'You want to nuke everything? (node_modules, vendor, and git-ignored files?)';
}
const response = await enquirer.prompt<{ confirm: boolean }>({
type: 'confirm',
name: 'confirm',
message: chalk.green(confirmMessage),
initial: true,
});
return response;
}
}