项目中如果填写了一些密钥、账号、密码等敏感信息,我们一般不希望把这些数据上传到git仓库中,避免隐私泄露。
以下是一种通过 pre-commit
实现的敏感数据检测方案:
利用 .git/hooks/pre-commit
来实现一个 shell
脚本,检测指定 token
,即敏感信息,然后将拒绝提交,并给出报错信息。
-
找到项目中的
.git/hooks
文件夹,在里面创建一个pre-commit
文件(没有任何后缀名),通过git
提交前,会自动执行这个脚本; -
在
pre-commit
中写入:#!/bin/bash # 定义敏感信息模式 sensitive_patterns=("password" "api_key" "secret" "token") # 扫描所有已暂存的文件 files=$(git diff --cached --name-only) found_sensitive_info=false for file in $files; do if [ -f "$file" ]; then for pattern in "${sensitive_patterns[@]}"; do if grep -q "$pattern" "$file"; then echo "Sensitive information detected in file: $file" echo "Pattern: $pattern" found_sensitive_info=true fi done fi done # 如果发现敏感信息,拒绝提交 if [ "$found_sensitive_info" = true ]; then echo "Commit rejected due to sensitive information." exit 1 fi
sensitive_patterns
中就是字符串形式的敏感信息; -
然后通过
git commit
提交时,如果存在上述信息,就会报错并拒绝提交:20:48:07.752: [demo] git -c credential.helper= -c core.quotepath=false -c log.showSignature=false add --ignore-errors -A -f -- src/main/resources/application.yml src/main/java/cn/comradexy/demo/config/DemoConfig.java .gitignore 20:48:07.809: [demo] git -c credential.helper= -c core.quotepath=false -c log.showSignature=false commit -F C:\Users\71969\AppData\Local\Temp\git-commit-msg-.txt -- Sensitive information detected in file: src/main/resources/application.yml Pattern: password Commit rejected due to sensitive information.
-
手动修改后,重新提交,就可以避免敏感信息的泄露。