forked from deftomat/opinionated
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.ts
executable file
·302 lines (268 loc) · 10.1 KB
/
cli.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
import chalk from 'chalk';
import { program } from 'commander';
import inquirer from 'inquirer';
import { registerExitHandlers } from './src/cleanup.js';
import { ensureConfigs } from './src/configs.js';
import { Context, describeContext, isMonorepoPackageContext } from './src/context.js';
import { lint } from './src/eslint.js';
import { format } from './src/format.js';
import {
checkNpmAudit,
checkNpmLockIntegrity,
fixNpmAudit,
fixNpmLockDuplicates,
usesNpm
} from './src/npm.js';
import { preCommit } from './src/preCommit.js';
import { getIncompleteChecks, updateIncompleteChecks } from './src/store.js';
import { containsTypeScript, runTypeCheck } from './src/typeCheck.js';
import { StepResult, renderOnePackageWarning, step } from './src/utils.js';
import {
checkLockDuplicates,
checkLockIntegrity,
fixLockDuplicates,
usesYarn
} from './src/yarn.js';
// @ts-ignore
import('../../package.json', { assert: { type: 'json' } }).then(
({ default: { version, description } }) => {
const { bold, gray, red, yellow } = chalk;
registerExitHandlers();
program.version(version, '-v, --vers', 'output the current version').description(description);
program.command('pre-commit').description('Run pre-commit checks.').action(handlePreCommit);
program.command('checkup').description('Check up the project.').action(handleCheckup);
program
.command('ensure-configs')
.description(
'Ensure that all necessary configs are in place.\n\n' +
'In a normal conditions, running this command is not necessary as \neach check ensures that all configs are in place.'
)
.action(handleEnsureConfigs);
program.on('command:*', () => {
console.error(
red('Invalid command: %s\nSee --help for a list of available commands.'),
program.args.join(' ')
);
});
program.parse(process.argv);
if (!process.argv.slice(2).length) {
program.outputHelp({ error: true });
}
async function handlePreCommit() {
const context = await prepareContext({ autoStage: true });
await step({
description: 'Running pre-commit checks',
run: () => preCommit(context)
});
}
async function handleCheckup() {
const context = await prepareContext({ autoStage: false });
if (isMonorepoPackageContext(context)) renderOnePackageWarning(context);
const incompleteChecks = getIncompleteChecks(context);
const { requiredChecks, autoFix } = await inquirer.prompt([
{
type: 'checkbox',
name: 'requiredChecks',
message: 'Select checkup operations:',
choices: [
usesYarn(context) && {
checked: incompleteChecks.size > 0 ? incompleteChecks.has('integrity') : true,
name: `${bold('Integrity')} - ensures that dependencies are installed properly`,
short: 'Integrity',
value: 'integrity'
},
usesYarn(context) && {
checked: incompleteChecks.size > 0 ? incompleteChecks.has('duplicates') : true,
name: `${bold(
'Dependency duplicates check'
)} - ensures no unnecessary dependency duplicates`,
short: 'Duplicates',
value: 'duplicates'
},
usesNpm(context) && {
checked: incompleteChecks.size > 0 ? incompleteChecks.has('integrity') : true,
name: `${bold('Integrity')} - ensures that dependencies are installed properly`,
short: 'Integrity',
value: 'integrity'
},
usesNpm(context) && {
checked: incompleteChecks.size > 0 ? incompleteChecks.has('duplicates') : true,
name: `${bold(
'Dependency duplicates check'
)} - ensures no unnecessary dependency duplicates`,
short: 'Duplicates',
value: 'duplicates'
},
usesNpm(context) && {
checked: incompleteChecks.size > 0 ? incompleteChecks.has('audit') : true,
name: `${bold('Packages audit')} - ensures all packages are up to date`,
short: 'Audit',
value: 'audit'
},
{
checked: incompleteChecks.size > 0 ? incompleteChecks.has('eslint') : true,
name: `${bold('Linter')} - runs ESLint`,
short: 'Linter',
value: 'eslint'
},
containsTypeScript(context) && {
checked: incompleteChecks.size > 0 ? incompleteChecks.has('typescript') : true,
name: `${bold('TypeScript check')} - detects type errors and unused code`,
short: 'TypeScript',
value: 'typescript'
},
{
checked: incompleteChecks.size > 0 ? incompleteChecks.has('prettier') : false,
name: `${bold('Formatting')} - runs Prettier`,
short: 'Formatter',
value: 'prettier'
}
].filter(Boolean)
},
{
type: 'confirm',
name: 'autoFix',
message: 'Do you want to auto-fix any issues if possible?',
default: false,
when: ({ requiredChecks }) =>
requiredChecks.includes('eslint') ||
requiredChecks.includes('duplicates') ||
requiredChecks.includes('audit')
}
]);
if ((await context.git.hasChanges()) && (autoFix || requiredChecks.includes('prettier'))) {
const { shouldRun } = await inquirer.prompt([
{
type: 'confirm',
name: 'shouldRun',
message: yellow(
'Selected operations may affect your non-committed files! Do you want to continue?'
),
default: false
}
]);
if (!shouldRun) process.exit();
}
updateIncompleteChecks(context, requiredChecks);
const checks: Check[] = [];
if (usesYarn(context)) {
checks.push({
name: 'integrity',
enabled: requiredChecks.includes('integrity'),
description: 'Checking yarn.lock integrity',
run: () => checkLockIntegrity(context)
});
checks.push({
name: 'duplicates',
enabled: requiredChecks.includes('duplicates') && autoFix,
description: 'Removing dependency duplicates',
run: () => fixLockDuplicates(context)
});
checks.push({
name: 'duplicates',
enabled: requiredChecks.includes('duplicates') && !autoFix,
description: 'Detecting dependency duplicates',
run: () => checkLockDuplicates(context)
});
}
if (usesNpm(context)) {
checks.push({
name: 'integrity',
enabled: requiredChecks.includes('integrity'),
description: 'Checking package-lock.json integrity',
run: () => checkNpmLockIntegrity(context)
});
checks.push({
name: 'duplicates',
enabled: requiredChecks.includes('duplicates'),
description: 'Removing dependency duplicates',
run: () => fixNpmLockDuplicates(context)
});
checks.push({
name: 'audit',
enabled: requiredChecks.includes('audit') && autoFix,
description: 'Fixing the npm audit',
run: () => fixNpmAudit(context)
});
checks.push({
name: 'audit',
enabled: requiredChecks.includes('audit') && !autoFix,
description: 'Checking the npm audit',
run: () => checkNpmAudit(context)
});
}
checks.push({
name: 'eslint',
enabled: requiredChecks.includes('eslint') && autoFix,
description: 'Linting & auto-fixing via ESLint',
run: () => lint(context, { autoFix: true })
});
checks.push({
name: 'eslint',
enabled: requiredChecks.includes('eslint') && !autoFix,
description: 'Linting via ESLint',
run: () => lint(context, { autoFix: false })
});
checks.push({
name: 'typescript',
enabled: requiredChecks.includes('typescript'),
description: 'Running TypeScript checks',
run: () => runTypeCheck(context)
});
checks.push({
name: 'prettier',
enabled: requiredChecks.includes('prettier'),
description: 'Formatting with Prettier',
run: () => format(context)
});
const missingChecks = new Set<string>(requiredChecks);
for (const check of checks) {
if (!check.enabled) continue;
check.result = await step({
description: check.description,
run: check.run
});
missingChecks.delete(check.name);
updateIncompleteChecks(context, missingChecks);
}
}
interface Check {
readonly name: string;
readonly enabled: boolean;
readonly description: string;
result?: StepResult;
run(): void;
}
async function handleEnsureConfigs(cmd) {
const context = describeContext(process.cwd());
await step({
description: 'Checking necessary configs',
run: () => ensureConfigs(context),
success: (addedConfigs: string[]) => {
if (addedConfigs.length > 0) {
return `The following configs have been added into project: ${addedConfigs.join(', ')}`;
}
return 'All configs are in place';
}
});
}
async function prepareContext({ autoStage }: { autoStage: boolean }): Promise<Context> {
try {
const context = describeContext(process.cwd());
await context.git.ensureMinimumGitVersion();
if (!(await context.git.isGitRepository())) {
throw Error('Failed to run! Project must be the Git repository.');
}
const addedConfigs = await ensureConfigs(context, { autoStage });
if (addedConfigs.length > 0)
console.info(
gray(`[The following configs have been added into project: ${addedConfigs.join(', ')}]`)
);
return context;
} catch (e) {
console.error(red(e.message));
throw process.exit(1);
}
}
}
);