2 * @fileoverview Config initialization wizard.
9 //------------------------------------------------------------------------------
11 //------------------------------------------------------------------------------
13 const util = require("util"),
14 path = require("path"),
16 enquirer = require("enquirer"),
17 ProgressBar = require("progress"),
18 semver = require("semver"),
19 espree = require("espree"),
20 recConfig = require("../../conf/eslint-recommended"),
21 ConfigOps = require("@eslint/eslintrc/lib/shared/config-ops"),
22 log = require("../shared/logging"),
23 naming = require("@eslint/eslintrc/lib/shared/naming"),
24 ModuleResolver = require("../shared/relative-module-resolver"),
25 autoconfig = require("./autoconfig.js"),
26 ConfigFile = require("./config-file"),
27 npmUtils = require("./npm-utils"),
28 { getSourceCodeOfFiles } = require("./source-code-utils");
30 const debug = require("debug")("eslint:config-initializer");
32 //------------------------------------------------------------------------------
34 //------------------------------------------------------------------------------
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") {
52 } else if (format === "JavaScript") {
53 const pkgJSONPath = npmUtils.findPackageJson();
56 const pkgJSONContents = JSON.parse(fs.readFileSync(pkgJSONPath, "utf8"));
58 if (pkgJSONContents.type === "module") {
64 const installedESLint = config.installedESLint;
66 delete config.installedESLint;
68 ConfigFile.write(config, `./.eslintrc${extname}`);
69 log.info(`Successfully created .eslintrc${extname} file in ${process.cwd()}`);
71 if (installedESLint) {
72 log.info("ESLint was installed locally. We recommend using this local copy instead of your globally-installed copy.");
77 * Get the peer dependencies of the given module.
78 * This adds the gotten value to cache at the first time, then reuses it.
79 * In a process, this function is called twice, but `npmUtils.fetchPeerDependencies` needs to access network which is relatively slow.
80 * @param {string} moduleName The module name to get.
81 * @returns {Object} The peer dependencies of the given module.
82 * This object is the object of `peerDependencies` field of `package.json`.
83 * Returns null if npm was not found.
85 function getPeerDependencies(moduleName) {
86 let result = getPeerDependencies.cache.get(moduleName);
89 log.info(`Checking peerDependencies of ${moduleName}`);
91 result = npmUtils.fetchPeerDependencies(moduleName);
92 getPeerDependencies.cache.set(moduleName, result);
97 getPeerDependencies.cache = new Map();
100 * Return necessary plugins, configs, parsers, etc. based on the config
101 * @param {Object} config config object
102 * @param {boolean} [installESLint=true] If `false` is given, it does not install eslint.
103 * @returns {string[]} An array of modules to be installed.
105 function getModulesList(config, installESLint) {
108 // Create a list of modules which should be installed based on config
109 if (config.plugins) {
110 for (const plugin of config.plugins) {
111 const moduleName = naming.normalizePackageName(plugin, "eslint-plugin");
113 modules[moduleName] = "latest";
116 if (config.extends) {
117 const extendList = Array.isArray(config.extends) ? config.extends : [config.extends];
119 for (const extend of extendList) {
120 if (extend.startsWith("eslint:") || extend.startsWith("plugin:")) {
123 const moduleName = naming.normalizePackageName(extend, "eslint-config");
125 modules[moduleName] = "latest";
128 getPeerDependencies(`${moduleName}@latest`)
133 const parser = config.parser || (config.parserOptions && config.parserOptions.parser);
136 modules[parser] = "latest";
139 if (installESLint === false) {
140 delete modules.eslint;
142 const installStatus = npmUtils.checkDevDeps(["eslint"]);
144 // Mark to show messages if it's new installation of eslint.
145 if (installStatus.eslint === false) {
146 log.info("Local ESLint installation not found.");
147 modules.eslint = modules.eslint || "latest";
148 config.installedESLint = true;
152 return Object.keys(modules).map(name => `${name}@${modules[name]}`);
156 * Set the `rules` of a config by examining a user's source code
158 * Note: This clones the config object and returns a new config to avoid mutating
159 * the original config parameter.
160 * @param {Object} answers answers received from enquirer
161 * @param {Object} config config object
162 * @returns {Object} config object with configured rules
164 function configureRules(answers, config) {
165 const BAR_TOTAL = 20,
166 BAR_SOURCE_CODE_TOTAL = 4,
167 newConfig = Object.assign({}, config),
168 disabledConfigs = {};
172 // Set up a progress bar, as this process can take a long time
173 const bar = new ProgressBar("Determining Config: :percent [:bar] :elapseds elapsed, eta :etas ", {
178 bar.tick(0); // Shows the progress bar
180 // Get the SourceCode of all chosen files
181 const patterns = answers.patterns.split(/[\s]+/u);
184 sourceCodes = getSourceCodeOfFiles(patterns, { baseConfig: newConfig, useEslintrc: false }, total => {
185 bar.tick((BAR_SOURCE_CODE_TOTAL / total));
191 const fileQty = Object.keys(sourceCodes).length;
195 throw new Error("Automatic Configuration failed. No files were able to be parsed.");
198 // Create a registry of rule configs
199 registry = new autoconfig.Registry();
200 registry.populateFromCoreRules();
202 // Lint all files with each rule config in the registry
203 registry = registry.lintSourceCode(sourceCodes, newConfig, total => {
204 bar.tick((BAR_TOTAL - BAR_SOURCE_CODE_TOTAL) / total); // Subtract out ticks used at beginning
206 debug(`\nRegistry: ${util.inspect(registry.rules, { depth: null })}`);
208 // Create a list of recommended rules, because we don't want to disable them
209 const recRules = Object.keys(recConfig.rules).filter(ruleId => ConfigOps.isErrorSeverity(recConfig.rules[ruleId]));
211 // Find and disable rules which had no error-free configuration
212 const failingRegistry = registry.getFailingRulesRegistry();
214 Object.keys(failingRegistry.rules).forEach(ruleId => {
216 // If the rule is recommended, set it to error, otherwise disable it
217 disabledConfigs[ruleId] = (recRules.indexOf(ruleId) !== -1) ? 2 : 0;
220 // Now that we know which rules to disable, strip out configs with errors
221 registry = registry.stripFailingConfigs();
224 * If there is only one config that results in no errors for a rule, we should use it.
225 * createConfig will only add rules that have one configuration in the registry.
227 const singleConfigs = registry.createConfig().rules;
230 * The "sweet spot" for number of options in a config seems to be two (severity plus one option).
231 * Very often, a third option (usually an object) is available to address
232 * edge cases, exceptions, or unique situations. We will prefer to use a config with
233 * specificity of two.
235 const specTwoConfigs = registry.filterBySpecificity(2).createConfig().rules;
237 // Maybe a specific combination using all three options works
238 const specThreeConfigs = registry.filterBySpecificity(3).createConfig().rules;
240 // If all else fails, try to use the default (severity only)
241 const defaultConfigs = registry.filterBySpecificity(1).createConfig().rules;
243 // Combine configs in reverse priority order (later take precedence)
244 newConfig.rules = Object.assign({}, disabledConfigs, defaultConfigs, specThreeConfigs, specTwoConfigs, singleConfigs);
246 // Make sure progress bar has finished (floating point rounding)
247 bar.update(BAR_TOTAL);
249 // Log out some stats to let the user know what happened
250 const finalRuleIds = Object.keys(newConfig.rules);
251 const totalRules = finalRuleIds.length;
252 const enabledRules = finalRuleIds.filter(ruleId => (newConfig.rules[ruleId] !== 0)).length;
253 const resultMessage = [
254 `\nEnabled ${enabledRules} out of ${totalRules}`,
255 `rules based on ${fileQty}`,
256 `file${(fileQty === 1) ? "." : "s."}`
259 log.info(resultMessage);
261 ConfigOps.normalizeToStrings(newConfig);
266 * process user's answers and create config object
267 * @param {Object} answers answers received from enquirer
268 * @returns {Object} config object
270 function processAnswers(answers) {
278 config.parserOptions.ecmaVersion = espree.latestEcmaVersion;
279 config.env.es2021 = true;
281 // set the module type
282 if (answers.moduleType === "esm") {
283 config.parserOptions.sourceType = "module";
284 } else if (answers.moduleType === "commonjs") {
285 config.env.commonjs = true;
288 // add in browser and node environments if necessary
289 answers.env.forEach(env => {
290 config.env[env] = true;
293 // add in library information
294 if (answers.framework === "react") {
295 config.parserOptions.ecmaFeatures = {
298 config.plugins = ["react"];
299 config.extends.push("plugin:react/recommended");
300 } else if (answers.framework === "vue") {
301 config.plugins = ["vue"];
302 config.extends.push("plugin:vue/essential");
305 if (answers.typescript) {
306 if (answers.framework === "vue") {
307 config.parserOptions.parser = "@typescript-eslint/parser";
309 config.parser = "@typescript-eslint/parser";
312 if (Array.isArray(config.plugins)) {
313 config.plugins.push("@typescript-eslint");
315 config.plugins = ["@typescript-eslint"];
319 // setup rules based on problems/style enforcement preferences
320 if (answers.purpose === "problems") {
321 config.extends.unshift("eslint:recommended");
322 } else if (answers.purpose === "style") {
323 if (answers.source === "prompt") {
324 config.extends.unshift("eslint:recommended");
325 config.rules.indent = ["error", answers.indent];
326 config.rules.quotes = ["error", answers.quotes];
327 config.rules["linebreak-style"] = ["error", answers.linebreak];
328 config.rules.semi = ["error", answers.semi ? "always" : "never"];
329 } else if (answers.source === "auto") {
330 config = configureRules(answers, config);
331 config = autoconfig.extendFromRecommended(config);
334 if (answers.typescript && config.extends.includes("eslint:recommended")) {
335 config.extends.push("plugin:@typescript-eslint/recommended");
339 if (config.extends.length === 0) {
340 delete config.extends;
341 } else if (config.extends.length === 1) {
342 config.extends = config.extends[0];
345 ConfigOps.normalizeToStrings(config);
350 * Get the version of the local ESLint.
351 * @returns {string|null} The version. If the local ESLint was not found, returns null.
353 function getLocalESLintVersion() {
355 const eslintPath = ModuleResolver.resolve("eslint", path.join(process.cwd(), "__placeholder__.js"));
356 const eslint = require(eslintPath);
358 return eslint.linter.version || null;
365 * Get the shareable config name of the chosen style guide.
366 * @param {Object} answers The answers object.
367 * @returns {string} The shareable config name.
369 function getStyleGuideName(answers) {
370 if (answers.styleguide === "airbnb" && answers.framework !== "react") {
371 return "airbnb-base";
373 return answers.styleguide;
377 * Check whether the local ESLint version conflicts with the required version of the chosen shareable config.
378 * @param {Object} answers The answers object.
379 * @returns {boolean} `true` if the local ESLint is found then it conflicts with the required version of the chosen shareable config.
381 function hasESLintVersionConflict(answers) {
383 // Get the local ESLint version.
384 const localESLintVersion = getLocalESLintVersion();
386 if (!localESLintVersion) {
390 // Get the required range of ESLint version.
391 const configName = getStyleGuideName(answers);
392 const moduleName = `eslint-config-${configName}@latest`;
393 const peerDependencies = getPeerDependencies(moduleName) || {};
394 const requiredESLintVersionRange = peerDependencies.eslint;
396 if (!requiredESLintVersionRange) {
400 answers.localESLintVersion = localESLintVersion;
401 answers.requiredESLintVersionRange = requiredESLintVersionRange;
403 // Check the version.
404 if (semver.satisfies(localESLintVersion, requiredESLintVersionRange)) {
405 answers.installESLint = false;
414 * @param {string[]} modules Modules to be installed.
417 function installModules(modules) {
418 log.info(`Installing ${modules.join(", ")}`);
419 npmUtils.installSyncSaveDev(modules);
422 /* istanbul ignore next: no need to test enquirer */
424 * Ask user to install modules.
425 * @param {string[]} modules Array of modules to be installed.
426 * @param {boolean} packageJsonExists Indicates if package.json is existed.
427 * @returns {Promise} Answer that indicates if user wants to install.
429 function askInstallModules(modules, packageJsonExists) {
431 // If no modules, do nothing.
432 if (modules.length === 0) {
433 return Promise.resolve();
436 log.info("The config that you've selected requires the following dependencies:\n");
437 log.info(modules.join(" "));
438 return enquirer.prompt([
441 name: "executeInstallation",
442 message: "Would you like to install them now with npm?",
447 return !(modules.length && packageJsonExists);
450 return this.skipped ? null : input;
453 ]).then(({ executeInstallation }) => {
454 if (executeInstallation) {
455 installModules(modules);
460 /* istanbul ignore next: no need to test enquirer */
462 * Ask use a few questions on command prompt
463 * @returns {Promise} The promise with the result of the prompt
465 function promptUser() {
467 return enquirer.prompt([
471 message: "How would you like to use ESLint?",
473 // The returned number matches the name value of nth in the choices array.
476 { message: "To check syntax only", name: "syntax" },
477 { message: "To check syntax and find problems", name: "problems" },
478 { message: "To check syntax, find problems, and enforce code style", name: "style" }
484 message: "What type of modules does your project use?",
487 { message: "JavaScript modules (import/export)", name: "esm" },
488 { message: "CommonJS (require/exports)", name: "commonjs" },
489 { message: "None of these", name: "none" }
495 message: "Which framework does your project use?",
498 { message: "React", name: "react" },
499 { message: "Vue.js", name: "vue" },
500 { message: "None of these", name: "none" }
506 message: "Does your project use TypeScript?",
514 message: "Where does your code run?",
515 hint: "(Press <space> to select, <a> to toggle all, <i> to invert selection)",
518 { message: "Browser", name: "browser" },
519 { message: "Node", name: "node" }
525 message: "How would you like to define a style for your project?",
527 { message: "Use a popular style guide", name: "guide" },
528 { message: "Answer questions about your style", name: "prompt" },
529 { message: "Inspect your JavaScript file(s)", name: "auto" }
532 return this.state.answers.purpose !== "style";
535 return this.skipped ? null : input;
541 message: "Which style guide do you want to follow?",
543 { message: "Airbnb: https://github.com/airbnb/javascript", name: "airbnb" },
544 { message: "Standard: https://github.com/standard/standard", name: "standard" },
545 { message: "Google: https://github.com/google/eslint-config-google", name: "google" },
546 { message: "XO: https://github.com/xojs/eslint-config-xo", name: "xo" }
549 this.state.answers.packageJsonExists = npmUtils.checkPackageJson();
550 return !(this.state.answers.source === "guide" && this.state.answers.packageJsonExists);
553 return this.skipped ? null : input;
559 message: "Which file(s), path(s), or glob(s) should be examined?",
561 return this.state.answers.source !== "auto";
564 if (!this.skipped && input.trim().length === 0 && input.trim() !== ",") {
565 return "You must tell us what code to examine. Try again.";
573 message: "What format do you want your config file to be in?",
575 choices: ["JavaScript", "YAML", "JSON"]
579 name: "installESLint",
581 const { answers } = this.state;
582 const verb = semver.ltr(answers.localESLintVersion, answers.requiredESLintVersionRange)
586 return `The style guide "${answers.styleguide}" requires eslint@${answers.requiredESLintVersionRange}. You are currently using eslint@${answers.localESLintVersion}.\n Do you want to ${verb}?`;
592 return !(this.state.answers.source === "guide" && this.state.answers.packageJsonExists && hasESLintVersionConflict(this.state.answers));
595 return this.skipped ? null : input;
598 ]).then(earlyAnswers => {
600 // early exit if no style guide is necessary
601 if (earlyAnswers.purpose !== "style") {
602 const config = processAnswers(earlyAnswers);
603 const modules = getModulesList(config);
605 return askInstallModules(modules, earlyAnswers.packageJsonExists)
606 .then(() => writeFile(config, earlyAnswers.format));
609 // early exit if you are using a style guide
610 if (earlyAnswers.source === "guide") {
611 if (!earlyAnswers.packageJsonExists) {
612 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.");
615 if (earlyAnswers.installESLint === false && !semver.satisfies(earlyAnswers.localESLintVersion, earlyAnswers.requiredESLintVersionRange)) {
616 log.info(`Note: it might not work since ESLint's version is mismatched with the ${earlyAnswers.styleguide} config.`);
618 if (earlyAnswers.styleguide === "airbnb" && earlyAnswers.framework !== "react") {
619 earlyAnswers.styleguide = "airbnb-base";
622 const config = processAnswers(earlyAnswers);
624 if (Array.isArray(config.extends)) {
625 config.extends.push(earlyAnswers.styleguide);
626 } else if (config.extends) {
627 config.extends = [config.extends, earlyAnswers.styleguide];
629 config.extends = [earlyAnswers.styleguide];
632 const modules = getModulesList(config);
634 return askInstallModules(modules, earlyAnswers.packageJsonExists)
635 .then(() => writeFile(config, earlyAnswers.format));
639 if (earlyAnswers.source === "auto") {
640 const combinedAnswers = Object.assign({}, earlyAnswers);
641 const config = processAnswers(combinedAnswers);
642 const modules = getModulesList(config);
644 return askInstallModules(modules).then(() => writeFile(config, earlyAnswers.format));
647 // continue with the style questions otherwise...
648 return enquirer.prompt([
652 message: "What style of indentation do you use?",
654 choices: [{ message: "Tabs", name: "tab" }, { message: "Spaces", name: 4 }]
659 message: "What quotes do you use for strings?",
661 choices: [{ message: "Double", name: "double" }, { message: "Single", name: "single" }]
666 message: "What line endings do you use?",
668 choices: [{ message: "Unix", name: "unix" }, { message: "Windows", name: "windows" }]
673 message: "Do you require semicolons?",
679 const totalAnswers = Object.assign({}, earlyAnswers, answers);
681 const config = processAnswers(totalAnswers);
682 const modules = getModulesList(config);
684 return askInstallModules(modules).then(() => writeFile(config, earlyAnswers.format));
689 //------------------------------------------------------------------------------
691 //------------------------------------------------------------------------------
695 hasESLintVersionConflict,
699 /* istanbul ignore next */initializeConfig() {
704 module.exports = init;