massive update, probably broken
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / eslint / lib / init / config-initializer.js
1 /**
2  * @fileoverview Config initialization wizard.
3  * @author Ilya Volodin
4  */
5
6
7 "use strict";
8
9 //------------------------------------------------------------------------------
10 // Requirements
11 //------------------------------------------------------------------------------
12
13 const util = require("util"),
14     path = require("path"),
15     fs = require("fs"),
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");
29
30 const debug = require("debug")("eslint:config-initializer");
31
32 //------------------------------------------------------------------------------
33 // Private
34 //------------------------------------------------------------------------------
35
36 /* istanbul ignore next: hard to test fs function */
37 /**
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.
41  * @returns {void}
42  */
43 function writeFile(config, format) {
44
45     // default is .js
46     let extname = ".js";
47
48     if (format === "YAML") {
49         extname = ".yml";
50     } else if (format === "JSON") {
51         extname = ".json";
52     } else if (format === "JavaScript") {
53         const pkgJSONPath = npmUtils.findPackageJson();
54
55         if (pkgJSONPath) {
56             const pkgJSONContents = JSON.parse(fs.readFileSync(pkgJSONPath, "utf8"));
57
58             if (pkgJSONContents.type === "module") {
59                 extname = ".cjs";
60             }
61         }
62     }
63
64     const installedESLint = config.installedESLint;
65
66     delete config.installedESLint;
67
68     ConfigFile.write(config, `./.eslintrc${extname}`);
69     log.info(`Successfully created .eslintrc${extname} file in ${process.cwd()}`);
70
71     if (installedESLint) {
72         log.info("ESLint was installed locally. We recommend using this local copy instead of your globally-installed copy.");
73     }
74 }
75
76 /**
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.
84  */
85 function getPeerDependencies(moduleName) {
86     let result = getPeerDependencies.cache.get(moduleName);
87
88     if (!result) {
89         log.info(`Checking peerDependencies of ${moduleName}`);
90
91         result = npmUtils.fetchPeerDependencies(moduleName);
92         getPeerDependencies.cache.set(moduleName, result);
93     }
94
95     return result;
96 }
97 getPeerDependencies.cache = new Map();
98
99 /**
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.
104  */
105 function getModulesList(config, installESLint) {
106     const modules = {};
107
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");
112
113             modules[moduleName] = "latest";
114         }
115     }
116     if (config.extends) {
117         const extendList = Array.isArray(config.extends) ? config.extends : [config.extends];
118
119         for (const extend of extendList) {
120             if (extend.startsWith("eslint:") || extend.startsWith("plugin:")) {
121                 continue;
122             }
123             const moduleName = naming.normalizePackageName(extend, "eslint-config");
124
125             modules[moduleName] = "latest";
126             Object.assign(
127                 modules,
128                 getPeerDependencies(`${moduleName}@latest`)
129             );
130         }
131     }
132
133     const parser = config.parser || (config.parserOptions && config.parserOptions.parser);
134
135     if (parser) {
136         modules[parser] = "latest";
137     }
138
139     if (installESLint === false) {
140         delete modules.eslint;
141     } else {
142         const installStatus = npmUtils.checkDevDeps(["eslint"]);
143
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;
149         }
150     }
151
152     return Object.keys(modules).map(name => `${name}@${modules[name]}`);
153 }
154
155 /**
156  * Set the `rules` of a config by examining a user's source code
157  *
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
163  */
164 function configureRules(answers, config) {
165     const BAR_TOTAL = 20,
166         BAR_SOURCE_CODE_TOTAL = 4,
167         newConfig = Object.assign({}, config),
168         disabledConfigs = {};
169     let sourceCodes,
170         registry;
171
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 ", {
174         width: 30,
175         total: BAR_TOTAL
176     });
177
178     bar.tick(0); // Shows the progress bar
179
180     // Get the SourceCode of all chosen files
181     const patterns = answers.patterns.split(/[\s]+/u);
182
183     try {
184         sourceCodes = getSourceCodeOfFiles(patterns, { baseConfig: newConfig, useEslintrc: false }, total => {
185             bar.tick((BAR_SOURCE_CODE_TOTAL / total));
186         });
187     } catch (e) {
188         log.info("\n");
189         throw e;
190     }
191     const fileQty = Object.keys(sourceCodes).length;
192
193     if (fileQty === 0) {
194         log.info("\n");
195         throw new Error("Automatic Configuration failed.  No files were able to be parsed.");
196     }
197
198     // Create a registry of rule configs
199     registry = new autoconfig.Registry();
200     registry.populateFromCoreRules();
201
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
205     });
206     debug(`\nRegistry: ${util.inspect(registry.rules, { depth: null })}`);
207
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]));
210
211     // Find and disable rules which had no error-free configuration
212     const failingRegistry = registry.getFailingRulesRegistry();
213
214     Object.keys(failingRegistry.rules).forEach(ruleId => {
215
216         // If the rule is recommended, set it to error, otherwise disable it
217         disabledConfigs[ruleId] = (recRules.indexOf(ruleId) !== -1) ? 2 : 0;
218     });
219
220     // Now that we know which rules to disable, strip out configs with errors
221     registry = registry.stripFailingConfigs();
222
223     /*
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.
226      */
227     const singleConfigs = registry.createConfig().rules;
228
229     /*
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.
234      */
235     const specTwoConfigs = registry.filterBySpecificity(2).createConfig().rules;
236
237     // Maybe a specific combination using all three options works
238     const specThreeConfigs = registry.filterBySpecificity(3).createConfig().rules;
239
240     // If all else fails, try to use the default (severity only)
241     const defaultConfigs = registry.filterBySpecificity(1).createConfig().rules;
242
243     // Combine configs in reverse priority order (later take precedence)
244     newConfig.rules = Object.assign({}, disabledConfigs, defaultConfigs, specThreeConfigs, specTwoConfigs, singleConfigs);
245
246     // Make sure progress bar has finished (floating point rounding)
247     bar.update(BAR_TOTAL);
248
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."}`
257     ].join(" ");
258
259     log.info(resultMessage);
260
261     ConfigOps.normalizeToStrings(newConfig);
262     return newConfig;
263 }
264
265 /**
266  * process user's answers and create config object
267  * @param {Object} answers answers received from enquirer
268  * @returns {Object} config object
269  */
270 function processAnswers(answers) {
271     let config = {
272         rules: {},
273         env: {},
274         parserOptions: {},
275         extends: []
276     };
277
278     config.parserOptions.ecmaVersion = espree.latestEcmaVersion;
279     config.env.es2021 = true;
280
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;
286     }
287
288     // add in browser and node environments if necessary
289     answers.env.forEach(env => {
290         config.env[env] = true;
291     });
292
293     // add in library information
294     if (answers.framework === "react") {
295         config.parserOptions.ecmaFeatures = {
296             jsx: true
297         };
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");
303     }
304
305     if (answers.typescript) {
306         if (answers.framework === "vue") {
307             config.parserOptions.parser = "@typescript-eslint/parser";
308         } else {
309             config.parser = "@typescript-eslint/parser";
310         }
311
312         if (Array.isArray(config.plugins)) {
313             config.plugins.push("@typescript-eslint");
314         } else {
315             config.plugins = ["@typescript-eslint"];
316         }
317     }
318
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);
332         }
333     }
334     if (answers.typescript && config.extends.includes("eslint:recommended")) {
335         config.extends.push("plugin:@typescript-eslint/recommended");
336     }
337
338     // normalize extends
339     if (config.extends.length === 0) {
340         delete config.extends;
341     } else if (config.extends.length === 1) {
342         config.extends = config.extends[0];
343     }
344
345     ConfigOps.normalizeToStrings(config);
346     return config;
347 }
348
349 /**
350  * Get the version of the local ESLint.
351  * @returns {string|null} The version. If the local ESLint was not found, returns null.
352  */
353 function getLocalESLintVersion() {
354     try {
355         const eslintPath = ModuleResolver.resolve("eslint", path.join(process.cwd(), "__placeholder__.js"));
356         const eslint = require(eslintPath);
357
358         return eslint.linter.version || null;
359     } catch {
360         return null;
361     }
362 }
363
364 /**
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.
368  */
369 function getStyleGuideName(answers) {
370     if (answers.styleguide === "airbnb" && answers.framework !== "react") {
371         return "airbnb-base";
372     }
373     return answers.styleguide;
374 }
375
376 /**
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.
380  */
381 function hasESLintVersionConflict(answers) {
382
383     // Get the local ESLint version.
384     const localESLintVersion = getLocalESLintVersion();
385
386     if (!localESLintVersion) {
387         return false;
388     }
389
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;
395
396     if (!requiredESLintVersionRange) {
397         return false;
398     }
399
400     answers.localESLintVersion = localESLintVersion;
401     answers.requiredESLintVersionRange = requiredESLintVersionRange;
402
403     // Check the version.
404     if (semver.satisfies(localESLintVersion, requiredESLintVersionRange)) {
405         answers.installESLint = false;
406         return false;
407     }
408
409     return true;
410 }
411
412 /**
413  * Install modules.
414  * @param   {string[]} modules Modules to be installed.
415  * @returns {void}
416  */
417 function installModules(modules) {
418     log.info(`Installing ${modules.join(", ")}`);
419     npmUtils.installSyncSaveDev(modules);
420 }
421
422 /* istanbul ignore next: no need to test enquirer */
423 /**
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.
428  */
429 function askInstallModules(modules, packageJsonExists) {
430
431     // If no modules, do nothing.
432     if (modules.length === 0) {
433         return Promise.resolve();
434     }
435
436     log.info("The config that you've selected requires the following dependencies:\n");
437     log.info(modules.join(" "));
438     return enquirer.prompt([
439         {
440             type: "toggle",
441             name: "executeInstallation",
442             message: "Would you like to install them now with npm?",
443             enabled: "Yes",
444             disabled: "No",
445             initial: 1,
446             skip() {
447                 return !(modules.length && packageJsonExists);
448             },
449             result(input) {
450                 return this.skipped ? null : input;
451             }
452         }
453     ]).then(({ executeInstallation }) => {
454         if (executeInstallation) {
455             installModules(modules);
456         }
457     });
458 }
459
460 /* istanbul ignore next: no need to test enquirer */
461 /**
462  * Ask use a few questions on command prompt
463  * @returns {Promise} The promise with the result of the prompt
464  */
465 function promptUser() {
466
467     return enquirer.prompt([
468         {
469             type: "select",
470             name: "purpose",
471             message: "How would you like to use ESLint?",
472
473             // The returned number matches the name value of nth in the choices array.
474             initial: 1,
475             choices: [
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" }
479             ]
480         },
481         {
482             type: "select",
483             name: "moduleType",
484             message: "What type of modules does your project use?",
485             initial: 0,
486             choices: [
487                 { message: "JavaScript modules (import/export)", name: "esm" },
488                 { message: "CommonJS (require/exports)", name: "commonjs" },
489                 { message: "None of these", name: "none" }
490             ]
491         },
492         {
493             type: "select",
494             name: "framework",
495             message: "Which framework does your project use?",
496             initial: 0,
497             choices: [
498                 { message: "React", name: "react" },
499                 { message: "Vue.js", name: "vue" },
500                 { message: "None of these", name: "none" }
501             ]
502         },
503         {
504             type: "toggle",
505             name: "typescript",
506             message: "Does your project use TypeScript?",
507             enabled: "Yes",
508             disabled: "No",
509             initial: 0
510         },
511         {
512             type: "multiselect",
513             name: "env",
514             message: "Where does your code run?",
515             hint: "(Press <space> to select, <a> to toggle all, <i> to invert selection)",
516             initial: 0,
517             choices: [
518                 { message: "Browser", name: "browser" },
519                 { message: "Node", name: "node" }
520             ]
521         },
522         {
523             type: "select",
524             name: "source",
525             message: "How would you like to define a style for your project?",
526             choices: [
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" }
530             ],
531             skip() {
532                 return this.state.answers.purpose !== "style";
533             },
534             result(input) {
535                 return this.skipped ? null : input;
536             }
537         },
538         {
539             type: "select",
540             name: "styleguide",
541             message: "Which style guide do you want to follow?",
542             choices: [
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" }
547             ],
548             skip() {
549                 this.state.answers.packageJsonExists = npmUtils.checkPackageJson();
550                 return !(this.state.answers.source === "guide" && this.state.answers.packageJsonExists);
551             },
552             result(input) {
553                 return this.skipped ? null : input;
554             }
555         },
556         {
557             type: "input",
558             name: "patterns",
559             message: "Which file(s), path(s), or glob(s) should be examined?",
560             skip() {
561                 return this.state.answers.source !== "auto";
562             },
563             validate(input) {
564                 if (!this.skipped && input.trim().length === 0 && input.trim() !== ",") {
565                     return "You must tell us what code to examine. Try again.";
566                 }
567                 return true;
568             }
569         },
570         {
571             type: "select",
572             name: "format",
573             message: "What format do you want your config file to be in?",
574             initial: 0,
575             choices: ["JavaScript", "YAML", "JSON"]
576         },
577         {
578             type: "toggle",
579             name: "installESLint",
580             message() {
581                 const { answers } = this.state;
582                 const verb = semver.ltr(answers.localESLintVersion, answers.requiredESLintVersionRange)
583                     ? "upgrade"
584                     : "downgrade";
585
586                 return `The style guide "${answers.styleguide}" requires eslint@${answers.requiredESLintVersionRange}. You are currently using eslint@${answers.localESLintVersion}.\n  Do you want to ${verb}?`;
587             },
588             enabled: "Yes",
589             disabled: "No",
590             initial: 1,
591             skip() {
592                 return !(this.state.answers.source === "guide" && this.state.answers.packageJsonExists && hasESLintVersionConflict(this.state.answers));
593             },
594             result(input) {
595                 return this.skipped ? null : input;
596             }
597         }
598     ]).then(earlyAnswers => {
599
600         // early exit if no style guide is necessary
601         if (earlyAnswers.purpose !== "style") {
602             const config = processAnswers(earlyAnswers);
603             const modules = getModulesList(config);
604
605             return askInstallModules(modules, earlyAnswers.packageJsonExists)
606                 .then(() => writeFile(config, earlyAnswers.format));
607         }
608
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.");
613                 return void 0;
614             }
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.`);
617             }
618             if (earlyAnswers.styleguide === "airbnb" && earlyAnswers.framework !== "react") {
619                 earlyAnswers.styleguide = "airbnb-base";
620             }
621
622             const config = processAnswers(earlyAnswers);
623
624             if (Array.isArray(config.extends)) {
625                 config.extends.push(earlyAnswers.styleguide);
626             } else if (config.extends) {
627                 config.extends = [config.extends, earlyAnswers.styleguide];
628             } else {
629                 config.extends = [earlyAnswers.styleguide];
630             }
631
632             const modules = getModulesList(config);
633
634             return askInstallModules(modules, earlyAnswers.packageJsonExists)
635                 .then(() => writeFile(config, earlyAnswers.format));
636
637         }
638
639         if (earlyAnswers.source === "auto") {
640             const combinedAnswers = Object.assign({}, earlyAnswers);
641             const config = processAnswers(combinedAnswers);
642             const modules = getModulesList(config);
643
644             return askInstallModules(modules).then(() => writeFile(config, earlyAnswers.format));
645         }
646
647         // continue with the style questions otherwise...
648         return enquirer.prompt([
649             {
650                 type: "select",
651                 name: "indent",
652                 message: "What style of indentation do you use?",
653                 initial: 0,
654                 choices: [{ message: "Tabs", name: "tab" }, { message: "Spaces", name: 4 }]
655             },
656             {
657                 type: "select",
658                 name: "quotes",
659                 message: "What quotes do you use for strings?",
660                 initial: 0,
661                 choices: [{ message: "Double", name: "double" }, { message: "Single", name: "single" }]
662             },
663             {
664                 type: "select",
665                 name: "linebreak",
666                 message: "What line endings do you use?",
667                 initial: 0,
668                 choices: [{ message: "Unix", name: "unix" }, { message: "Windows", name: "windows" }]
669             },
670             {
671                 type: "toggle",
672                 name: "semi",
673                 message: "Do you require semicolons?",
674                 enabled: "Yes",
675                 disabled: "No",
676                 initial: 1
677             }
678         ]).then(answers => {
679             const totalAnswers = Object.assign({}, earlyAnswers, answers);
680
681             const config = processAnswers(totalAnswers);
682             const modules = getModulesList(config);
683
684             return askInstallModules(modules).then(() => writeFile(config, earlyAnswers.format));
685         });
686     });
687 }
688
689 //------------------------------------------------------------------------------
690 // Public Interface
691 //------------------------------------------------------------------------------
692
693 const init = {
694     getModulesList,
695     hasESLintVersionConflict,
696     installModules,
697     processAnswers,
698     writeFile,
699     /* istanbul ignore next */initializeConfig() {
700         return promptUser();
701     }
702 };
703
704 module.exports = init;