eslint + pre-commit检测代码

良好的代码规范有助于项目的维护和新人的快速上手。前段时间,把eslint引入了项目中做静态代码检查。 一下把所有的代码都改造是不可能,要改的地方太多,而且要保证后来提交代码的质量。于是有了eslint + pre-commit 的结合。
  pre-commit是git的钩子,顾名思义就是在提交前运行,所以一般用于代码检查、单元测试。git还有其他钩子,比如prepare-commit-msg、pre-push等,具体可查看git官网。git 钩子目录在.git/hooks下(如下图):

git-hooks.png


  上图这些文件都是对应钩子的示例脚本,.sample后缀都是出于未启动状态。对应的钩子要生效,把.sample去掉。示例都是用shell脚本写的。那如果想用js写怎么办呢?需要借助pre-commit库

 

  1. 安装pre-commit
npm install pre-commit --save-dev
  1. 配置package.json
  • 执行静态文件检查
// package.json
"scripts": {
    "lint": "eslint src --ext .js --cache --fix",
  },
  "pre-commit": [
    "lint",
  ]

上面配置会保证eslint在提交时会校验src目录下的js文件。
那如果要动态获取提交的代码进行校验呢?

  • 校验提交代码
// 获取修改后的js文件
git diff HEAD --name-only| grep .js$

package.json文件可改为:

// package.json
"scripts": {
     "lint": "eslint src --ext .js --cache --fix",
     "pre-lint": "node check.js"
},
"pre-commit": [
     "pre-lint",
]

在check.js中需要调用eslint的Node.js API,详情可看eslint官网。以下是我在项目中的例子,可作为参考:

// check.js
const exec = require('child_process').exec
const CLIEngine = require('eslint').CLIEngine
const cli = new CLIEngine({})
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| grep .js$', (error, stdout) => {
    if (stdout.length) {
        const array = stdout.split('\n')
        array.pop()
        const results = cli.executeOnFiles(array).results
        let errorCount = 0
        let warningCount = 0
        results.forEach((result) => {
            errorCount += result.errorCount
            warningCount += result.warningCount
            if (result.messages.length > 0) {
                console.log('\n')
                console.log(result.filePath)
                result.messages.forEach((obj) => {
                    const level = getErrorLevel(obj.severity)
                    console.log(`   ${obj.line}:${obj.column}  ${level}  ${obj.message}  ${obj.ruleId}`)
                    pass = 1
                })
            }
        })
        if (warningCount > 0 || errorCount > 0) {
            console.log(`\n   ${errorCount + warningCount} problems (${errorCount} ${'errors'} ${warningCount} warnings)`)
        }
        process.exit(pass)
    }
    if (error !== null) {
        console.log(`exec error: ${error}`)
    }
})



作者:du_4c0c
链接:https://www.jianshu.com/p/072a96633479
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

转载于:https://my.oschina.net/u/4000302/blog/3033462

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值