2 * @fileoverview Config initialization wizard.
9 //------------------------------------------------------------------------------
11 //------------------------------------------------------------------------------
13 const util = require("util"),
14 path = require("path"),
15 inquirer = require("inquirer"),
16 ProgressBar = require("progress"),
17 semver = require("semver"),
18 recConfig = require("../../conf/eslint-recommended"),
19 ConfigOps = require("../shared/config-ops"),
20 log = require("../shared/logging"),
21 naming = require("../shared/naming"),
22 ModuleResolver = require("../shared/relative-module-resolver"),
23 autoconfig = require("./autoconfig.js"),
24 ConfigFile = require("./config-file"),
25 npmUtils = require("./npm-utils"),
26 { getSourceCodeOfFiles } = require("./source-code-utils");
28 const debug = require("debug")("eslint:config-initializer");
30 //------------------------------------------------------------------------------
32 //------------------------------------------------------------------------------
34 const DEFAULT_ECMA_VERSION = 2018;
36 /* istanbul ignore next: hard to test fs function */
38 * Create .eslintrc file in the current working directory
39 * @param {Object} config object that contains user's answers
40 * @param {string} format The file format to write to.
43 function writeFile(config, format) {
48 if (format === "YAML") {
50 } else if (format === "JSON") {
54 const installedESLint = config.installedESLint;
56 delete config.installedESLint;
58 ConfigFile.write(config, `./.eslintrc${extname}`);
59 log.info(`Successfully created .eslintrc${extname} file in ${process.cwd()}`);
61 if (installedESLint) {
62 log.info("ESLint was installed locally. We recommend using this local copy instead of your globally-installed copy.");
67 * Get the peer dependencies of the given module.
68 * This adds the gotten value to cache at the first time, then reuses it.
69 * In a process, this function is called twice, but `npmUtils.fetchPeerDependencies` needs to access network which is relatively slow.
70 * @param {string} moduleName The module name to get.
71 * @returns {Object} The peer dependencies of the given module.
72 * This object is the object of `peerDependencies` field of `package.json`.
73 * Returns null if npm was not found.
75 function getPeerDependencies(moduleName) {
76 let result = getPeerDependencies.cache.get(moduleName);
79 log.info(`Checking peerDependencies of ${moduleName}`);
81 result = npmUtils.fetchPeerDependencies(moduleName);
82 getPeerDependencies.cache.set(moduleName, result);
87 getPeerDependencies.cache = new Map();
90 * Return necessary plugins, configs, parsers, etc. based on the config
91 * @param {Object} config config object
92 * @param {boolean} [installESLint=true] If `false` is given, it does not install eslint.
93 * @returns {string[]} An array of modules to be installed.
95 function getModulesList(config, installESLint) {
98 // Create a list of modules which should be installed based on config
100 for (const plugin of config.plugins) {
101 const moduleName = naming.normalizePackageName(plugin, "eslint-plugin");
103 modules[moduleName] = "latest";
106 if (config.extends) {
107 const extendList = Array.isArray(config.extends) ? config.extends : [config.extends];
109 for (const extend of extendList) {
110 if (extend.startsWith("eslint:") || extend.startsWith("plugin:")) {
113 const moduleName = naming.normalizePackageName(extend, "eslint-config");
115 modules[moduleName] = "latest";
118 getPeerDependencies(`${moduleName}@latest`)
123 const parser = config.parser || (config.parserOptions && config.parserOptions.parser);
126 modules[parser] = "latest";
129 if (installESLint === false) {
130 delete modules.eslint;
132 const installStatus = npmUtils.checkDevDeps(["eslint"]);
134 // Mark to show messages if it's new installation of eslint.
135 if (installStatus.eslint === false) {
136 log.info("Local ESLint installation not found.");
137 modules.eslint = modules.eslint || "latest";
138 config.installedESLint = true;
142 return Object.keys(modules).map(name => `${name}@${modules[name]}`);
146 * Set the `rules` of a config by examining a user's source code
148 * Note: This clones the config object and returns a new config to avoid mutating
149 * the original config parameter.
150 * @param {Object} answers answers received from inquirer
151 * @param {Object} config config object
152 * @returns {Object} config object with configured rules
154 function configureRules(answers, config) {
155 const BAR_TOTAL = 20,
156 BAR_SOURCE_CODE_TOTAL = 4,
157 newConfig = Object.assign({}, config),
158 disabledConfigs = {};
162 // Set up a progress bar, as this process can take a long time
163 const bar = new ProgressBar("Determining Config: :percent [:bar] :elapseds elapsed, eta :etas ", {
168 bar.tick(0); // Shows the progress bar
170 // Get the SourceCode of all chosen files
171 const patterns = answers.patterns.split(/[\s]+/u);
174 sourceCodes = getSourceCodeOfFiles(patterns, { baseConfig: newConfig, useEslintrc: false }, total => {
175 bar.tick((BAR_SOURCE_CODE_TOTAL / total));
181 const fileQty = Object.keys(sourceCodes).length;
185 throw new Error("Automatic Configuration failed. No files were able to be parsed.");
188 // Create a registry of rule configs
189 registry = new autoconfig.Registry();
190 registry.populateFromCoreRules();
192 // Lint all files with each rule config in the registry
193 registry = registry.lintSourceCode(sourceCodes, newConfig, total => {
194 bar.tick((BAR_TOTAL - BAR_SOURCE_CODE_TOTAL) / total); // Subtract out ticks used at beginning
196 debug(`\nRegistry: ${util.inspect(registry.rules, { depth: null })}`);
198 // Create a list of recommended rules, because we don't want to disable them
199 const recRules = Object.keys(recConfig.rules).filter(ruleId => ConfigOps.isErrorSeverity(recConfig.rules[ruleId]));
201 // Find and disable rules which had no error-free configuration
202 const failingRegistry = registry.getFailingRulesRegistry();
204 Object.keys(failingRegistry.rules).forEach(ruleId => {
206 // If the rule is recommended, set it to error, otherwise disable it
207 disabledConfigs[ruleId] = (recRules.indexOf(ruleId) !== -1) ? 2 : 0;
210 // Now that we know which rules to disable, strip out configs with errors
211 registry = registry.stripFailingConfigs();
214 * If there is only one config that results in no errors for a rule, we should use it.
215 * createConfig will only add rules that have one configuration in the registry.
217 const singleConfigs = registry.createConfig().rules;
220 * The "sweet spot" for number of options in a config seems to be two (severity plus one option).
221 * Very often, a third option (usually an object) is available to address
222 * edge cases, exceptions, or unique situations. We will prefer to use a config with
223 * specificity of two.
225 const specTwoConfigs = registry.filterBySpecificity(2).createConfig().rules;
227 // Maybe a specific combination using all three options works
228 const specThreeConfigs = registry.filterBySpecificity(3).createConfig().rules;
230 // If all else fails, try to use the default (severity only)
231 const defaultConfigs = registry.filterBySpecificity(1).createConfig().rules;
233 // Combine configs in reverse priority order (later take precedence)
234 newConfig.rules = Object.assign({}, disabledConfigs, defaultConfigs, specThreeConfigs, specTwoConfigs, singleConfigs);
236 // Make sure progress bar has finished (floating point rounding)
237 bar.update(BAR_TOTAL);
239 // Log out some stats to let the user know what happened
240 const finalRuleIds = Object.keys(newConfig.rules);
241 const totalRules = finalRuleIds.length;
242 const enabledRules = finalRuleIds.filter(ruleId => (newConfig.rules[ruleId] !== 0)).length;
243 const resultMessage = [
244 `\nEnabled ${enabledRules} out of ${totalRules}`,
245 `rules based on ${fileQty}`,
246 `file${(fileQty === 1) ? "." : "s."}`
249 log.info(resultMessage);
251 ConfigOps.normalizeToStrings(newConfig);
256 * process user's answers and create config object
257 * @param {Object} answers answers received from inquirer
258 * @returns {Object} config object
260 function processAnswers(answers) {
268 // set the latest ECMAScript version
269 config.parserOptions.ecmaVersion = DEFAULT_ECMA_VERSION;
270 config.env.es6 = true;
273 SharedArrayBuffer: "readonly"
276 // set the module type
277 if (answers.moduleType === "esm") {
278 config.parserOptions.sourceType = "module";
279 } else if (answers.moduleType === "commonjs") {
280 config.env.commonjs = true;
283 // add in browser and node environments if necessary
284 answers.env.forEach(env => {
285 config.env[env] = true;
288 // add in library information
289 if (answers.framework === "react") {
290 config.parserOptions.ecmaFeatures = {
293 config.plugins = ["react"];
294 config.extends.push("plugin:react/recommended");
295 } else if (answers.framework === "vue") {
296 config.plugins = ["vue"];
297 config.extends.push("plugin:vue/essential");
300 if (answers.typescript) {
301 if (answers.framework === "vue") {
302 config.parserOptions.parser = "@typescript-eslint/parser";
304 config.parser = "@typescript-eslint/parser";
307 if (Array.isArray(config.plugins)) {
308 config.plugins.push("@typescript-eslint");
310 config.plugins = ["@typescript-eslint"];
314 // setup rules based on problems/style enforcement preferences
315 if (answers.purpose === "problems") {
316 config.extends.unshift("eslint:recommended");
317 } else if (answers.purpose === "style") {
318 if (answers.source === "prompt") {
319 config.extends.unshift("eslint:recommended");
320 config.rules.indent = ["error", answers.indent];
321 config.rules.quotes = ["error", answers.quotes];
322 config.rules["linebreak-style"] = ["error", answers.linebreak];
323 config.rules.semi = ["error", answers.semi ? "always" : "never"];
324 } else if (answers.source === "auto") {
325 config = configureRules(answers, config);
326 config = autoconfig.extendFromRecommended(config);
329 if (answers.typescript && config.extends.includes("eslint:recommended")) {
330 config.extends.push("plugin:@typescript-eslint/eslint-recommended");
334 if (config.extends.length === 0) {
335 delete config.extends;
336 } else if (config.extends.length === 1) {
337 config.extends = config.extends[0];
340 ConfigOps.normalizeToStrings(config);
345 * Get the version of the local ESLint.
346 * @returns {string|null} The version. If the local ESLint was not found, returns null.
348 function getLocalESLintVersion() {
350 const eslintPath = ModuleResolver.resolve("eslint", path.join(process.cwd(), "__placeholder__.js"));
351 const eslint = require(eslintPath);
353 return eslint.linter.version || null;
360 * Get the shareable config name of the chosen style guide.
361 * @param {Object} answers The answers object.
362 * @returns {string} The shareable config name.
364 function getStyleGuideName(answers) {
365 if (answers.styleguide === "airbnb" && answers.framework !== "react") {
366 return "airbnb-base";
368 return answers.styleguide;
372 * Check whether the local ESLint version conflicts with the required version of the chosen shareable config.
373 * @param {Object} answers The answers object.
374 * @returns {boolean} `true` if the local ESLint is found then it conflicts with the required version of the chosen shareable config.
376 function hasESLintVersionConflict(answers) {
378 // Get the local ESLint version.
379 const localESLintVersion = getLocalESLintVersion();
381 if (!localESLintVersion) {
385 // Get the required range of ESLint version.
386 const configName = getStyleGuideName(answers);
387 const moduleName = `eslint-config-${configName}@latest`;
388 const peerDependencies = getPeerDependencies(moduleName) || {};
389 const requiredESLintVersionRange = peerDependencies.eslint;
391 if (!requiredESLintVersionRange) {
395 answers.localESLintVersion = localESLintVersion;
396 answers.requiredESLintVersionRange = requiredESLintVersionRange;
398 // Check the version.
399 if (semver.satisfies(localESLintVersion, requiredESLintVersionRange)) {
400 answers.installESLint = false;
409 * @param {string[]} modules Modules to be installed.
412 function installModules(modules) {
413 log.info(`Installing ${modules.join(", ")}`);
414 npmUtils.installSyncSaveDev(modules);
417 /* istanbul ignore next: no need to test inquirer */
419 * Ask user to install modules.
420 * @param {string[]} modules Array of modules to be installed.
421 * @param {boolean} packageJsonExists Indicates if package.json is existed.
422 * @returns {Promise} Answer that indicates if user wants to install.
424 function askInstallModules(modules, packageJsonExists) {
426 // If no modules, do nothing.
427 if (modules.length === 0) {
428 return Promise.resolve();
431 log.info("The config that you've selected requires the following dependencies:\n");
432 log.info(modules.join(" "));
433 return inquirer.prompt([
436 name: "executeInstallation",
437 message: "Would you like to install them now with npm?",
440 return modules.length && packageJsonExists;
443 ]).then(({ executeInstallation }) => {
444 if (executeInstallation) {
445 installModules(modules);
450 /* istanbul ignore next: no need to test inquirer */
452 * Ask use a few questions on command prompt
453 * @returns {Promise} The promise with the result of the prompt
455 function promptUser() {
457 return inquirer.prompt([
461 message: "How would you like to use ESLint?",
464 { name: "To check syntax only", value: "syntax" },
465 { name: "To check syntax and find problems", value: "problems" },
466 { name: "To check syntax, find problems, and enforce code style", value: "style" }
472 message: "What type of modules does your project use?",
475 { name: "JavaScript modules (import/export)", value: "esm" },
476 { name: "CommonJS (require/exports)", value: "commonjs" },
477 { name: "None of these", value: "none" }
483 message: "Which framework does your project use?",
486 { name: "React", value: "react" },
487 { name: "Vue.js", value: "vue" },
488 { name: "None of these", value: "none" }
494 message: "Does your project use TypeScript?",
500 message: "Where does your code run?",
501 default: ["browser"],
503 { name: "Browser", value: "browser" },
504 { name: "Node", value: "node" }
510 message: "How would you like to define a style for your project?",
513 { name: "Use a popular style guide", value: "guide" },
514 { name: "Answer questions about your style", value: "prompt" },
515 { name: "Inspect your JavaScript file(s)", value: "auto" }
518 return answers.purpose === "style";
524 message: "Which style guide do you want to follow?",
526 { name: "Airbnb: https://github.com/airbnb/javascript", value: "airbnb" },
527 { name: "Standard: https://github.com/standard/standard", value: "standard" },
528 { name: "Google: https://github.com/google/eslint-config-google", value: "google" }
531 answers.packageJsonExists = npmUtils.checkPackageJson();
532 return answers.source === "guide" && answers.packageJsonExists;
538 message: "Which file(s), path(s), or glob(s) should be examined?",
540 return (answers.source === "auto");
543 if (input.trim().length === 0 && input.trim() !== ",") {
544 return "You must tell us what code to examine. Try again.";
552 message: "What format do you want your config file to be in?",
553 default: "JavaScript",
554 choices: ["JavaScript", "YAML", "JSON"]
558 name: "installESLint",
560 const verb = semver.ltr(answers.localESLintVersion, answers.requiredESLintVersionRange)
564 return `The style guide "${answers.styleguide}" requires eslint@${answers.requiredESLintVersionRange}. You are currently using eslint@${answers.localESLintVersion}.\n Do you want to ${verb}?`;
568 return answers.source === "guide" && answers.packageJsonExists && hasESLintVersionConflict(answers);
571 ]).then(earlyAnswers => {
573 // early exit if no style guide is necessary
574 if (earlyAnswers.purpose !== "style") {
575 const config = processAnswers(earlyAnswers);
576 const modules = getModulesList(config);
578 return askInstallModules(modules, earlyAnswers.packageJsonExists)
579 .then(() => writeFile(config, earlyAnswers.format));
582 // early exit if you are using a style guide
583 if (earlyAnswers.source === "guide") {
584 if (!earlyAnswers.packageJsonExists) {
585 log.info("A package.json is necessary to install plugins such as style guides. Run `npm init` to create a package.json file and try again.");
588 if (earlyAnswers.installESLint === false && !semver.satisfies(earlyAnswers.localESLintVersion, earlyAnswers.requiredESLintVersionRange)) {
589 log.info(`Note: it might not work since ESLint's version is mismatched with the ${earlyAnswers.styleguide} config.`);
591 if (earlyAnswers.styleguide === "airbnb" && earlyAnswers.framework !== "react") {
592 earlyAnswers.styleguide = "airbnb-base";
595 const config = processAnswers(earlyAnswers);
597 if (Array.isArray(config.extends)) {
598 config.extends.push(earlyAnswers.styleguide);
599 } else if (config.extends) {
600 config.extends = [config.extends, earlyAnswers.styleguide];
602 config.extends = [earlyAnswers.styleguide];
605 const modules = getModulesList(config);
607 return askInstallModules(modules, earlyAnswers.packageJsonExists)
608 .then(() => writeFile(config, earlyAnswers.format));
612 if (earlyAnswers.source === "auto") {
613 const combinedAnswers = Object.assign({}, earlyAnswers);
614 const config = processAnswers(combinedAnswers);
615 const modules = getModulesList(config);
617 return askInstallModules(modules).then(() => writeFile(config, earlyAnswers.format));
620 // continue with the style questions otherwise...
621 return inquirer.prompt([
625 message: "What style of indentation do you use?",
627 choices: [{ name: "Tabs", value: "tab" }, { name: "Spaces", value: 4 }]
632 message: "What quotes do you use for strings?",
634 choices: [{ name: "Double", value: "double" }, { name: "Single", value: "single" }]
639 message: "What line endings do you use?",
641 choices: [{ name: "Unix", value: "unix" }, { name: "Windows", value: "windows" }]
646 message: "Do you require semicolons?",
650 const totalAnswers = Object.assign({}, earlyAnswers, answers);
652 const config = processAnswers(totalAnswers);
653 const modules = getModulesList(config);
655 return askInstallModules(modules).then(() => writeFile(config, earlyAnswers.format));
660 //------------------------------------------------------------------------------
662 //------------------------------------------------------------------------------
666 hasESLintVersionConflict,
669 /* istanbul ignore next */initializeConfig() {
674 module.exports = init;