UNPKG

7.57 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 options = require("./options"),
21 CLIEngine = require("./cli-engine"),
22 mkdirp = require("mkdirp"),
23 log = require("./util/logging");
24
25const debug = require("debug")("eslint:cli");
26
27//------------------------------------------------------------------------------
28// Helpers
29//------------------------------------------------------------------------------
30
31/**
32 * Predicate function for whether or not to apply fixes in quiet mode.
33 * If a message is a warning, do not apply a fix.
34 * @param {LintResult} lintResult The lint result.
35 * @returns {boolean} True if the lint message is an error (and thus should be
36 * autofixed), false otherwise.
37 */
38function quietFixPredicate(lintResult) {
39 return lintResult.severity === 2;
40}
41
42/**
43 * Translates the CLI options into the options expected by the CLIEngine.
44 * @param {Object} cliOptions The CLI options to translate.
45 * @returns {CLIEngineOptions} The options object for the CLIEngine.
46 * @private
47 */
48function translateOptions(cliOptions) {
49 return {
50 envs: cliOptions.env,
51 extensions: cliOptions.ext,
52 rules: cliOptions.rule,
53 plugins: cliOptions.plugin,
54 globals: cliOptions.global,
55 ignore: cliOptions.ignore,
56 ignorePath: cliOptions.ignorePath,
57 ignorePattern: cliOptions.ignorePattern,
58 configFile: cliOptions.config,
59 rulePaths: cliOptions.rulesdir,
60 useEslintrc: cliOptions.eslintrc,
61 parser: cliOptions.parser,
62 parserOptions: cliOptions.parserOptions,
63 cache: cliOptions.cache,
64 cacheFile: cliOptions.cacheFile,
65 cacheLocation: cliOptions.cacheLocation,
66 fix: (cliOptions.fix || cliOptions.fixDryRun) && (cliOptions.quiet ? quietFixPredicate : true),
67 fixTypes: cliOptions.fixType,
68 allowInlineConfig: cliOptions.inlineConfig,
69 reportUnusedDisableDirectives: cliOptions.reportUnusedDisableDirectives
70 };
71}
72
73/**
74 * Outputs the results of the linting.
75 * @param {CLIEngine} engine The CLIEngine to use.
76 * @param {LintResult[]} results The results to print.
77 * @param {string} format The name of the formatter to use or the path to the formatter.
78 * @param {string} outputFile The path for the output file.
79 * @returns {boolean} True if the printing succeeds, false if not.
80 * @private
81 */
82function printResults(engine, results, format, outputFile) {
83 let formatter;
84
85 try {
86 formatter = engine.getFormatter(format);
87 } catch (e) {
88 log.error(e.message);
89 return false;
90 }
91
92 const output = formatter(results);
93
94 if (output) {
95 if (outputFile) {
96 const filePath = path.resolve(process.cwd(), outputFile);
97
98 if (fs.existsSync(filePath) && fs.statSync(filePath).isDirectory()) {
99 log.error("Cannot write to output file path, it is a directory: %s", outputFile);
100 return false;
101 }
102
103 try {
104 mkdirp.sync(path.dirname(filePath));
105 fs.writeFileSync(filePath, output);
106 } catch (ex) {
107 log.error("There was a problem writing the output file:\n%s", ex);
108 return false;
109 }
110 } else {
111 log.info(output);
112 }
113 }
114
115 return true;
116
117}
118
119//------------------------------------------------------------------------------
120// Public Interface
121//------------------------------------------------------------------------------
122
123/**
124 * Encapsulates all CLI behavior for eslint. Makes it easier to test as well as
125 * for other Node.js programs to effectively run the CLI.
126 */
127const cli = {
128
129 /**
130 * Executes the CLI based on an array of arguments that is passed in.
131 * @param {string|Array|Object} args The arguments to process.
132 * @param {string} [text] The text to lint (used for TTY).
133 * @returns {int} The exit code for the operation.
134 */
135 execute(args, text) {
136 if (Array.isArray(args)) {
137 debug("CLI args: %o", args.slice(2));
138 }
139
140 let currentOptions;
141
142 try {
143 currentOptions = options.parse(args);
144 } catch (error) {
145 log.error(error.message);
146 return 2;
147 }
148
149 const files = currentOptions._;
150
151 const useStdin = typeof text === "string";
152
153 if (currentOptions.version) { // version from package.json
154
155 log.info(`v${require("../package.json").version}`);
156
157 } else if (currentOptions.printConfig) {
158 if (files.length) {
159 log.error("The --print-config option must be used with exactly one file name.");
160 return 2;
161 }
162 if (useStdin) {
163 log.error("The --print-config option is not available for piped-in code.");
164 return 2;
165 }
166
167 const engine = new CLIEngine(translateOptions(currentOptions));
168
169 const fileConfig = engine.getConfigForFile(currentOptions.printConfig);
170
171 log.info(JSON.stringify(fileConfig, null, " "));
172 return 0;
173 } else if (currentOptions.help || (!files.length && !useStdin)) {
174
175 log.info(options.generateHelp());
176
177 } else {
178
179 debug(`Running on ${useStdin ? "text" : "files"}`);
180
181 if (currentOptions.fix && currentOptions.fixDryRun) {
182 log.error("The --fix option and the --fix-dry-run option cannot be used together.");
183 return 2;
184 }
185
186 if (useStdin && currentOptions.fix) {
187 log.error("The --fix option is not available for piped-in code; use --fix-dry-run instead.");
188 return 2;
189 }
190
191 if (currentOptions.fixType && !currentOptions.fix && !currentOptions.fixDryRun) {
192 log.error("The --fix-type option requires either --fix or --fix-dry-run.");
193 return 2;
194 }
195
196 const engine = new CLIEngine(translateOptions(currentOptions));
197 const report = useStdin ? engine.executeOnText(text, currentOptions.stdinFilename, true) : engine.executeOnFiles(files);
198
199 if (currentOptions.fix) {
200 debug("Fix mode enabled - applying fixes");
201 CLIEngine.outputFixes(report);
202 }
203
204 if (currentOptions.quiet) {
205 debug("Quiet mode enabled - filtering out warnings");
206 report.results = CLIEngine.getErrorResults(report.results);
207 }
208
209 if (printResults(engine, report.results, currentOptions.format, currentOptions.outputFile)) {
210 const tooManyWarnings = currentOptions.maxWarnings >= 0 && report.warningCount > currentOptions.maxWarnings;
211
212 if (!report.errorCount && tooManyWarnings) {
213 log.error("ESLint found too many warnings (maximum: %s).", currentOptions.maxWarnings);
214 }
215
216 return (report.errorCount || tooManyWarnings) ? 1 : 0;
217 }
218 return 2;
219
220
221 }
222
223 return 0;
224 }
225};
226
227module.exports = cli;