Git hooks 是强大的脚本,它们在 Git 仓库中特定事件发生时自动触发。通过巧妙地使用这些钩子,你可以大大提高工作效率,确保代码质量,并自动化许多重复性任务。让我们深入探讨一下你可以用 Git hooks 做些什么。
自动化分支管理
我们先来看一个实际的例子。以下是一个 post-checkout hook 脚本,它在切换分支时执行一些有用的操作:
bash
#!/bin/bash
set -e
CURRENT_BRANCH=$(git symbolic-ref --short HEAD)
PREV_BRANCH_FILE=".git/custom/previous_branch"
FEATURE_BUILD_FILE=".github/workflows/Feature_build.yml"
TEMPLATE_PATH="/path/to/your/template/Feature_build.yml"
# 定义颜色代码
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
log() {
local color="$1"
local message="$2"
echo -e "${color}[$(date +'%Y-%m-%d %H:%M:%S')] $message${NC}"
}
update_previous_branch() {
mkdir -p "$(dirname "$PREV_BRANCH_FILE")"
echo "$CURRENT_BRANCH" > "$PREV_BRANCH_FILE"
}
create_feature_build_file() {
if [[ ! -f "$FEATURE_BUILD_FILE" ]]; then
log "$YELLOW" "Creating $FEATURE_BUILD_FILE"
mkdir -p "$(dirname "$FEATURE_BUILD_FILE")"
cp "$TEMPLATE_PATH" "$FEATURE_BUILD_FILE"
sed -i '' "s/branches:.*/branches: ['$CURRENT_BRANCH']/" "$FEATURE_BUILD_FILE"
log "$GREEN" "Successfully created and updated $FEATURE_BUILD_FILE"
else
log "$BLUE" "$FEATURE_BUILD_FILE already exists"
fi
}
main() {
PREV_BRANCH=$(cat "$PREV_BRANCH_FILE" 2>/dev/null || echo "")
if [[ "$CURRENT_BRANCH" != "$PREV_BRANCH" ]]; then
log "$YELLOW" "Branch switched from $PREV_BRANCH to $CURRENT_BRANCH"
update_previous_branch
if [[ "$CURRENT_BRANCH" == feature* ]]; then
log "$GREEN" "Switched to a feature branch: $CURRENT_BRANCH"
create_feature_build_file
else
log "$BLUE" "Current branch is not a feature branch"
fi
else
log "$BLUE" "No branch switch detected"
fi
}
main
脚本功能详解
这个脚本作为一个 post-checkout hook,在每次切换分支时自动执行,从本地复制一个yml模板文件到当前分支的文件夹下面。应该不同的分支针对了不同的工作流文件,所以直接修改为了git切换分支的时候自动创建文件。