# ===== CodeLab: Git Hooks 自动化 =====
# 来源: https://aoerliang.dpdns.org/articles/git-hooks
# 以下代码片段按文章出现顺序拼接, 共 5 段

# ----- 片段 1 (bash) -----
ls .git/hooks/
# pre-commit.sample  commit-msg.sample  pre-push.sample ...

# 启用钩子:去掉 .sample 后缀并加执行权限
mv .git/hooks/pre-commit.sample .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit

# ----- 片段 2 (bash) -----
#!/bin/sh
# .git/hooks/pre-commit
files=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(js|ts)$')
for f in $files; do
  if git show :"$f" | grep -nE 'console\.log|debugger'; then
    echo "错误: $f 包含调试代码,禁止提交!"
    exit 1
  fi
done
exit 0

# ----- 片段 3 (bash) -----
#!/bin/sh
# .git/hooks/commit-msg
msg=$(cat "$1")
if ! echo "$msg" | grep -qE '^(feat|fix|docs|refactor|chore|test)\([a-z-]+\): .+'; then
  echo "提交信息不符合规范: type(scope): subject"
  echo "示例: feat(login): 增加验证码登录"
  exit 1
fi

# ----- 片段 4 (bash) -----
#!/bin/sh
# .git/hooks/pre-push
echo "=== 推送前运行测试 ==="
npm test
if [ $? -ne 0 ]; then
  echo "测试失败,已阻止推送!"
  exit 1
fi

# ----- 片段 5 (bash) -----
# scripts/install-hooks.sh
#!/bin/sh
for hook in pre-commit commit-msg pre-push; do
  ln -sf ../../scripts/hooks/$hook .git/hooks/$hook
done
echo "钩子安装完成"
