eslintCheck.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /* eslint-disable prefer-template */
  2. /**
  3. * 工程代码pre-commit 检查工具
  4. * @date 2019.9.4
  5. */
  6. const { exec } = require('child_process');
  7. const chalk = require('chalk');
  8. const { CLIEngine } = require('eslint');
  9. const cli = new CLIEngine({});
  10. const { log } = console;
  11. function getErrorLevel(number) {
  12. switch (number) {
  13. case 2:
  14. return 'error';
  15. case 1:
  16. return 'warn';
  17. default:
  18. }
  19. return 'undefined';
  20. }
  21. let pass = 0;
  22. exec('git diff --cached --name-only --diff-filter=ACM | grep -Ei "\\.ts$|\\.js$"', (error, stdout) => {
  23. if (stdout.length) {
  24. const array = stdout.split('\n');
  25. array.pop();
  26. const { results } = cli.executeOnFiles(array);
  27. let errorCount = 0;
  28. let warningCount = 0;
  29. results.forEach((result) => {
  30. errorCount += result.errorCount;
  31. warningCount += result.warningCount;
  32. if (result.messages.length > 0) {
  33. log('\n');
  34. log(result.filePath);
  35. result.messages.forEach((obj) => {
  36. const level = getErrorLevel(obj.severity);
  37. if (level === 'warn')
  38. log(
  39. ' ' +
  40. obj.line +
  41. ':' +
  42. obj.column +
  43. '\t ' +
  44. chalk.yellow(level) +
  45. ' \0 ' +
  46. obj.message +
  47. '\t\t' +
  48. chalk.grey(obj.ruleId) +
  49. '',
  50. );
  51. if (level === 'error')
  52. log(
  53. ' ' +
  54. obj.line +
  55. ':' +
  56. obj.column +
  57. '\t ' +
  58. chalk.red.bold(level) +
  59. ' \0 ' +
  60. obj.message +
  61. '\t\t ' +
  62. chalk.grey(obj.ruleId) +
  63. '',
  64. );
  65. if (level === 'error') pass = 1;
  66. });
  67. }
  68. });
  69. if (warningCount > 0 || errorCount > 0) {
  70. log(
  71. '\n' +
  72. chalk.bgRed.bold(errorCount + warningCount + ' problems') +
  73. ' (' +
  74. chalk.red.bold(errorCount) +
  75. ' errors, ' +
  76. chalk.yellow(warningCount) +
  77. ' warnings) \0',
  78. );
  79. }
  80. !pass && log(chalk.green.bold('~~ Done: 代码检验通过,提交成功 ~~'));
  81. process.exit(pass);
  82. }
  83. if (error !== null) {
  84. log(`exec error: ${error}`);
  85. }
  86. });