Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

config-initializer.js 22KB

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