stringFormatter.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. 'use strict';
  2. const path = require('path');
  3. const stringWidth = require('string-width');
  4. const table = require('table');
  5. const { yellow, dim, underline, blue, red, green } = require('picocolors');
  6. const pluralize = require('../utils/pluralize');
  7. const { assertNumber } = require('../utils/validateTypes');
  8. const terminalLink = require('./terminalLink');
  9. const MARGIN_WIDTHS = 9;
  10. /**
  11. * @param {string} s
  12. * @returns {string}
  13. */
  14. function nope(s) {
  15. return s;
  16. }
  17. const levelColors = {
  18. info: blue,
  19. warning: yellow,
  20. error: red,
  21. success: nope,
  22. };
  23. const symbols = {
  24. info: blue('ℹ'),
  25. warning: yellow('⚠'),
  26. error: red('✖'),
  27. success: green('✔'),
  28. };
  29. /**
  30. * @param {import('stylelint').LintResult[]} results
  31. * @returns {string}
  32. */
  33. function deprecationsFormatter(results) {
  34. const allDeprecationWarnings = results.flatMap((result) => result.deprecations);
  35. if (allDeprecationWarnings.length === 0) {
  36. return '';
  37. }
  38. const seenText = new Set();
  39. return allDeprecationWarnings.reduce((output, warning) => {
  40. if (seenText.has(warning.text)) return output;
  41. seenText.add(warning.text);
  42. output += yellow('Deprecation Warning: ');
  43. output += warning.text;
  44. if (warning.reference) {
  45. output += dim(' See: ');
  46. output += dim(underline(warning.reference));
  47. }
  48. return `${output}\n`;
  49. }, '\n');
  50. }
  51. /**
  52. * @param {import('stylelint').LintResult[]} results
  53. * @return {string}
  54. */
  55. function invalidOptionsFormatter(results) {
  56. const allInvalidOptionWarnings = results.flatMap((result) =>
  57. result.invalidOptionWarnings.map((warning) => warning.text),
  58. );
  59. const uniqueInvalidOptionWarnings = [...new Set(allInvalidOptionWarnings)];
  60. return uniqueInvalidOptionWarnings.reduce((output, warning) => {
  61. output += red('Invalid Option: ');
  62. output += warning;
  63. return `${output}\n`;
  64. }, '\n');
  65. }
  66. /**
  67. * @param {string} fromValue
  68. * @param {string} cwd
  69. * @return {string}
  70. */
  71. function logFrom(fromValue, cwd) {
  72. if (fromValue.startsWith('<')) {
  73. return underline(fromValue);
  74. }
  75. const filePath = path.relative(cwd, fromValue).split(path.sep).join('/');
  76. return terminalLink(filePath, `file://${fromValue}`);
  77. }
  78. /**
  79. * @param {{[k: number]: number}} columnWidths
  80. * @return {number}
  81. */
  82. function getMessageWidth(columnWidths) {
  83. const width = columnWidths[3];
  84. assertNumber(width);
  85. if (!process.stdout.isTTY) {
  86. return width;
  87. }
  88. const availableWidth = process.stdout.columns < 80 ? 80 : process.stdout.columns;
  89. const fullWidth = Object.values(columnWidths).reduce((a, b) => a + b);
  90. // If there is no reason to wrap the text, we won't align the last column to the right
  91. if (availableWidth > fullWidth + MARGIN_WIDTHS) {
  92. return width;
  93. }
  94. return availableWidth - (fullWidth - width + MARGIN_WIDTHS);
  95. }
  96. /**
  97. * @param {import('stylelint').Warning[]} messages
  98. * @param {string} source
  99. * @param {string} cwd
  100. * @return {string}
  101. */
  102. function formatter(messages, source, cwd) {
  103. if (!messages.length) return '';
  104. const orderedMessages = [...messages].sort((a, b) => {
  105. // positionless first
  106. if (!a.line && b.line) return -1;
  107. // positionless first
  108. if (a.line && !b.line) return 1;
  109. if (a.line < b.line) return -1;
  110. if (a.line > b.line) return 1;
  111. if (a.column < b.column) return -1;
  112. if (a.column > b.column) return 1;
  113. return 0;
  114. });
  115. /**
  116. * Create a list of column widths, needed to calculate
  117. * the size of the message column and if needed wrap it.
  118. * @type {{[k: string]: number}}
  119. */
  120. const columnWidths = { 0: 1, 1: 1, 2: 1, 3: 1, 4: 1 };
  121. /**
  122. * @param {[string, string, string, string, string]} columns
  123. * @return {[string, string, string, string, string]}
  124. */
  125. function calculateWidths(columns) {
  126. for (const [key, value] of Object.entries(columns)) {
  127. const normalisedValue = value ? value.toString() : value;
  128. const width = columnWidths[key];
  129. assertNumber(width);
  130. columnWidths[key] = Math.max(width, stringWidth(normalisedValue));
  131. }
  132. return columns;
  133. }
  134. let output = '\n';
  135. if (source) {
  136. output += `${logFrom(source, cwd)}\n`;
  137. }
  138. /**
  139. * @param {import('stylelint').Warning} message
  140. * @return {string}
  141. */
  142. function formatMessageText(message) {
  143. let result = message.text;
  144. result = result
  145. // Remove all control characters (newline, tab and etc)
  146. .replace(/[\u0001-\u001A]+/g, ' ') // eslint-disable-line no-control-regex
  147. .replace(/\.$/, '');
  148. const ruleString = ` (${message.rule})`;
  149. if (result.endsWith(ruleString)) {
  150. result = result.slice(0, result.lastIndexOf(ruleString));
  151. }
  152. return result;
  153. }
  154. const cleanedMessages = orderedMessages.map((message) => {
  155. const { line, column, severity } = message;
  156. /**
  157. * @type {[string, string, string, string, string]}
  158. */
  159. const row = [
  160. line ? line.toString() : '',
  161. column ? column.toString() : '',
  162. symbols[severity] ? levelColors[severity](symbols[severity]) : severity,
  163. formatMessageText(message),
  164. dim(message.rule || ''),
  165. ];
  166. calculateWidths(row);
  167. return row;
  168. });
  169. output += table
  170. .table(cleanedMessages, {
  171. border: table.getBorderCharacters('void'),
  172. columns: {
  173. 0: { alignment: 'right', width: columnWidths[0], paddingRight: 0 },
  174. 1: { alignment: 'left', width: columnWidths[1] },
  175. 2: { alignment: 'center', width: columnWidths[2] },
  176. 3: {
  177. alignment: 'left',
  178. width: getMessageWidth(columnWidths),
  179. wrapWord: getMessageWidth(columnWidths) > 1,
  180. },
  181. 4: { alignment: 'left', width: columnWidths[4], paddingRight: 0 },
  182. },
  183. drawHorizontalLine: () => false,
  184. })
  185. .split('\n')
  186. .map(
  187. /**
  188. * @param {string} el
  189. * @returns {string}
  190. */
  191. (el) => el.replace(/(\d+)\s+(\d+)/, (_m, p1, p2) => dim(`${p1}:${p2}`)),
  192. )
  193. .join('\n');
  194. return output;
  195. }
  196. /**
  197. * @type {import('stylelint').Formatter}
  198. */
  199. module.exports = function (results, returnValue) {
  200. let output = invalidOptionsFormatter(results);
  201. output += deprecationsFormatter(results);
  202. let errorCount = 0;
  203. let warningCount = 0;
  204. output = results.reduce((accum, result) => {
  205. // Treat parseErrors as warnings
  206. if (result.parseErrors) {
  207. for (const error of result.parseErrors) {
  208. result.warnings.push({
  209. line: error.line,
  210. column: error.column,
  211. rule: error.stylelintType,
  212. severity: 'error',
  213. text: `${error.text} (${error.stylelintType})`,
  214. });
  215. errorCount += 1;
  216. }
  217. }
  218. accum += formatter(
  219. result.warnings,
  220. result.source || '',
  221. (returnValue && returnValue.cwd) || process.cwd(),
  222. );
  223. for (const warning of result.warnings) {
  224. switch (warning.severity) {
  225. case 'error':
  226. errorCount += 1;
  227. break;
  228. case 'warning':
  229. warningCount += 1;
  230. break;
  231. default:
  232. throw new Error(`Unknown severity: "${warning.severity}"`);
  233. }
  234. }
  235. return accum;
  236. }, output);
  237. // Ensure consistent padding
  238. output = output.trim();
  239. if (output !== '') {
  240. output = `\n${output}\n\n`;
  241. const total = errorCount + warningCount;
  242. if (total > 0) {
  243. const tally =
  244. `${total} ${pluralize('problem', total)}` +
  245. ` (${errorCount} ${pluralize('error', errorCount)}` +
  246. `, ${warningCount} ${pluralize('warning', warningCount)})`;
  247. output += `${tally}\n\n`;
  248. }
  249. }
  250. return output;
  251. };