2 * @fileoverview Main CLI object.
3 * @author Nicholas C. Zakas
9 * NOTE: The CLI object should *not* call process.exit() directly. It should only return
10 * exit codes. This allows other programs to use the CLI object and still control
11 * when the program exits.
14 //------------------------------------------------------------------------------
16 //------------------------------------------------------------------------------
18 const fs
= require("fs"),
19 path
= require("path"),
20 { promisify
} = require("util"),
21 { ESLint
} = require("./eslint"),
22 { FlatESLint
} = require("./eslint/flat-eslint"),
23 createCLIOptions
= require("./options"),
24 log
= require("./shared/logging"),
25 RuntimeInfo
= require("./shared/runtime-info");
26 const { Legacy
: { naming
} } = require("@eslint/eslintrc");
27 const { findFlatConfigFile
} = require("./eslint/flat-eslint");
28 const { gitignoreToMinimatch
} = require("@humanwhocodes/gitignore-to-minimatch");
29 const { ModuleImporter
} = require("@humanwhocodes/module-importer");
31 const debug
= require("debug")("eslint:cli");
33 //------------------------------------------------------------------------------
35 //------------------------------------------------------------------------------
37 /** @typedef {import("./eslint/eslint").ESLintOptions} ESLintOptions */
38 /** @typedef {import("./eslint/eslint").LintMessage} LintMessage */
39 /** @typedef {import("./eslint/eslint").LintResult} LintResult */
40 /** @typedef {import("./options").ParsedCLIOptions} ParsedCLIOptions */
42 //------------------------------------------------------------------------------
44 //------------------------------------------------------------------------------
46 const mkdir = promisify(fs.mkdir);
47 const stat = promisify(fs.stat);
48 const writeFile = promisify(fs.writeFile);
51 * Predicate function for whether or not to apply fixes in quiet mode.
52 * If a message is a warning, do not apply a fix.
53 * @param {LintMessage} message The lint result.
54 * @returns {boolean} True if the lint message is an error (and thus should be
55 * autofixed), false otherwise.
57 function quietFixPredicate(message
) {
58 return message
.severity
=== 2;
62 * Translates the CLI options into the options expected by the ESLint constructor.
63 * @param {ParsedCLIOptions} cliOptions The CLI options to translate.
64 * @param {"flat"|"eslintrc"} [configType="eslintrc"] The format of the
66 * @returns {Promise<ESLintOptions>} The options object for the ESLint constructor.
69 async
function translateOptions({
77 errorOnUnmatchedPattern
,
92 reportUnusedDisableDirectives
,
93 resolvePluginsRelativeTo
,
98 let overrideConfig
, overrideConfigFile
;
99 const importer
= new ModuleImporter();
101 if (configType
=== "flat") {
102 overrideConfigFile
= (typeof config
=== "string") ? config
: !configLookup
;
103 if (overrideConfigFile
=== false) {
104 overrideConfigFile
= void 0;
110 globals
= global
.reduce((obj
, name
) => {
111 if (name
.endsWith(":true")) {
112 obj
[name
.slice(0, -5)] = "writable";
114 obj
[name
] = "readonly";
123 parserOptions
: parserOptions
|| {}
125 rules
: rule
? rule
: {}
129 overrideConfig
[0].languageOptions
.parser
= await importer
.import(parser
);
135 for (const pluginName
of plugin
) {
137 const shortName
= naming
.getShorthandName(pluginName
, "eslint-plugin");
138 const longName
= naming
.normalizePackageName(pluginName
, "eslint-plugin");
140 plugins
[shortName
] = await importer
.import(longName
);
143 overrideConfig
[0].plugins
= plugins
;
147 overrideConfig
.push({
148 ignores
: ignorePattern
.map(gitignoreToMinimatch
)
153 overrideConfigFile
= config
;
156 env
: env
&& env
.reduce((obj
, name
) => {
160 globals
: global
&& global
.reduce((obj
, name
) => {
161 if (name
.endsWith(":true")) {
162 obj
[name
.slice(0, -5)] = "writable";
164 obj
[name
] = "readonly";
168 ignorePatterns
: ignorePattern
,
177 allowInlineConfig
: inlineConfig
,
179 cacheLocation
: cacheLocation
|| cacheFile
,
181 errorOnUnmatchedPattern
,
182 fix
: (fix
|| fixDryRun
) && (quiet
? quietFixPredicate
: true),
188 reportUnusedDisableDirectives
: reportUnusedDisableDirectives
? "error" : void 0
191 if (configType
!== "flat") {
192 options
.resolvePluginsRelativeTo
= resolvePluginsRelativeTo
;
193 options
.rulePaths
= rulesdir
;
194 options
.useEslintrc
= eslintrc
;
195 options
.extensions
= ext
;
202 * Count error messages.
203 * @param {LintResult[]} results The lint results.
204 * @returns {{errorCount:number;warningCount:number}} The number of error messages.
206 function countErrors(results
) {
208 let fatalErrorCount
= 0;
209 let warningCount
= 0;
211 for (const result
of results
) {
212 errorCount
+= result
.errorCount
;
213 fatalErrorCount
+= result
.fatalErrorCount
;
214 warningCount
+= result
.warningCount
;
217 return { errorCount
, fatalErrorCount
, warningCount
};
221 * Check if a given file path is a directory or not.
222 * @param {string} filePath The path to a file to check.
223 * @returns {Promise<boolean>} `true` if the given path is a directory.
225 async
function isDirectory(filePath
) {
227 return (await
stat(filePath
)).isDirectory();
229 if (error
.code
=== "ENOENT" || error
.code
=== "ENOTDIR") {
237 * Outputs the results of the linting.
238 * @param {ESLint} engine The ESLint instance to use.
239 * @param {LintResult[]} results The results to print.
240 * @param {string} format The name of the formatter to use or the path to the formatter.
241 * @param {string} outputFile The path for the output file.
242 * @returns {Promise<boolean>} True if the printing succeeds, false if not.
245 async
function printResults(engine
, results
, format
, outputFile
) {
249 formatter
= await engine
.loadFormatter(format
);
251 log
.error(e
.message
);
255 const output
= await formatter
.format(results
);
259 const filePath
= path
.resolve(process
.cwd(), outputFile
);
261 if (await
isDirectory(filePath
)) {
262 log
.error("Cannot write to output file path, it is a directory: %s", outputFile
);
267 await
mkdir(path
.dirname(filePath
), { recursive
: true });
268 await
writeFile(filePath
, output
);
270 log
.error("There was a problem writing the output file:\n%s", ex
);
281 //------------------------------------------------------------------------------
283 //------------------------------------------------------------------------------
286 * Encapsulates all CLI behavior for eslint. Makes it easier to test as well as
287 * for other Node.js programs to effectively run the CLI.
292 * Executes the CLI based on an array of arguments that is passed in.
293 * @param {string|Array|Object} args The arguments to process.
294 * @param {string} [text] The text to lint (used for TTY).
295 * @param {boolean} [allowFlatConfig] Whether or not to allow flat config.
296 * @returns {Promise<number>} The exit code for the operation.
298 async
execute(args
, text
, allowFlatConfig
) {
299 if (Array
.isArray(args
)) {
300 debug("CLI args: %o", args
.slice(2));
304 * Before doing anything, we need to see if we are using a
305 * flat config file. If so, then we need to change the way command
306 * line args are parsed. This is temporary, and when we fully
307 * switch to flat config we can remove this logic.
310 const usingFlatConfig
= allowFlatConfig
&& !!(await
findFlatConfigFile(process
.cwd()));
312 debug("Using flat config?", usingFlatConfig
);
314 const CLIOptions
= createCLIOptions(usingFlatConfig
);
316 /** @type {ParsedCLIOptions} */
320 options
= CLIOptions
.parse(args
);
322 debug("Error parsing CLI options:", error
.message
);
323 log
.error(error
.message
);
327 const files
= options
._
;
328 const useStdin
= typeof text
=== "string";
331 log
.info(CLIOptions
.generateHelp());
334 if (options
.version
) {
335 log
.info(RuntimeInfo
.version());
338 if (options
.envInfo
) {
340 log
.info(RuntimeInfo
.environment());
343 debug("Error retrieving environment info");
344 log
.error(err
.message
);
349 if (options
.printConfig
) {
351 log
.error("The --print-config option must be used with exactly one file name.");
355 log
.error("The --print-config option is not available for piped-in code.");
359 const engine
= usingFlatConfig
360 ? new FlatESLint(await
translateOptions(options
, "flat"))
361 : new ESLint(await
translateOptions(options
));
363 await engine
.calculateConfigForFile(options
.printConfig
);
365 log
.info(JSON
.stringify(fileConfig
, null, " "));
369 debug(`Running on ${useStdin ? "text" : "files"}`);
371 if (options
.fix
&& options
.fixDryRun
) {
372 log
.error("The --fix option and the --fix-dry-run option cannot be used together.");
375 if (useStdin
&& options
.fix
) {
376 log
.error("The --fix option is not available for piped-in code; use --fix-dry-run instead.");
379 if (options
.fixType
&& !options
.fix
&& !options
.fixDryRun
) {
380 log
.error("The --fix-type option requires either --fix or --fix-dry-run.");
384 const ActiveESLint
= usingFlatConfig
? FlatESLint
: ESLint
;
386 const engine
= new ActiveESLint(await
translateOptions(options
, usingFlatConfig
? "flat" : "eslintrc"));
390 results
= await engine
.lintText(text
, {
391 filePath
: options
.stdinFilename
,
395 results
= await engine
.lintFiles(files
);
399 debug("Fix mode enabled - applying fixes");
400 await ActiveESLint
.outputFixes(results
);
403 let resultsToPrint
= results
;
406 debug("Quiet mode enabled - filtering out warnings");
407 resultsToPrint
= ActiveESLint
.getErrorResults(resultsToPrint
);
410 if (await
printResults(engine
, resultsToPrint
, options
.format
, options
.outputFile
)) {
412 // Errors and warnings from the original unfiltered results should determine the exit code
413 const { errorCount
, fatalErrorCount
, warningCount
} = countErrors(results
);
415 const tooManyWarnings
=
416 options
.maxWarnings
>= 0 && warningCount
> options
.maxWarnings
;
417 const shouldExitForFatalErrors
=
418 options
.exitOnFatalError
&& fatalErrorCount
> 0;
420 if (!errorCount
&& tooManyWarnings
) {
422 "ESLint found too many warnings (maximum: %s).",
427 if (shouldExitForFatalErrors
) {
431 return (errorCount
|| tooManyWarnings
) ? 1 : 0;
438 module
.exports
= cli
;