linter.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. "use strict";
  2. const {
  3. dirname,
  4. isAbsolute,
  5. join
  6. } = require('path');
  7. const ESLintError = require('./ESLintError');
  8. const {
  9. getESLint
  10. } = require('./getESLint');
  11. /** @typedef {import('eslint').ESLint} ESLint */
  12. /** @typedef {import('eslint').ESLint.Formatter} Formatter */
  13. /** @typedef {import('eslint').ESLint.LintResult} LintResult */
  14. /** @typedef {import('webpack').Compiler} Compiler */
  15. /** @typedef {import('webpack').Compilation} Compilation */
  16. /** @typedef {import('./options').Options} Options */
  17. /** @typedef {import('./options').FormatterFunction} FormatterFunction */
  18. /** @typedef {(compilation: Compilation) => Promise<void>} GenerateReport */
  19. /** @typedef {{errors?: ESLintError, warnings?: ESLintError, generateReportAsset?: GenerateReport}} Report */
  20. /** @typedef {() => Promise<Report>} Reporter */
  21. /** @typedef {(files: string|string[]) => void} Linter */
  22. /** @typedef {{[files: string]: LintResult}} LintResultMap */
  23. /** @type {WeakMap<Compiler, LintResultMap>} */
  24. const resultStorage = new WeakMap();
  25. /**
  26. * @param {string|undefined} key
  27. * @param {Options} options
  28. * @param {Compilation} compilation
  29. * @returns {{lint: Linter, report: Reporter, threads: number}}
  30. */
  31. function linter(key, options, compilation) {
  32. /** @type {ESLint} */
  33. let eslint;
  34. /** @type {(files: string|string[]) => Promise<LintResult[]>} */
  35. let lintFiles;
  36. /** @type {() => Promise<void>} */
  37. let cleanup;
  38. /** @type number */
  39. let threads;
  40. /** @type {Promise<LintResult[]>[]} */
  41. const rawResults = [];
  42. const crossRunResultStorage = getResultStorage(compilation);
  43. try {
  44. ({
  45. eslint,
  46. lintFiles,
  47. cleanup,
  48. threads
  49. } = getESLint(key, options));
  50. } catch (e) {
  51. throw new ESLintError(e.message);
  52. }
  53. return {
  54. lint,
  55. report,
  56. threads
  57. };
  58. /**
  59. * @param {string | string[]} files
  60. */
  61. function lint(files) {
  62. for (const file of asList(files)) {
  63. delete crossRunResultStorage[file];
  64. }
  65. rawResults.push(lintFiles(files).catch(e => {
  66. // @ts-ignore
  67. compilation.errors.push(new ESLintError(e.message));
  68. return [];
  69. }));
  70. }
  71. async function report() {
  72. // Filter out ignored files.
  73. let results = await removeIgnoredWarnings(eslint, // Get the current results, resetting the rawResults to empty
  74. await flatten(rawResults.splice(0, rawResults.length)));
  75. await cleanup();
  76. for (const result of results) {
  77. crossRunResultStorage[result.filePath] = result;
  78. }
  79. results = Object.values(crossRunResultStorage); // do not analyze if there are no results or eslint config
  80. if (!results || results.length < 1) {
  81. return {};
  82. }
  83. const formatter = await loadFormatter(eslint, options.formatter);
  84. const {
  85. errors,
  86. warnings
  87. } = await formatResults(formatter, parseResults(options, results));
  88. return {
  89. errors,
  90. warnings,
  91. generateReportAsset
  92. };
  93. /**
  94. * @param {Compilation} compilation
  95. * @returns {Promise<void>}
  96. */
  97. async function generateReportAsset({
  98. compiler
  99. }) {
  100. const {
  101. outputReport
  102. } = options;
  103. /**
  104. * @param {string} name
  105. * @param {string | Buffer} content
  106. */
  107. const save = (name, content) =>
  108. /** @type {Promise<void>} */
  109. new Promise((finish, bail) => {
  110. const {
  111. mkdir,
  112. writeFile
  113. } = compiler.outputFileSystem; // ensure directory exists
  114. // @ts-ignore - the types for `outputFileSystem` are missing the 3 arg overload
  115. mkdir(dirname(name), {
  116. recursive: true
  117. }, err => {
  118. /* istanbul ignore if */
  119. if (err) bail(err);else writeFile(name, content, err2 => {
  120. /* istanbul ignore if */
  121. if (err2) bail(err2);else finish();
  122. });
  123. });
  124. });
  125. if (!outputReport || !outputReport.filePath) {
  126. return;
  127. }
  128. const content = await (outputReport.formatter ? (await loadFormatter(eslint, outputReport.formatter)).format(results) : formatter.format(results));
  129. let {
  130. filePath
  131. } = outputReport;
  132. if (!isAbsolute(filePath)) {
  133. filePath = join(compiler.outputPath, filePath);
  134. }
  135. await save(filePath, content);
  136. }
  137. }
  138. }
  139. /**
  140. * @param {Formatter} formatter
  141. * @param {{ errors: LintResult[]; warnings: LintResult[]; }} results
  142. * @returns {Promise<{errors?: ESLintError, warnings?: ESLintError}>}
  143. */
  144. async function formatResults(formatter, results) {
  145. let errors;
  146. let warnings;
  147. if (results.warnings.length > 0) {
  148. warnings = new ESLintError(await formatter.format(results.warnings));
  149. }
  150. if (results.errors.length > 0) {
  151. errors = new ESLintError(await formatter.format(results.errors));
  152. }
  153. return {
  154. errors,
  155. warnings
  156. };
  157. }
  158. /**
  159. * @param {Options} options
  160. * @param {LintResult[]} results
  161. * @returns {{errors: LintResult[], warnings: LintResult[]}}
  162. */
  163. function parseResults(options, results) {
  164. /** @type {LintResult[]} */
  165. const errors = [];
  166. /** @type {LintResult[]} */
  167. const warnings = [];
  168. results.forEach(file => {
  169. if (fileHasErrors(file)) {
  170. const messages = file.messages.filter(message => options.emitError && message.severity === 2);
  171. if (messages.length > 0) {
  172. errors.push({ ...file,
  173. messages
  174. });
  175. }
  176. }
  177. if (fileHasWarnings(file)) {
  178. const messages = file.messages.filter(message => options.emitWarning && message.severity === 1);
  179. if (messages.length > 0) {
  180. warnings.push({ ...file,
  181. messages
  182. });
  183. }
  184. }
  185. });
  186. return {
  187. errors,
  188. warnings
  189. };
  190. }
  191. /**
  192. * @param {LintResult} file
  193. * @returns {boolean}
  194. */
  195. function fileHasErrors(file) {
  196. return file.errorCount > 0;
  197. }
  198. /**
  199. * @param {LintResult} file
  200. * @returns {boolean}
  201. */
  202. function fileHasWarnings(file) {
  203. return file.warningCount > 0;
  204. }
  205. /**
  206. * @param {ESLint} eslint
  207. * @param {string|FormatterFunction=} formatter
  208. * @returns {Promise<Formatter>}
  209. */
  210. async function loadFormatter(eslint, formatter) {
  211. if (typeof formatter === 'function') {
  212. return {
  213. format: formatter
  214. };
  215. }
  216. if (typeof formatter === 'string') {
  217. try {
  218. return eslint.loadFormatter(formatter);
  219. } catch (_) {// Load the default formatter.
  220. }
  221. }
  222. return eslint.loadFormatter();
  223. }
  224. /**
  225. * @param {ESLint} eslint
  226. * @param {LintResult[]} results
  227. * @returns {Promise<LintResult[]>}
  228. */
  229. async function removeIgnoredWarnings(eslint, results) {
  230. const filterPromises = results.map(async result => {
  231. // Short circuit the call to isPathIgnored.
  232. // fatal is false for ignored file warnings.
  233. // ruleId is unset for internal ESLint errors.
  234. // line is unset for warnings not involving file contents.
  235. const ignored = result.messages.length === 0 || result.warningCount === 1 && result.errorCount === 0 && !result.messages[0].fatal && !result.messages[0].ruleId && !result.messages[0].line && (await eslint.isPathIgnored(result.filePath));
  236. return ignored ? false : result;
  237. }); // @ts-ignore
  238. return (await Promise.all(filterPromises)).filter(result => !!result);
  239. }
  240. /**
  241. * @param {Promise<LintResult[]>[]} results
  242. * @returns {Promise<LintResult[]>}
  243. */
  244. async function flatten(results) {
  245. /**
  246. * @param {LintResult[]} acc
  247. * @param {LintResult[]} list
  248. */
  249. const flat = (acc, list) => [...acc, ...list];
  250. return (await Promise.all(results)).reduce(flat, []);
  251. }
  252. /**
  253. * @param {Compilation} compilation
  254. * @returns {LintResultMap}
  255. */
  256. function getResultStorage({
  257. compiler
  258. }) {
  259. let storage = resultStorage.get(compiler);
  260. if (!storage) {
  261. resultStorage.set(compiler, storage = {});
  262. }
  263. return storage;
  264. }
  265. /**
  266. * @param {string | string[]} x
  267. */
  268. function asList(x) {
  269. /* istanbul ignore next */
  270. return Array.isArray(x) ? x : [x];
  271. }
  272. module.exports = linter;