Git Hooks Pre-Commit CI Pipeline
Enforce quality gates with a pre-commit hook running lint and format checks, mirrored by the CI pipeline stages.
Code
#!/usr/bin/env bash
# .git/hooks/pre-commit —— 提交前的本地质量门禁
set -euo pipefail
fail() { echo "Error: $*" >&2; exit 1; }
command -v shellcheck >/dev/null || fail "shellcheck 未安装"
# 只检查暂存区里真实变更的文件
mapfile -t staged < <(git diff --cached --name-only --diff-filter=ACM)
lint_shell() {
local scripts=()
for f in "${staged[@]}"; do
[[ "$f" == *.sh ]] && scripts+=("$f")
done
(( ${#scripts[@]} == 0 )) && return 0
shellcheck "${scripts[@]}" || fail "shellcheck 未通过,请修复后重提"
}
check_secrets() {
# 密钥模式粗筛:防凭据误入版本库
local pattern='(AKIA[0-9A-Z]{16}|sk-live-[a-zA-Z0-9]{20,}|BEGIN RSA PRIVATE KEY)'
for f in "${staged[@]}"; do
[[ -f "$f" ]] || continue
if git diff --cached -- "$f" | grep -E "${pattern}" >/dev/null; then
fail "疑似密钥泄漏: ${f}"
fi
done
}
lint_shell
check_secrets
echo "pre-commit 检查通过:${#staged[@]} 个文件"
# CI 流水线中的镜像阶段(.gitlab-ci.yml 节选):
# stages: [lint, test]
# lint:shellcheck:
# stage: lint
# script:
# - shellcheck scripts/*.sh
# lint:secrets:
# stage: lint
# script:
# - gitleaks detect --source . --staged
Report a problem with this exampleOpens a pre-filled issue on GitHub.