基于git diff进行的eslint代码检测

缘起

在项目中, 通常都会使用代码检测工具来规范团队的代码风格, 比如eslint。随着代码的不断增加, eslint进行代码检测的时间也越来越久。每次检测的时候, 需要检测的文件和实际检测的文件极度不对称,所以便基于git diff写了这样一个小工具。

源代码

2017-02-21更新

太久时间没来博客园了, 今天来了, 然后顺便把这个也更新了吧。 最开始写这个的时候, 思路不清晰, 以至于数据处理部分用了bash, node, 然而实际上我只是通过git来获取到与指定分支相比发生变化的文件而已, 所以这个过程应该从git入手而不是自己另行处理, 庆幸的是, 刚好有那么个选项git diff origin/<branchname> --name-only可以让我获取到当前分支和指定分支发生变化的文件, 所以现在要达到之前的效果, 只需要执行这个bash脚本即可。

#!/bin/bash
INFO='\033[36m';
NOR='\033[0m';
ERR='\033[31m';
br='dev';
echo -e "${INFO}run lint now ... just wait a moment ...${NOR}"; [ $1 ] && br=$1;
log=`git diff origin/${br} --name-only | grep ".js$" | egrep "^src/|^tests/"`;
if [ -z "${log}" ]; then
echo -e "${INFO}No file changed, exit now ${NOR}";
exit 0;
fi;
node ./node_modules/eslint/bin/eslint.js $log | grep error -C 100 --color=auto;

更新之前的

  • 启动脚本(lint.sh)

#!/bin/bash
INFO='\033[36m';
NOR='\033[0m';
ERR='\033[31m';
br='dev';
echo -e "${INFO}run lint now ... just wait a moment ...${NOR}";
if [ $1 ]; then
br=$1;
fi;
# echo "The br is $br";
git diff origin/${br} > diff.log;
log=`cat diff.log | grep 'diff --git a/src'`;
if [[ -z ${log} ]]; then
echo -e "${INFO}没有文件发生变化${NOR}";
else
echo '';
node ./lint-by-diff.js > lint.log;
cat lint.log | grep error -C 1000 --color=auto;
fi;
echo -e "${INFO}done ...${NOR}";
rm diff.log change.log lint.log 2> /dev/null
read;
  • 检测工具(lint-by-diff.js)
const fs = require('fs');
const shelljs = require('shelljs'); const jsFiles = [],
LOG__PATH = './diff.log',
FILE = /diff --git [a]([\s\S]*?) /g,
data = fs.readFileSync(LOG__PATH).toString(),
_files = data.match(FILE),
len = _files.length; let i = 0;
while (i < len) {
const _item = _files[i++].trim();
if (!/.js$/.test(_item)) continue;
const item = './' + _item.slice(13);
if (!/^\.\/src\//.test(item)) continue;
if (!fs.existsSync(item)) continue;
jsFiles.push(item);
}
if (jsFiles.length === 0) {
console.log('没有文件发生变化');
console.log('');
process.exit(1);
}
console.log('------------------------------');
console.log(' 以下文件发生改变: ');
console.log(jsFiles.join('\n'));
console.log('------------------------------');
shelljs.exec('node ./node_modules/eslint/bin/eslint.js ' + jsFiles.join(' '));

原理

通过git diff origin/dev获取到和dev分支的不同, 从而知道哪些文件需要进行代码检测(dev上的是通过检测的), 然后运行eslint的时候就指定这部分文件。

使用

在项目根目录下输入./lint.sh或者bash ./lint.sh, 默认的远程分支是dev, 如果需要和其他分支比较的话, 指定远程分支名,比如./lint.sh master

不足

  • 使用了bash, 导致这个看起来有点不伦不类, 使用纯js也许会更好, 但是我毕竟半吊子→_←
上一篇:Android LCD(二):LCD常用接口原理篇(转)


下一篇:C#数学运算表达式解释器