config-initializer.js 23 KB

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