使用 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 --


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM