eslintCheck.js 2.4 KB

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