Skip to content

Git 分支命名规范

概述

良好的分支命名规范可以提高团队协作效率,便于识别分支用途,自动化工具也能更好地处理分支。本指南将介绍常见的分支命名规范、前缀约定和工具支持。

分支命名规范

基本原则

  1. 简洁明了: 分支名应清晰表达分支用途
  2. 统一格式: 团队应遵循统一的命名格式
  3. 避免特殊字符: 只使用小写字母、数字、连字符和斜杠
  4. 长度适中: 不超过 50 个字符

命名格式

<type>/<issue-id>-<description>

<type>-<issue-id>-<description>

前缀约定

常用前缀

前缀说明示例
feature新功能feature/123-user-authentication
fixBug 修复fix/456-login-error
bugfixBug 修复(替代)bugfix/456-login-error
hotfix紧急修复hotfix/789-security-patch
release发布分支release/1.0.0
support支持分支support/1.0.x
docs文档更新docs/123-api-documentation
refactor重构refactor/456-user-module
test测试test/123-auth-tests
chore杂项chore/456-update-dependencies

功能分支

bash
# 新功能开发
feature/123-user-authentication
feature/124-payment-integration
feature/125-dashboard-redesign

# 命名规则
feature/<issue-id>-<short-description>

修复分支

bash
# Bug 修复
fix/456-login-validation-error
fix/457-memory-leak
fix/458-api-timeout

# 紧急修复
hotfix/789-critical-security-issue
hotfix/790-payment-failure

# 命名规则
fix/<issue-id>-<short-description>
hotfix/<version>-<short-description>

发布分支

bash
# 版本发布
release/1.0.0
release/2.0.0-beta
release/2.0.0-rc.1

# 命名规则
release/<version>
release/<version>-<prerelease>

其他分支

bash
# 文档
docs/123-api-documentation
docs/456-readme-update

# 重构
refactor/123-user-module
refactor/456-database-layer

# 测试
test/123-auth-integration
test/456-e2e-tests

# 杂项
chore/123-update-dependencies
chore/456-ci-configuration

命名最佳实践

使用 Issue 编号

bash
# 好的实践: 包含 Issue 编号
feature/123-user-authentication
fix/456-login-error

# 便于追踪和关联
# 可以在 Issue 中看到相关分支
# 可以在 PR 中自动关闭 Issue

使用连字符分隔

bash
# 好的实践: 使用连字符
feature/123-user-authentication
fix/456-login-error

# 不好的实践: 使用下划线或驼峰
feature/123_user_authentication
fix/456LoginError

描述简洁明了

bash
# 好的实践: 简洁描述
feature/123-user-auth
fix/456-login-error

# 不好的实践: 过长描述
feature/123-implement-user-authentication-with-jwt-tokens
fix/456-fix-the-login-validation-error-that-occurs-when-user-submits-empty-form

避免个人信息

bash
# 好的实践: 描述功能
feature/123-user-authentication

# 不好的实践: 包含个人信息
feature/john-auth-work
feature/123-john-working-on-auth

工作流分支策略

Git Flow 分支命名

bash
# 主要分支
main
master
develop

# 特性分支
feature/123-user-auth
feature/124-payment-system

# 发布分支
release/1.0.0
release/2.0.0

# 热修复分支
hotfix/1.0.1
hotfix/2.0.1

GitHub Flow 分支命名

bash
# 主分支
main

# 特性分支
feature/123-user-auth
fix/456-login-error
docs/789-api-documentation

GitLab Flow 分支命名

bash
# 环境分支
main
staging
production

# 特性分支
feature-123-user-auth
fix-456-login-error

# 发布分支
release-1.0.0

Trunk Based 分支命名

bash
# 主分支
main

# 短期分支(使用用户名或时间戳)
username/feature-123
username/fix-456
2024-01-01-feature

工具支持

Git 别名

