git 提交代码检测

1,448 阅读1分钟

场景

经常有同事不小心把 debugger、或者无用的console、alert等提交到git上,所以想在代码提交前检测,发现不该提交的代码,禁止提交

步骤

1、安装依赖

npm install pre-commit --save-dev
npm instal husky --save-dev

2、在package.json中添加依赖

"scripts": {
    "check-keyword": "bash ./hooks/check-keyword.sh"
    "precommit":"npm run check-keyword"
  },
  "pre-commit": [
    "precommit"
  ],

3、需要在项目根目录下, 新建hooks/check-keyword.sh, 代码如下

#!/bin/bash

red=`tput setaf 1`
green=`tput setaf 2`
reset=`tput sgr0`
# echo "${red}red text ${green}green text${reset}"

echo  "${green}start checking keyword${reset}"


for FILE in `git diff --name-only --cached`; do

    if [[ $FILE == *".sh"* ]] || [[ $FILE == *"vendor/*"* ]] ||[[$FILE == *"node_modules/*"*]]||[[$FILE == *"public/*"*]]; then
        echo $FILE
        continue
    fi
    grep 'TODO:\|debugger\|console.log\|alert(' $FILE 2>&1 >/dev/null
    if [ $? -eq 0 ]; then
        echo $FILE '包含,TODO: or debugger or console.log,请删除后再提交'
        exit 1
    fi
    
done
exit

4、提交代码检测

在代码中添加debugger等,提交代码,检测一下是否能检测出来

5、使用

将hooks的配置和packagejson的配置提交,其他同事就可以用了