UNPKG

8.2 kBJavaScriptView Raw
1/**
2 * @fileoverview Main CLI object.
3 * @author Nicholas C. Zakas
4 */
5
6"use strict";
7
8/*
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.
12 */
13
14//------------------------------------------------------------------------------
15// Requirements
16//------------------------------------------------------------------------------
17
18const 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");
25
26const debug = require("debug")("eslint:cli");
27
28//------------------------------------------------------------------------------
29// Helpers
30//------------------------------------------------------------------------------
31
32/**
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.
38 */
39function quietFixPredicate(lintResult) {
40 return lintResult.severity === 2;
41}
42
43/**
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.
47 * @private
48 */
49function translateOptions(cliOptions) {
50 return {
51 envs: cliOptions.env,
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 };
73}
74
75/**
76 * Outputs the results of the linting.
77 * @param {CLIEngine} engine The CLIEngine to use.
78 * @param {LintResult[]} results The results to print.
79 * @param {string} format The name of the formatter to use or the path to the formatter.
80 * @param {string} outputFile The path for the output file.
81 * @returns {boolean} True if the printing succeeds, false if not.
82 * @private
83 */
84function printResults(engine, results, format, outputFile) {
85 let formatter;
86 let rulesMeta;
87
88 try {
89 formatter = engine.getFormatter(format);
90 } catch (e) {
91 log.error(e.message);
92 return false;
93 }
94
95 const output = formatter(results, {
96 get rulesMeta() {
97 if (!rulesMeta) {
98 rulesMeta = {};
99 for (const [ruleId, rule] of engine.getRules()) {
100 rulesMeta[ruleId] = rule.meta;
101 }
102 }
103 return rulesMeta;
104 }
105 });
106
107 if (output) {
108 if (outputFile) {
109 const filePath = path.resolve(process.cwd(), outputFile);
110
111 if (fs.existsSync(filePath) && fs.statSync(filePath).isDirectory()) {
112 log.error("Cannot write to output file path, it is a directory: %s", outputFile);
113 return false;
114 }
115
116 try {
117 mkdirp.sync(path.dirname(filePath));
118 fs.writeFileSync(filePath, output);
119 } catch (ex) {
120 log.error("There was a problem writing the output file:\n%s", ex);
121 return false;
122 }
123 } else {
124 log.info(output);
125 }
126 }
127
128 return true;
129
130}
131
132//------------------------------------------------------------------------------
133// Public Interface
134//------------------------------------------------------------------------------
135
136/**
137 * Encapsulates all CLI behavior for eslint. Makes it easier to test as well as
138 * for other Node.js programs to effectively run the CLI.
139 */
140const cli = {
141
142 /**
143 * Executes the CLI based on an array of arguments that is passed in.
144 * @param {string|Array|Object} args The arguments to process.
145 * @param {string} [text] The text to lint (used for TTY).
146 * @returns {int} The exit code for the operation.
147 */
148 execute(args, text) {
149 if (Array.isArray(args)) {
150 debug("CLI args: %o", args.slice(2));
151 }
152
153 let currentOptions;
154
155 try {
156 currentOptions = options.parse(args);
157 } catch (error) {
158 log.error(error.message);
159 return 2;
160 }
161
162 const files = currentOptions._;
163 const useStdin = typeof text === "string";
164
165 if (currentOptions.version) {
166 log.info(RuntimeInfo.version());
167 } else if (currentOptions.envInfo) {
168 try {
169 log.info(RuntimeInfo.environment());
170 return 0;
171 } catch (err) {
172 log.error(err.message);
173 return 2;
174 }
175 } else if (currentOptions.printConfig) {
176 if (files.length) {
177 log.error("The --print-config option must be used with exactly one file name.");
178 return 2;
179 }
180 if (useStdin) {
181 log.error("The --print-config option is not available for piped-in code.");
182 return 2;
183 }
184
185 const engine = new CLIEngine(translateOptions(currentOptions));
186 const fileConfig = engine.getConfigForFile(currentOptions.printConfig);
187
188 log.info(JSON.stringify(fileConfig, null, " "));
189 return 0;
190 } else if (currentOptions.help || (!files.length && !useStdin)) {
191 log.info(options.generateHelp());
192 } else {
193 debug(`Running on ${useStdin ? "text" : "files"}`);
194
195 if (currentOptions.fix && currentOptions.fixDryRun) {
196 log.error("The --fix option and the --fix-dry-run option cannot be used together.");
197 return 2;
198 }
199
200 if (useStdin && currentOptions.fix) {
201 log.error("The --fix option is not available for piped-in code; use --fix-dry-run instead.");
202 return 2;
203 }
204
205 if (currentOptions.fixType && !currentOptions.fix && !currentOptions.fixDryRun) {
206 log.error("The --fix-type option requires either --fix or --fix-dry-run.");
207 return 2;
208 }
209
210 const engine = new CLIEngine(translateOptions(currentOptions));
211 const report = useStdin ? engine.executeOnText(text, currentOptions.stdinFilename, true) : engine.executeOnFiles(files);
212
213 if (currentOptions.fix) {
214 debug("Fix mode enabled - applying fixes");
215 CLIEngine.outputFixes(report);
216 }
217
218 if (currentOptions.quiet) {
219 debug("Quiet mode enabled - filtering out warnings");
220 report.results = CLIEngine.getErrorResults(report.results);
221 }
222
223 if (printResults(engine, report.results, currentOptions.format, currentOptions.outputFile)) {
224 const tooManyWarnings = currentOptions.maxWarnings >= 0 && report.warningCount > currentOptions.maxWarnings;
225
226 if (!report.errorCount && tooManyWarnings) {
227 log.error("ESLint found too many warnings (maximum: %s).", currentOptions.maxWarnings);
228 }
229
230 return (report.errorCount || tooManyWarnings) ? 1 : 0;
231 }
232
233 return 2;
234 }
235
236 return 0;
237 }
238};
239
240module.exports = cli;