config-initializer.js 21 KB

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