2 * @fileoverview Main CLI object.
3 * @author Nicholas C. Zakas
9 * 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 mkdirp = require("mkdirp"),
21 { CLIEngine } = require("./cli-engine"),
22 options = require("./options"),
23 log = require("./shared/logging"),
24 RuntimeInfo = require("./shared/runtime-info");
26 const debug = require("debug")("eslint:cli");
28 //------------------------------------------------------------------------------
30 //------------------------------------------------------------------------------
33 * Predicate function for whether or not to apply fixes in quiet mode.
34 * If a message is a warning, do not apply a fix.
35 * @param {LintResult} lintResult The lint result.
36 * @returns {boolean} True if the lint message is an error (and thus should be
37 * autofixed), false otherwise.
39 function quietFixPredicate(lintResult) {
40 return lintResult.severity === 2;
44 * Translates the CLI options into the options expected by the CLIEngine.
45 * @param {Object} cliOptions The CLI options to translate.
46 * @returns {CLIEngineOptions} The options object for the CLIEngine.
49 function translateOptions(cliOptions) {
52 extensions: cliOptions.ext,
53 rules: cliOptions.rule,
54 plugins: cliOptions.plugin,
55 globals: cliOptions.global,
56 ignore: cliOptions.ignore,
57 ignorePath: cliOptions.ignorePath,
58 ignorePattern: cliOptions.ignorePattern,
59 configFile: cliOptions.config,
60 rulePaths: cliOptions.rulesdir,
61 useEslintrc: cliOptions.eslintrc,
62 parser: cliOptions.parser,
63 parserOptions: cliOptions.parserOptions,
64 cache: cliOptions.cache,
65 cacheFile: cliOptions.cacheFile,
66 cacheLocation: cliOptions.cacheLocation,
67 fix: (cliOptions.fix || cliOptions.fixDryRun) && (cliOptions.quiet ? quietFixPredicate : true),
68 fixTypes: cliOptions.fixType,
69 allowInlineConfig: cliOptions.inlineConfig,
70 reportUnusedDisableDirectives: cliOptions.reportUnusedDisableDirectives,
71 resolvePluginsRelativeTo: cliOptions.resolvePluginsRelativeTo,
72 errorOnUnmatchedPattern: cliOptions.errorOnUnmatchedPattern
77 * Outputs the results of the linting.
78 * @param {CLIEngine} engine The CLIEngine to use.
79 * @param {LintResult[]} results The results to print.
80 * @param {string} format The name of the formatter to use or the path to the formatter.
81 * @param {string} outputFile The path for the output file.
82 * @returns {boolean} True if the printing succeeds, false if not.
85 function printResults(engine, results, format, outputFile) {
90 formatter = engine.getFormatter(format);
96 const output = formatter(results, {
100 for (const [ruleId, rule] of engine.getRules()) {
101 rulesMeta[ruleId] = rule.meta;
110 const filePath = path.resolve(process.cwd(), outputFile);
112 if (fs.existsSync(filePath) && fs.statSync(filePath).isDirectory()) {
113 log.error("Cannot write to output file path, it is a directory: %s", outputFile);
118 mkdirp.sync(path.dirname(filePath));
119 fs.writeFileSync(filePath, output);
121 log.error("There was a problem writing the output file:\n%s", ex);
133 //------------------------------------------------------------------------------
135 //------------------------------------------------------------------------------
138 * Encapsulates all CLI behavior for eslint. Makes it easier to test as well as
139 * for other Node.js programs to effectively run the CLI.
144 * Executes the CLI based on an array of arguments that is passed in.
145 * @param {string|Array|Object} args The arguments to process.
146 * @param {string} [text] The text to lint (used for TTY).
147 * @returns {int} The exit code for the operation.
149 execute(args, text) {
150 if (Array.isArray(args)) {
151 debug("CLI args: %o", args.slice(2));
157 currentOptions = options.parse(args);
159 log.error(error.message);
163 const files = currentOptions._;
164 const useStdin = typeof text === "string";
166 if (currentOptions.version) {
167 log.info(RuntimeInfo.version());
168 } else if (currentOptions.envInfo) {
170 log.info(RuntimeInfo.environment());
173 log.error(err.message);
176 } else if (currentOptions.printConfig) {
178 log.error("The --print-config option must be used with exactly one file name.");
182 log.error("The --print-config option is not available for piped-in code.");
186 const engine = new CLIEngine(translateOptions(currentOptions));
187 const fileConfig = engine.getConfigForFile(currentOptions.printConfig);
189 log.info(JSON.stringify(fileConfig, null, " "));
191 } else if (currentOptions.help || (!files.length && !useStdin)) {
192 log.info(options.generateHelp());
194 debug(`Running on ${useStdin ? "text" : "files"}`);
196 if (currentOptions.fix && currentOptions.fixDryRun) {
197 log.error("The --fix option and the --fix-dry-run option cannot be used together.");
201 if (useStdin && currentOptions.fix) {
202 log.error("The --fix option is not available for piped-in code; use --fix-dry-run instead.");
206 if (currentOptions.fixType && !currentOptions.fix && !currentOptions.fixDryRun) {
207 log.error("The --fix-type option requires either --fix or --fix-dry-run.");
211 const engine = new CLIEngine(translateOptions(currentOptions));
212 const report = useStdin ? engine.executeOnText(text, currentOptions.stdinFilename, true) : engine.executeOnFiles(files);
214 if (currentOptions.fix) {
215 debug("Fix mode enabled - applying fixes");
216 CLIEngine.outputFixes(report);
219 if (currentOptions.quiet) {
220 debug("Quiet mode enabled - filtering out warnings");
221 report.results = CLIEngine.getErrorResults(report.results);
224 if (printResults(engine, report.results, currentOptions.format, currentOptions.outputFile)) {
225 const tooManyWarnings = currentOptions.maxWarnings >= 0 && report.warningCount > currentOptions.maxWarnings;
227 if (!report.errorCount && tooManyWarnings) {
228 log.error("ESLint found too many warnings (maximum: %s).", currentOptions.maxWarnings);
231 return (report.errorCount || tooManyWarnings) ? 1 : 0;
241 module.exports = cli;