config-initializer.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. /**
  2. * @fileoverview Config initialization wizard.
  3. * @author Ilya Volodin
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const util = require("util"),
  10. inquirer = require("inquirer"),
  11. ProgressBar = require("progress"),
  12. semver = require("semver"),
  13. autoconfig = require("./autoconfig.js"),
  14. ConfigFile = require("./config-file"),
  15. ConfigOps = require("./config-ops"),
  16. getSourceCodeOfFiles = require("../util/source-code-utils").getSourceCodeOfFiles,
  17. ModuleResolver = require("../util/module-resolver"),
  18. npmUtils = require("../util/npm-utils"),
  19. recConfig = require("../../conf/eslint-recommended"),
  20. log = require("../util/logging");
  21. const debug = require("debug")("eslint:config-initializer");
  22. //------------------------------------------------------------------------------
  23. // Private
  24. //------------------------------------------------------------------------------
  25. const DEFAULT_ECMA_VERSION = 2018;
  26. /* istanbul ignore next: hard to test fs function */
  27. /**
  28. * Create .eslintrc file in the current working directory
  29. * @param {Object} config object that contains user's answers
  30. * @param {string} format The file format to write to.
  31. * @returns {void}
  32. */
  33. function writeFile(config, format) {
  34. // default is .js
  35. let extname = ".js";
  36. if (format === "YAML") {
  37. extname = ".yml";
  38. } else if (format === "JSON") {
  39. extname = ".json";
  40. }
  41. const installedESLint = config.installedESLint;
  42. delete config.installedESLint;
  43. ConfigFile.write(config, `./.eslintrc${extname}`);
  44. log.info(`Successfully created .eslintrc${extname} file in ${process.cwd()}`);
  45. if (installedESLint) {
  46. log.info("ESLint was installed locally. We recommend using this local copy instead of your globally-installed copy.");
  47. }
  48. }
  49. /**
  50. * Get the peer dependencies of the given module.
  51. * This adds the gotten value to cache at the first time, then reuses it.
  52. * In a process, this function is called twice, but `npmUtils.fetchPeerDependencies` needs to access network which is relatively slow.
  53. * @param {string} moduleName The module name to get.
  54. * @returns {Object} The peer dependencies of the given module.
  55. * This object is the object of `peerDependencies` field of `package.json`.
  56. * Returns null if npm was not found.
  57. */
  58. function getPeerDependencies(moduleName) {
  59. let result = getPeerDependencies.cache.get(moduleName);
  60. if (!result) {
  61. log.info(`Checking peerDependencies of ${moduleName}`);
  62. result = npmUtils.fetchPeerDependencies(moduleName);
  63. getPeerDependencies.cache.set(moduleName, result);
  64. }
  65. return result;
  66. }
  67. getPeerDependencies.cache = new Map();
  68. /**
  69. * Return necessary plugins, configs, parsers, etc. based on the config
  70. * @param {Object} config config object
  71. * @param {boolean} [installESLint=true] If `false` is given, it does not install eslint.
  72. * @returns {string[]} An array of modules to be installed.
  73. */
  74. function getModulesList(config, installESLint) {
  75. const modules = {};
  76. // Create a list of modules which should be installed based on config
  77. if (config.plugins) {
  78. for (const plugin of config.plugins) {
  79. modules[`eslint-plugin-${plugin}`] = "latest";
  80. }
  81. }
  82. if (config.extends && config.extends.indexOf("eslint:") === -1) {
  83. const moduleName = `eslint-config-${config.extends}`;
  84. modules[moduleName] = "latest";
  85. Object.assign(
  86. modules,
  87. getPeerDependencies(`${moduleName}@latest`)
  88. );
  89. }
  90. if (installESLint === false) {
  91. delete modules.eslint;
  92. } else {
  93. const installStatus = npmUtils.checkDevDeps(["eslint"]);
  94. // Mark to show messages if it's new installation of eslint.
  95. if (installStatus.eslint === false) {
  96. log.info("Local ESLint installation not found.");
  97. modules.eslint = modules.eslint || "latest";
  98. config.installedESLint = true;
  99. }
  100. }
  101. return Object.keys(modules).map(name => `${name}@${modules[name]}`);
  102. }
  103. /**
  104. * Set the `rules` of a config by examining a user's source code
  105. *
  106. * Note: This clones the config object and returns a new config to avoid mutating
  107. * the original config parameter.
  108. *
  109. * @param {Object} answers answers received from inquirer
  110. * @param {Object} config config object
  111. * @returns {Object} config object with configured rules
  112. */
  113. function configureRules(answers, config) {
  114. const BAR_TOTAL = 20,
  115. BAR_SOURCE_CODE_TOTAL = 4,
  116. newConfig = Object.assign({}, config),
  117. disabledConfigs = {};
  118. let sourceCodes,
  119. registry;
  120. // Set up a progress bar, as this process can take a long time
  121. const bar = new ProgressBar("Determining Config: :percent [:bar] :elapseds elapsed, eta :etas ", {
  122. width: 30,
  123. total: BAR_TOTAL
  124. });
  125. bar.tick(0); // Shows the progress bar
  126. // Get the SourceCode of all chosen files
  127. const patterns = answers.patterns.split(/[\s]+/u);
  128. try {
  129. sourceCodes = getSourceCodeOfFiles(patterns, { baseConfig: newConfig, useEslintrc: false }, total => {
  130. bar.tick((BAR_SOURCE_CODE_TOTAL / total));
  131. });
  132. } catch (e) {
  133. log.info("\n");
  134. throw e;
  135. }
  136. const fileQty = Object.keys(sourceCodes).length;
  137. if (fileQty === 0) {
  138. log.info("\n");
  139. throw new Error("Automatic Configuration failed. No files were able to be parsed.");
  140. }
  141. // Create a registry of rule configs
  142. registry = new autoconfig.Registry();
  143. registry.populateFromCoreRules();
  144. // Lint all files with each rule config in the registry
  145. registry = registry.lintSourceCode(sourceCodes, newConfig, total => {
  146. bar.tick((BAR_TOTAL - BAR_SOURCE_CODE_TOTAL) / total); // Subtract out ticks used at beginning
  147. });
  148. debug(`\nRegistry: ${util.inspect(registry.rules, { depth: null })}`);
  149. // Create a list of recommended rules, because we don't want to disable them
  150. const recRules = Object.keys(recConfig.rules).filter(ruleId => ConfigOps.isErrorSeverity(recConfig.rules[ruleId]));
  151. // Find and disable rules which had no error-free configuration
  152. const failingRegistry = registry.getFailingRulesRegistry();
  153. Object.keys(failingRegistry.rules).forEach(ruleId => {
  154. // If the rule is recommended, set it to error, otherwise disable it
  155. disabledConfigs[ruleId] = (recRules.indexOf(ruleId) !== -1) ? 2 : 0;
  156. });
  157. // Now that we know which rules to disable, strip out configs with errors
  158. registry = registry.stripFailingConfigs();
  159. /*
  160. * If there is only one config that results in no errors for a rule, we should use it.
  161. * createConfig will only add rules that have one configuration in the registry.
  162. */
  163. const singleConfigs = registry.createConfig().rules;
  164. /*
  165. * The "sweet spot" for number of options in a config seems to be two (severity plus one option).
  166. * Very often, a third option (usually an object) is available to address
  167. * edge cases, exceptions, or unique situations. We will prefer to use a config with
  168. * specificity of two.
  169. */
  170. const specTwoConfigs = registry.filterBySpecificity(2).createConfig().rules;
  171. // Maybe a specific combination using all three options works
  172. const specThreeConfigs = registry.filterBySpecificity(3).createConfig().rules;
  173. // If all else fails, try to use the default (severity only)
  174. const defaultConfigs = registry.filterBySpecificity(1).createConfig().rules;
  175. // Combine configs in reverse priority order (later take precedence)
  176. newConfig.rules = Object.assign({}, disabledConfigs, defaultConfigs, specThreeConfigs, specTwoConfigs, singleConfigs);
  177. // Make sure progress bar has finished (floating point rounding)
  178. bar.update(BAR_TOTAL);
  179. // Log out some stats to let the user know what happened
  180. const finalRuleIds = Object.keys(newConfig.rules);
  181. const totalRules = finalRuleIds.length;
  182. const enabledRules = finalRuleIds.filter(ruleId => (newConfig.rules[ruleId] !== 0)).length;
  183. const resultMessage = [
  184. `\nEnabled ${enabledRules} out of ${totalRules}`,
  185. `rules based on ${fileQty}`,
  186. `file${(fileQty === 1) ? "." : "s."}`
  187. ].join(" ");
  188. log.info(resultMessage);
  189. ConfigOps.normalizeToStrings(newConfig);
  190. return newConfig;
  191. }
  192. /**
  193. * process user's answers and create config object
  194. * @param {Object} answers answers received from inquirer
  195. * @returns {Object} config object
  196. */
  197. function processAnswers(answers) {
  198. let config = {
  199. rules: {},
  200. env: {},
  201. parserOptions: {},
  202. extends: []
  203. };
  204. // set the latest ECMAScript version
  205. config.parserOptions.ecmaVersion = DEFAULT_ECMA_VERSION;
  206. config.env.es6 = true;
  207. config.globals = {
  208. Atomics: "readonly",
  209. SharedArrayBuffer: "readonly"
  210. };
  211. // set the module type
  212. if (answers.moduleType === "esm") {
  213. config.parserOptions.sourceType = "module";
  214. } else if (answers.moduleType === "commonjs") {
  215. config.env.commonjs = true;
  216. }
  217. // add in browser and node environments if necessary
  218. answers.env.forEach(env => {
  219. config.env[env] = true;
  220. });
  221. // add in library information
  222. if (answers.framework === "react") {
  223. config.parserOptions.ecmaFeatures = {
  224. jsx: true
  225. };
  226. config.plugins = ["react"];
  227. } else if (answers.framework === "vue") {
  228. config.plugins = ["vue"];
  229. config.extends.push("plugin:vue/essential");
  230. }
  231. // setup rules based on problems/style enforcement preferences
  232. if (answers.purpose === "problems") {
  233. config.extends.unshift("eslint:recommended");
  234. } else if (answers.purpose === "style") {
  235. if (answers.source === "prompt") {
  236. config.extends.unshift("eslint:recommended");
  237. config.rules.indent = ["error", answers.indent];
  238. config.rules.quotes = ["error", answers.quotes];
  239. config.rules["linebreak-style"] = ["error", answers.linebreak];
  240. config.rules.semi = ["error", answers.semi ? "always" : "never"];
  241. } else if (answers.source === "auto") {
  242. config = configureRules(answers, config);
  243. config = autoconfig.extendFromRecommended(config);
  244. }
  245. }
  246. // normalize extends
  247. if (config.extends.length === 0) {
  248. delete config.extends;
  249. } else if (config.extends.length === 1) {
  250. config.extends = config.extends[0];
  251. }
  252. ConfigOps.normalizeToStrings(config);
  253. return config;
  254. }
  255. /**
  256. * process user's style guide of choice and return an appropriate config object.
  257. * @param {string} guide name of the chosen style guide
  258. * @returns {Object} config object
  259. */
  260. function getConfigForStyleGuide(guide) {
  261. const guides = {
  262. google: { extends: "google" },
  263. airbnb: { extends: "airbnb" },
  264. "airbnb-base": { extends: "airbnb-base" },
  265. standard: { extends: "standard" }
  266. };
  267. if (!guides[guide]) {
  268. throw new Error("You referenced an unsupported guide.");
  269. }
  270. return guides[guide];
  271. }
  272. /**
  273. * Get the version of the local ESLint.
  274. * @returns {string|null} The version. If the local ESLint was not found, returns null.
  275. */
  276. function getLocalESLintVersion() {
  277. try {
  278. const resolver = new ModuleResolver();
  279. const eslintPath = resolver.resolve("eslint", process.cwd());
  280. const eslint = require(eslintPath);
  281. return eslint.linter.version || null;
  282. } catch (_err) {
  283. return null;
  284. }
  285. }
  286. /**
  287. * Get the shareable config name of the chosen style guide.
  288. * @param {Object} answers The answers object.
  289. * @returns {string} The shareable config name.
  290. */
  291. function getStyleGuideName(answers) {
  292. if (answers.styleguide === "airbnb" && answers.framework !== "react") {
  293. return "airbnb-base";
  294. }
  295. return answers.styleguide;
  296. }
  297. /**
  298. * Check whether the local ESLint version conflicts with the required version of the chosen shareable config.
  299. * @param {Object} answers The answers object.
  300. * @returns {boolean} `true` if the local ESLint is found then it conflicts with the required version of the chosen shareable config.
  301. */
  302. function hasESLintVersionConflict(answers) {
  303. // Get the local ESLint version.
  304. const localESLintVersion = getLocalESLintVersion();
  305. if (!localESLintVersion) {
  306. return false;
  307. }
  308. // Get the required range of ESLint version.
  309. const configName = getStyleGuideName(answers);
  310. const moduleName = `eslint-config-${configName}@latest`;
  311. const peerDependencies = getPeerDependencies(moduleName) || {};
  312. const requiredESLintVersionRange = peerDependencies.eslint;
  313. if (!requiredESLintVersionRange) {
  314. return false;
  315. }
  316. answers.localESLintVersion = localESLintVersion;
  317. answers.requiredESLintVersionRange = requiredESLintVersionRange;
  318. // Check the version.
  319. if (semver.satisfies(localESLintVersion, requiredESLintVersionRange)) {
  320. answers.installESLint = false;
  321. return false;
  322. }
  323. return true;
  324. }
  325. /**
  326. * Install modules.
  327. * @param {string[]} modules Modules to be installed.
  328. * @returns {void}
  329. */
  330. function installModules(modules) {
  331. log.info(`Installing ${modules.join(", ")}`);
  332. npmUtils.installSyncSaveDev(modules);
  333. }
  334. /* istanbul ignore next: no need to test inquirer */
  335. /**
  336. * Ask user to install modules.
  337. * @param {string[]} modules Array of modules to be installed.
  338. * @param {boolean} packageJsonExists Indicates if package.json is existed.
  339. * @returns {Promise} Answer that indicates if user wants to install.
  340. */
  341. function askInstallModules(modules, packageJsonExists) {
  342. // If no modules, do nothing.
  343. if (modules.length === 0) {
  344. return Promise.resolve();
  345. }
  346. log.info("The config that you've selected requires the following dependencies:\n");
  347. log.info(modules.join(" "));
  348. return inquirer.prompt([
  349. {
  350. type: "confirm",
  351. name: "executeInstallation",
  352. message: "Would you like to install them now with npm?",
  353. default: true,
  354. when() {
  355. return modules.length && packageJsonExists;
  356. }
  357. }
  358. ]).then(({ executeInstallation }) => {
  359. if (executeInstallation) {
  360. installModules(modules);
  361. }
  362. });
  363. }
  364. /* istanbul ignore next: no need to test inquirer */
  365. /**
  366. * Ask use a few questions on command prompt
  367. * @returns {Promise} The promise with the result of the prompt
  368. */
  369. function promptUser() {
  370. return inquirer.prompt([
  371. {
  372. type: "list",
  373. name: "purpose",
  374. message: "How would you like to use ESLint?",
  375. default: "problems",
  376. choices: [
  377. { name: "To check syntax only", value: "syntax" },
  378. { name: "To check syntax and find problems", value: "problems" },
  379. { name: "To check syntax, find problems, and enforce code style", value: "style" }
  380. ]
  381. },
  382. {
  383. type: "list",
  384. name: "moduleType",
  385. message: "What type of modules does your project use?",
  386. default: "esm",
  387. choices: [
  388. { name: "JavaScript modules (import/export)", value: "esm" },
  389. { name: "CommonJS (require/exports)", value: "commonjs" },
  390. { name: "None of these", value: "none" }
  391. ]
  392. },
  393. {
  394. type: "list",
  395. name: "framework",
  396. message: "Which framework does your project use?",
  397. default: "react",
  398. choices: [
  399. { name: "React", value: "react" },
  400. { name: "Vue.js", value: "vue" },
  401. { name: "None of these", value: "none" }
  402. ]
  403. },
  404. {
  405. type: "checkbox",
  406. name: "env",
  407. message: "Where does your code run?",
  408. default: ["browser"],
  409. choices: [
  410. { name: "Browser", value: "browser" },
  411. { name: "Node", value: "node" }
  412. ]
  413. },
  414. {
  415. type: "list",
  416. name: "source",
  417. message: "How would you like to define a style for your project?",
  418. default: "guide",
  419. choices: [
  420. { name: "Use a popular style guide", value: "guide" },
  421. { name: "Answer questions about your style", value: "prompt" },
  422. { name: "Inspect your JavaScript file(s)", value: "auto" }
  423. ],
  424. when(answers) {
  425. return answers.purpose === "style";
  426. }
  427. },
  428. {
  429. type: "list",
  430. name: "styleguide",
  431. message: "Which style guide do you want to follow?",
  432. choices: [
  433. { name: "Airbnb (https://github.com/airbnb/javascript)", value: "airbnb" },
  434. { name: "Standard (https://github.com/standard/standard)", value: "standard" },
  435. { name: "Google (https://github.com/google/eslint-config-google)", value: "google" }
  436. ],
  437. when(answers) {
  438. answers.packageJsonExists = npmUtils.checkPackageJson();
  439. return answers.source === "guide" && answers.packageJsonExists;
  440. }
  441. },
  442. {
  443. type: "input",
  444. name: "patterns",
  445. message: "Which file(s), path(s), or glob(s) should be examined?",
  446. when(answers) {
  447. return (answers.source === "auto");
  448. },
  449. validate(input) {
  450. if (input.trim().length === 0 && input.trim() !== ",") {
  451. return "You must tell us what code to examine. Try again.";
  452. }
  453. return true;
  454. }
  455. },
  456. {
  457. type: "list",
  458. name: "format",
  459. message: "What format do you want your config file to be in?",
  460. default: "JavaScript",
  461. choices: ["JavaScript", "YAML", "JSON"]
  462. },
  463. {
  464. type: "confirm",
  465. name: "installESLint",
  466. message(answers) {
  467. const verb = semver.ltr(answers.localESLintVersion, answers.requiredESLintVersionRange)
  468. ? "upgrade"
  469. : "downgrade";
  470. return `The style guide "${answers.styleguide}" requires eslint@${answers.requiredESLintVersionRange}. You are currently using eslint@${answers.localESLintVersion}.\n Do you want to ${verb}?`;
  471. },
  472. default: true,
  473. when(answers) {
  474. return answers.source === "guide" && answers.packageJsonExists && hasESLintVersionConflict(answers);
  475. }
  476. }
  477. ]).then(earlyAnswers => {
  478. // early exit if no style guide is necessary
  479. if (earlyAnswers.purpose !== "style") {
  480. const config = processAnswers(earlyAnswers);
  481. const modules = getModulesList(config);
  482. return askInstallModules(modules, earlyAnswers.packageJsonExists)
  483. .then(() => writeFile(config, earlyAnswers.format));
  484. }
  485. // early exit if you are using a style guide
  486. if (earlyAnswers.source === "guide") {
  487. if (!earlyAnswers.packageJsonExists) {
  488. 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.");
  489. return void 0;
  490. }
  491. if (earlyAnswers.installESLint === false && !semver.satisfies(earlyAnswers.localESLintVersion, earlyAnswers.requiredESLintVersionRange)) {
  492. log.info(`Note: it might not work since ESLint's version is mismatched with the ${earlyAnswers.styleguide} config.`);
  493. }
  494. if (earlyAnswers.styleguide === "airbnb" && earlyAnswers.framework !== "react") {
  495. earlyAnswers.styleguide = "airbnb-base";
  496. }
  497. const config = ConfigOps.merge(processAnswers(earlyAnswers), getConfigForStyleGuide(earlyAnswers.styleguide));
  498. const modules = getModulesList(config);
  499. return askInstallModules(modules, earlyAnswers.packageJsonExists)
  500. .then(() => writeFile(config, earlyAnswers.format));
  501. }
  502. if (earlyAnswers.source === "auto") {
  503. const combinedAnswers = Object.assign({}, earlyAnswers);
  504. const config = processAnswers(combinedAnswers);
  505. const modules = getModulesList(config);
  506. return askInstallModules(modules).then(() => writeFile(config, earlyAnswers.format));
  507. }
  508. // continue with the style questions otherwise...
  509. return inquirer.prompt([
  510. {
  511. type: "list",
  512. name: "indent",
  513. message: "What style of indentation do you use?",
  514. default: "tab",
  515. choices: [{ name: "Tabs", value: "tab" }, { name: "Spaces", value: 4 }]
  516. },
  517. {
  518. type: "list",
  519. name: "quotes",
  520. message: "What quotes do you use for strings?",
  521. default: "double",
  522. choices: [{ name: "Double", value: "double" }, { name: "Single", value: "single" }]
  523. },
  524. {
  525. type: "list",
  526. name: "linebreak",
  527. message: "What line endings do you use?",
  528. default: "unix",
  529. choices: [{ name: "Unix", value: "unix" }, { name: "Windows", value: "windows" }]
  530. },
  531. {
  532. type: "confirm",
  533. name: "semi",
  534. message: "Do you require semicolons?",
  535. default: true
  536. },
  537. {
  538. type: "list",
  539. name: "format",
  540. message: "What format do you want your config file to be in?",
  541. default: "JavaScript",
  542. choices: ["JavaScript", "YAML", "JSON"]
  543. }
  544. ]).then(answers => {
  545. const totalAnswers = Object.assign({}, earlyAnswers, answers);
  546. const config = processAnswers(totalAnswers);
  547. const modules = getModulesList(config);
  548. return askInstallModules(modules).then(() => writeFile(config, answers.format));
  549. });
  550. });
  551. }
  552. //------------------------------------------------------------------------------
  553. // Public Interface
  554. //------------------------------------------------------------------------------
  555. const init = {
  556. getConfigForStyleGuide,
  557. getModulesList,
  558. hasESLintVersionConflict,
  559. installModules,
  560. processAnswers,
  561. /* istanbul ignore next */initializeConfig() {
  562. return promptUser();
  563. }
  564. };
  565. module.exports = init;