bash
# 创建分支别名
git config --global alias.feature '!git checkout -b feature/$1'
git config --global alias.fix '!git checkout -b fix/$1'
git config --global alias.hotfix '!git checkout -b hotfix/$1'

# 使用别名
git feature 123-user-auth
git fix 456-login-error
git hotfix 789-security-patch

Git Hooks

创建 .git/hooks/pre-push:

bash
#!/bin/bash

# 检查分支命名规范
branch=$(git rev-parse --abbrev-ref HEAD)

# 允许的分支前缀
valid_prefixes=(
  "feature"
  "fix"
  "hotfix"
  "release"
  "docs"
  "refactor"
  "test"
  "chore"
  "main"
  "master"
  "develop"
  "staging"
  "production"
)

# 检查是否匹配前缀
valid=false
for prefix in "${valid_prefixes[@]}"; do
  if [[ $branch == $prefix/* ]] || [[ $branch == $prefix-* ]] || [[ $branch == $prefix ]]; then
    valid=true
    break
  fi
done

if [ "$valid" = false ]; then
  echo "错误: 分支名称不符合规范"
  echo "分支名应以以下前缀开头:"
  printf '  - %s\n' "${valid_prefixes[@]}"
  echo "示例: feature/123-user-auth, fix/456-login-error"
  exit 1
fi

exit 0

Husky + Branch Name Lint

bash
# 安装
npm install --save-dev husky branch-name-lint

# 配置 package.json
{
  "scripts": {
    "branch-lint": "branch-name-lint"
  },
  "branchNameLint": {
    "pattern": "^(feature|fix|hotfix|release|docs|refactor|test|chore)/(\\d+)-([a-z0-9-]+)$",
    "allowedBranches": [
      "main",
      "master",
      "develop",
      "staging",
      "production"
    ],
    "msgBranch": "分支名称不符合规范",
    "msgPattern": "分支名应匹配: type/issue-id-description"
  }
}

# 添加 Husky hook
npx husky add .husky/pre-push 'npm run branch-lint'

GitHub Actions 检查

yaml
# .github/workflows/branch-check.yml
name: Branch Name Check

on:
  push:
    branches-ignore:
      - main
      - master
      - develop

jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - name: Check branch name
        run: |
          BRANCH_NAME="${GITHUB_REF#refs/heads/}"
          
          # 允许的前缀
          VALID_PREFIXES=("feature" "fix" "hotfix" "release" "docs" "refactor" "test" "chore")
          
          # 检查前缀
          VALID=false
          for PREFIX in "${VALID_PREFIXES[@]}"; do
            if [[ $BRANCH_NAME == $PREFIX/* ]] || [[ $BRANCH_NAME == $PREFIX-* ]]; then
              VALID=true
              break
            fi
          done
          
          if [ "$VALID" = false ]; then
            echo "❌ 分支名称不符合规范: $BRANCH_NAME"
            echo "分支名应以以下前缀开头:"
            printf '  - %s\n' "${VALID_PREFIXES[@]}"
            exit 1
          fi
          
          echo "✅ 分支名称符合规范: $BRANCH_NAME"

GitLab CI 检查

yaml
# .gitlab-ci.yml
branch-check:
  stage: test
  script:
    - |
      BRANCH_NAME="${CI_COMMIT_REF_NAME}"
      
      # 允许的前缀
      VALID_PREFIXES=("feature" "fix" "hotfix" "release" "docs" "refactor" "test" "chore")
      
      # 检查前缀
      VALID=false
      for PREFIX in "${VALID_PREFIXES[@]}"; do
        if [[ $BRANCH_NAME == $PREFIX/* ]] || [[ $BRANCH_NAME == $PREFIX-* ]]; then
          VALID=true
          break
        fi
      done
      
      if [ "$VALID" = false ]; then
        echo "❌ 分支名称不符合规范: $BRANCH_NAME"
        exit 1
      fi
      
      echo "✅ 分支名称符合规范: $BRANCH_NAME"
  only:
    - branches
  except:
    - main
    - master
    - develop

分支管理脚本

创建分支脚本

bash
#!/bin/bash
# create-branch.sh

TYPE=$1
ISSUE_ID=$2
DESCRIPTION=$3

if [ -z "$TYPE" ] || [ -z "$ISSUE_ID" ] || [ -z "$DESCRIPTION" ]; then
  echo "用法: ./create-branch.sh <type> <issue-id> <description>"
  echo "示例: ./create-branch.sh feature 123 user-authentication"
  exit 1
fi

# 转换描述为小写并替换空格为连字符
DESCRIPTION=$(echo "$DESCRIPTION" | tr '[:upper:]' '[:lower:]' | tr ' ' '-')

# 创建分支名
BRANCH_NAME="${TYPE}/${ISSUE_ID}-${DESCRIPTION}"

# 创建分支
git checkout -b "$BRANCH_NAME"

echo "✅ 创建分支: $BRANCH_NAME"

清理分支脚本

bash
#!/bin/bash
# cleanup-branches.sh

# 删除已合并的本地分支
git branch --merged main | grep -v "^\*\|main\|master\|develop" | xargs -n 1 git branch -d

# 删除已合并的远程分支
git branch -r --merged main | grep -v "main\|master\|develop" | sed 's/origin\///' | xargs -n 1 git push --delete origin

# 清理远程分支引用
git fetch -p

echo "✅ 分支清理完成"

分支列表脚本

bash
#!/bin/bash
# list-branches.sh

echo "=== 本地分支 ==="
git branch --format='%(refname:short) - %(subject)'

echo ""
echo "=== 远程分支 ==="
git branch -r --format='%(refname:short) - %(subject)'

echo ""
echo "=== 按类型分组 ==="
echo "Feature 分支:"
git branch | grep "^  feature/"

echo "Fix 分支:"
git branch | grep "^  fix/"

echo "Hotfix 分支:"
git branch | grep "^  hotfix/"

echo "Release 分支:"
git branch | grep "^  release/"

团队规范文档

分支规范文档

创建 BRANCHING.md:

markdown
# 分支命名规范

## 命名格式

<type>/<issue-id>-<description>


<type>-<issue-id>-<description>


## 类型说明

| 类型 | 说明 | 示例 |
|------|------|------|
| feature | 新功能 | feature/123-user-auth |
| fix | Bug 修复 | fix/456-login-error |
| hotfix | 紧急修复 | hotfix/789-security-patch |
| release | 发布分支 | release/1.0.0 |
| docs | 文档更新 | docs/123-api-docs |
| refactor | 重构 | refactor/456-user-module |
| test | 测试 | test/123-auth-tests |
| chore | 杂项 | chore/456-deps-update |

## 命名规则

1. 使用小写字母
2. 使用连字符分隔单词
3. 包含 Issue 编号
4. 描述简洁明了
5. 不超过 50 个字符

## 示例

### 好的示例
- feature/123-user-authentication
- fix/456-login-validation-error
- hotfix/789-critical-security-issue
- release/1.0.0

### 不好的示例
- john-auth-work
- feature/UserAuthentication
- fix_456_login_error
- feature/123-implement-user-authentication-with-jwt-tokens

## 工作流程

1. 从 main 创建新分支
2. 开发完成后创建 PR
3. 代码审查通过后合并
4. 删除已合并的分支

总结

良好的分支命名规范带来的好处:

团队协作:

  • 快速识别分支用途
  • 便于追踪 Issue 关联
  • 提高代码审查效率

自动化支持:

  • CI/CD 流水线过滤
  • 自动生成变更日志
  • 自动关闭 Issue

项目管理:

  • 便于统计分支数量
  • 清晰的开发进度
  • 规范的发布流程

通过遵循分支命名规范,可以显著提高项目的可维护性和团队协作效率。