-
Notifications
You must be signed in to change notification settings - Fork 914
/
cli.ts
362 lines (325 loc) Β· 8.65 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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
import load from '@commitlint/load';
import lint from '@commitlint/lint';
import read from '@commitlint/read';
import isFunction from 'lodash/isFunction';
import stdin from 'get-stdin';
import resolveFrom from 'resolve-from';
import resolveGlobal from 'resolve-global';
import yargs from 'yargs';
import {CliFlags, Seed} from './types';
import {
LintOptions,
LintOutcome,
ParserOptions,
ParserPreset,
QualifiedConfig,
Formatter,
} from '@commitlint/types';
import {CliError} from './cli-error';
const pkg = require('../package');
const cli = yargs
.options({
color: {
alias: 'c',
default: true,
description: 'toggle colored output',
type: 'boolean',
},
config: {
alias: 'g',
description: 'path to the config file',
type: 'string',
},
cwd: {
alias: 'd',
default: process.cwd(),
defaultDescription: '(Working Directory)',
description: 'directory to execute in',
type: 'string',
},
edit: {
alias: 'e',
description:
'read last commit message from the specified file or fallbacks to ./.git/COMMIT_EDITMSG',
type: 'string',
},
env: {
alias: 'E',
description:
'check message in the file at path given by environment variable value',
type: 'string',
},
extends: {
alias: 'x',
description: 'array of shareable configurations to extend',
type: 'array',
},
'help-url': {
alias: 'H',
type: 'string',
description: 'help url in error message',
},
from: {
alias: 'f',
description:
'lower end of the commit range to lint; applies if edit=false',
type: 'string',
},
format: {
alias: 'o',
description: 'output format of the results',
type: 'string',
},
'parser-preset': {
alias: 'p',
description:
'configuration preset to use for conventional-commits-parser',
type: 'string',
},
quiet: {
alias: 'q',
default: false,
description: 'toggle console output',
type: 'boolean',
},
to: {
alias: 't',
description:
'upper end of the commit range to lint; applies if edit=false',
type: 'string',
},
verbose: {
alias: 'V',
type: 'boolean',
description: 'enable verbose output for reports without problems',
},
})
.version(
'version',
'display version information',
`${pkg.name}@${pkg.version}`
)
.alias('v', 'version')
.help('help')
.alias('h', 'help')
.usage(`${pkg.name}@${pkg.version} - ${pkg.description}\n`)
.usage(
`[input] reads from stdin if --edit, --env, --from and --to are omitted`
)
.strict();
main({edit: false, ...cli.argv}).catch((err) => {
setTimeout(() => {
if (err.type === pkg.name) {
process.exit(1);
}
throw err;
}, 0);
});
async function main(options: CliFlags) {
const raw = options._;
const flags = normalizeFlags(options);
const fromStdin = checkFromStdin(raw, flags);
const input = await (fromStdin
? stdin()
: read({
to: flags.to,
from: flags.from,
edit: flags.edit,
cwd: flags.cwd,
}));
const messages = (Array.isArray(input) ? input : [input])
.filter((message) => typeof message === 'string')
.filter((message) => message.trim() !== '')
.filter(Boolean);
if (messages.length === 0 && !checkFromRepository(flags)) {
const err = new CliError(
'[input] is required: supply via stdin, or --env or --edit or --from and --to',
pkg.name
);
yargs.showHelp('log');
console.log(err.message);
throw err;
}
const loadOpts = {cwd: flags.cwd, file: flags.config};
const loaded = await load(getSeed(flags), loadOpts);
const parserOpts = selectParserOpts(loaded.parserPreset);
const opts: LintOptions & {parserOpts: ParserOptions} = {
parserOpts: {},
plugins: {},
ignores: [],
defaultIgnores: true,
};
if (parserOpts) {
opts.parserOpts = parserOpts;
}
if (loaded.plugins) {
opts.plugins = loaded.plugins;
}
if (loaded.ignores) {
opts.ignores = loaded.ignores;
}
if (loaded.defaultIgnores === false) {
opts.defaultIgnores = false;
}
const format = loadFormatter(loaded, flags);
// Strip comments if reading from `.git/COMMIT_EDIT_MSG`
if (flags.edit) {
opts.parserOpts.commentChar = '#';
}
const results = await Promise.all(
messages.map((message) => lint(message, loaded.rules, opts))
);
if (Object.keys(loaded.rules).length === 0) {
let input = '';
if (results.length !== 0) {
input = results[0].input;
}
results.splice(0, results.length, {
valid: false,
errors: [
{
level: 2,
valid: false,
name: 'empty-rules',
message: [
'Please add rules to your `commitlint.config.js`',
' - Getting started guide: https://git.io/fhHij',
' - Example config: https://git.io/fhHip',
].join('\n'),
},
],
warnings: [],
input,
});
}
const report = results.reduce<{
valid: boolean;
errorCount: number;
warningCount: number;
results: LintOutcome[];
}>(
(info, result) => {
info.valid = result.valid ? info.valid : false;
info.errorCount += result.errors.length;
info.warningCount += result.warnings.length;
info.results.push(result);
return info;
},
{
valid: true,
errorCount: 0,
warningCount: 0,
results: [],
}
);
const output = format(report, {
color: flags.color,
verbose: flags.verbose,
helpUrl: flags['help-url']
? flags['help-url'].trim()
: 'https://github.com/conventional-changelog/commitlint/#what-is-commitlint',
});
if (!flags.quiet && output !== '') {
console.log(output);
}
if (!report.valid) {
throw new CliError(output, pkg.name);
}
}
function checkFromStdin(input: string[], flags: CliFlags): boolean {
return input.length === 0 && !checkFromRepository(flags);
}
function checkFromRepository(flags: CliFlags) {
return checkFromHistory(flags) || checkFromEdit(flags);
}
function checkFromEdit(flags: CliFlags) {
return Boolean(flags.edit) || flags.env;
}
function checkFromHistory(flags: CliFlags): boolean {
return typeof flags.from === 'string' || typeof flags.to === 'string';
}
function normalizeFlags(flags: CliFlags): CliFlags {
const edit = getEditValue(flags);
return {
...flags,
edit,
};
}
function getEditValue(flags: CliFlags) {
if (flags.env) {
if (!(flags.env in process.env)) {
throw new Error(
`Recieved '${flags.env}' as value for -E | --env, but environment variable '${flags.env}' is not available globally`
);
}
return process.env[flags.env];
}
const {edit} = flags;
// If the edit flag is set but empty (i.e '-e') we default
// to .git/COMMIT_EDITMSG
if (edit === '') {
return true;
}
if (typeof edit === 'boolean') {
return edit;
}
// The recommended method to specify -e with husky was `commitlint -e $HUSKY_GIT_PARAMS`
// This does not work properly with win32 systems, where env variable declarations
// use a different syntax
// See https://github.com/conventional-changelog/commitlint/issues/103 for details
// This has been superceded by the `-E GIT_PARAMS` / `-E HUSKY_GIT_PARAMS`
const isGitParams = edit === '$GIT_PARAMS' || edit === '%GIT_PARAMS%';
const isHuskyParams =
edit === '$HUSKY_GIT_PARAMS' || edit === '%HUSKY_GIT_PARAMS%';
if (isGitParams || isHuskyParams) {
console.warn(`Using environment variable syntax (${edit}) in -e |\
--edit is deprecated. Use '{-E|--env} HUSKY_GIT_PARAMS instead'`);
if (isGitParams && 'GIT_PARAMS' in process.env) {
return process.env.GIT_PARAMS;
}
if ('HUSKY_GIT_PARAMS' in process.env) {
return process.env.HUSKY_GIT_PARAMS;
}
throw new Error(
`Received ${edit} as value for -e | --edit, but GIT_PARAMS or HUSKY_GIT_PARAMS are not available globally.`
);
}
return edit;
}
function getSeed(flags: CliFlags): Seed {
const n = (flags.extends || []).filter(
(i): i is string => typeof i === 'string'
);
return n.length > 0
? {extends: n, parserPreset: flags['parser-preset']}
: {parserPreset: flags['parser-preset']};
}
function selectParserOpts(parserPreset: ParserPreset) {
if (typeof parserPreset !== 'object') {
return undefined;
}
if (typeof parserPreset.parserOpts !== 'object') {
return undefined;
}
return parserPreset.parserOpts;
}
function loadFormatter(config: QualifiedConfig, flags: CliFlags): Formatter {
const moduleName = flags.format || config.formatter || '@commitlint/format';
const modulePath =
resolveFrom.silent(__dirname, moduleName) ||
resolveFrom.silent(flags.cwd, moduleName) ||
resolveGlobal.silent(moduleName);
if (modulePath) {
const moduleInstance = require(modulePath);
if (isFunction(moduleInstance.default)) {
return moduleInstance.default;
}
return moduleInstance;
}
throw new Error(`Using format ${moduleName}, but cannot find the module.`);
}
// Catch unhandled rejections globally
process.on('unhandledRejection', (reason, promise) => {
console.log('Unhandled Rejection at: Promise ', promise, ' reason: ', reason);
throw reason;
});