123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340 |
- "use strict";
- var __asyncValues = (this && this.__asyncValues) || function (o) {
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
- var m = o[Symbol.asyncIterator], i;
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
- };
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- const load_1 = __importDefault(require("@commitlint/load"));
- const lint_1 = __importDefault(require("@commitlint/lint"));
- const read_1 = __importDefault(require("@commitlint/read"));
- const isFunction_1 = __importDefault(require("lodash/isFunction"));
- const resolve_from_1 = __importDefault(require("resolve-from"));
- const resolve_global_1 = __importDefault(require("resolve-global"));
- const yargs_1 = __importDefault(require("yargs"));
- const util_1 = __importDefault(require("util"));
- const cli_error_1 = require("./cli-error");
- const pkg = require('../package');
- const cli = yargs_1.default
- .options({
- color: {
- alias: 'c',
- default: true,
- description: 'toggle colored output',
- type: 'boolean',
- },
- config: {
- alias: 'g',
- description: 'path to the config file',
- type: 'string',
- },
- 'print-config': {
- type: 'boolean',
- default: false,
- description: 'print resolved config',
- },
- 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(cli.argv).catch((err) => {
- setTimeout(() => {
- if (err.type === pkg.name) {
- process.exit(1);
- }
- throw err;
- }, 0);
- });
- async function stdin() {
- var e_1, _a;
- let result = '';
- if (process.stdin.isTTY) {
- return result;
- }
- process.stdin.setEncoding('utf8');
- try {
- for (var _b = __asyncValues(process.stdin), _c; _c = await _b.next(), !_c.done;) {
- const chunk = _c.value;
- result += chunk;
- }
- }
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
- finally {
- try {
- if (_c && !_c.done && (_a = _b.return)) await _a.call(_b);
- }
- finally { if (e_1) throw e_1.error; }
- }
- return result;
- }
- async function resolveArgs(args) {
- return typeof args.then === 'function' ? await args : args;
- }
- async function main(args) {
- var _a;
- const options = await resolveArgs(args);
- if (typeof options.edit === 'undefined') {
- options.edit = false;
- }
- const raw = options._;
- const flags = normalizeFlags(options);
- if (flags['print-config']) {
- const loaded = await (0, load_1.default)(getSeed(flags), {
- cwd: flags.cwd,
- file: flags.config,
- });
- console.log(util_1.default.inspect(loaded, false, null, options.color));
- return;
- }
- const fromStdin = checkFromStdin(raw, flags);
- const input = await (fromStdin
- ? stdin()
- : (0, read_1.default)({
- 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 cli_error_1.CliError('[input] is required: supply via stdin, or --env or --edit or --from and --to', pkg.name);
- yargs_1.default.showHelp('log');
- console.log(err.message);
- throw err;
- }
- const loaded = await (0, load_1.default)(getSeed(flags), {
- cwd: flags.cwd,
- file: flags.config,
- });
- const parserOpts = selectParserOpts(loaded.parserPreset);
- const opts = {
- 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` using the
- // commentChar from the parser preset falling back to a `#` if that is not
- // set
- if (flags.edit && typeof opts.parserOpts.commentChar !== 'string') {
- opts.parserOpts.commentChar = '#';
- }
- const results = await Promise.all(messages.map((message) => (0, lint_1.default)(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((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 helpUrl = ((_a = flags['help-url']) === null || _a === void 0 ? void 0 : _a.trim()) || loaded.helpUrl;
- const output = format(report, {
- color: flags.color,
- verbose: flags.verbose,
- helpUrl,
- });
- if (!flags.quiet && output !== '') {
- console.log(output);
- }
- if (!report.valid) {
- throw new cli_error_1.CliError(output, pkg.name);
- }
- }
- function checkFromStdin(input, flags) {
- return input.length === 0 && !checkFromRepository(flags);
- }
- function checkFromRepository(flags) {
- return checkFromHistory(flags) || checkFromEdit(flags);
- }
- function checkFromEdit(flags) {
- return Boolean(flags.edit) || Boolean(flags.env);
- }
- function checkFromHistory(flags) {
- return typeof flags.from === 'string' || typeof flags.to === 'string';
- }
- function normalizeFlags(flags) {
- const edit = getEditValue(flags);
- return Object.assign(Object.assign({}, flags), { edit });
- }
- function getEditValue(flags) {
- if (flags.env) {
- if (!(flags.env in process.env)) {
- throw new Error(`Received '${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) {
- const n = (flags.extends || []).filter((i) => typeof i === 'string');
- return n.length > 0
- ? { extends: n, parserPreset: flags['parser-preset'] }
- : { parserPreset: flags['parser-preset'] };
- }
- function selectParserOpts(parserPreset) {
- if (typeof parserPreset !== 'object') {
- return undefined;
- }
- if (typeof parserPreset.parserOpts !== 'object') {
- return undefined;
- }
- return parserPreset.parserOpts;
- }
- function loadFormatter(config, flags) {
- const moduleName = flags.format || config.formatter || '@commitlint/format';
- const modulePath = resolve_from_1.default.silent(__dirname, moduleName) ||
- resolve_from_1.default.silent(flags.cwd, moduleName) ||
- resolve_global_1.default.silent(moduleName);
- if (modulePath) {
- const moduleInstance = require(modulePath);
- if ((0, isFunction_1.default)(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;
- });
- //# sourceMappingURL=cli.js.map
|