eslint + pre-commit檢測代碼

良好的代碼規範有助於項目的維護和新人的快速上手。前段時間,把eslint引入了項目中作靜態代碼檢查。 一下把全部的代碼都改造是不可能,要改的地方太多,並且要保證後來提交代碼的質量。因而有了eslint + pre-commit 的結合。
  pre-commit是git的鉤子,顧名思義就是在提交前運行,因此通常用於代碼檢查、單元測試。git還有其餘鉤子,好比prepare-commit-msg、pre-push等,具體可查看git官網。git 鉤子目錄在.git/hooks下(以下圖):node

git-hooks.pnggit


  上圖這些文件都是對應鉤子的示例腳本,.sample後綴都是出於未啓動狀態。對應的鉤子要生效,把.sample去掉。示例都是用shell腳本寫的。那若是想用js寫怎麼辦呢?須要藉助pre-commit庫github

 

  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文件。
那若是要動態獲取提交的代碼進行校驗呢?shell

  • 校驗提交代碼
// 獲取修改後的js文件
git diff HEAD --name-only| grep .js$

package.json文件可改成:npm

// 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官網。如下是我在項目中的例子,可做爲參考:json

// 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
來源:簡書
簡書著做權歸做者全部,任何形式的轉載都請聯繫做者得到受權並註明出處。api

相關文章
相關標籤/搜索