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

缘起

在项目中, 一般都邑运用代码检测工具来范例团队的代码作风, 比方eslint。跟着代码的不停增添, eslint举行代码检测的时刻也愈来愈久。每次检测的时刻, 须要检测的文件和现实检测的文件极端不对称,所以便基于git diff写了如许一个小工具。

2016/11/02更新

因为之前关于一系列的敕令不够熟习,在剧本中同时运用了nodejsbash, 而且经由过程文件来传递信息, 以下为改进后版本, 纯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}";
if [ $1 ]; then
  br=$1;
fi;

log=`git diff origin/${br} --name-only | grep js | grep src/`;
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 1000 --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;

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;
  echo -e "${INFO}done ...${NOR}";
fi;
rm diff.log change.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; // src为eslint须要检测的顶级目次
  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或许会更好, 然则我毕竟半吊子→_←

  • 没有对error举行高亮显现, 所以看起来照样会比较辛苦

    原文作者:374632897
    原文地址: https://segmentfault.com/a/1190000006503418
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