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