使用 husky 限制 git 提交

背景
在开发项目时候,我们默认都使用公司内部邮箱账号来提交代码。但开发外部项目(托管 GitHub)时候,就需要使用`git`命令设置外部邮箱。这时候如果输错或忘记切换账号,而使用内部邮箱提交到了外部仓库,则会出现内部邮箱泄露到 GitHub 的问题。

git config user.email "对应账号"

方案
为了解决上面问题, 可以使用 husky 做 pre commit 的钩子,然后用 shelljs 执行 "shell.exec('git config user.email')" 获取到 email, 再判断此账号是否在白名单中,以此来限制 git commit 操作.

详细步骤
1. 安装 husky:

npm install husky --save-dev 

2. 在 package.json 中配置:
- husky 中有很多操作 git 的 hooks,具体参考 husky, 此处我们只需配置 "pre-commit" ,即在 commit 前执行的命令.

"husky": {
  "hooks": {
  "pre-commit": "node check.js"
  }
},

3. 获取 git 中 user.email ,判断该邮箱是否允许 commit:
- 新建一个 js 文件(用于执行的脚本).

// check.js
const shell = require('shelljs');
const limit = ['@dudu', 'xiaojue'];

if (!shell.which('git')) {
  shell.echo('Sorry, this script requires git');
  shell.exit(1);
}

const email = shell.exec('git config user.email');

if (limit.some(v => email.indexOf(v) > -1)) {
  shell.exit(1);
}

  

-- end --

posted @ 2020-03-05 17:24  lmy_moonsky  阅读(1734)  评论(0编辑  收藏  举报