name: git-workspace-init description: “初始化一个新的git工作树和分支用于功能开发或bug修复。使用场景:(1) 开始新功能开发,(2) 开始bug修复,(3) 为任何任务创建隔离的工作空间,(4) 需要在多个分支上并行工作。此技能处理遵循约定分支命名的分支命名、工作树创建和远程推送设置。”
Git工作空间初始化
使用遵循约定分支命名规范的适当命名分支,初始化一个隔离的git工作树。
使用时机
- 开始新功能开发
- 开始bug修复
- 创建热修复
- 文档更新
- 重构工作
- 任何需要隔离工作空间的任务
前提条件
- 配置了远程仓库的Git仓库
- 推送分支的写入权限
工作流程概览
- 获取任务详情 → 询问类型和描述(或从命令接受)
- 生成分支名称 → 应用约定分支命名
- 创建工作树 → 设置隔离工作空间
- 推送到远程 → 在origin上跟踪分支
- 导航 → 切换到新工作空间
步骤1:收集任务信息
向用户询问或从命令参数接受:
任务类型
| 类型 | 使用场景 | 示例 |
|---|---|---|
feat |
新功能 | feat/user-authentication |
fix |
Bug修复 | fix/login-validation-error |
hotfix |
紧急生产修复 | hotfix/security-patch |
docs |
文档 | docs/api-reference |
refactor |
代码重构 | refactor/extract-service |
test |
测试添加 | test/auth-integration |
chore |
维护 | chore/upgrade-dependencies |
perf |
性能改进 | perf/optimize-queries |
ci |
CI/CD变更 | ci/add-deploy-workflow |
style |
代码风格/格式化 | style/apply-prettier |
任务描述
将成为分支名称后缀的简短描述:
- 使用小写
- 使用连字符代替空格
- 保持简洁但具有描述性
示例:
- “用户认证” →
user-authentication - “修复验证错误” →
validation-error - “添加深色模式” →
dark-mode
步骤2:生成分支名称
格式:<类型>/<描述>
# 示例
feat/user-authentication
fix/null-pointer-exception
hotfix/xss-vulnerability
docs/installation-guide
refactor/extract-user-service
命名规则
- 仅小写 -
feat/Add-User→feat/add-user - 空格用连字符 -
fix/login error→fix/login-error - 无特殊字符 - 仅允许
a-z、0-9、-、/ - 简洁 - 总长度保持在50个字符以内
- 描述性 - 应表明正在进行的工作
辅助函数
import re
def generate_branch_name(task_type: str, description: str) -> str:
"""根据类型和描述生成约定分支名称。"""
valid_types = ["feat", "fix", "hotfix", "docs", "refactor", "test", "chore", "perf", "ci", "style"]
if task_type not in valid_types:
raise ValueError(f"无效类型 '{task_type}'。必须是以下之一:{', '.join(valid_types)}")
# 规范化描述
normalized = description.lower().strip()
# 将空格和下划线替换为连字符
normalized = re.sub(r'[\s_]+', '-', normalized)
# 移除无效字符
normalized = re.sub(r'[^a-z0-9-]', '', normalized)
# 移除连续连字符
normalized = re.sub(r'-+', '-', normalized)
# 去除两端的连字符
normalized = normalized.strip('-')
return f"{task_type}/{normalized}"
步骤3:创建Git工作树
工作树允许在不存储或切换的情况下同时处理多个分支。
默认工作树位置
工作树在仓库根目录的.worktrees目录中创建:
my-project/
├── .worktrees/
│ ├── feat-user-auth/ # feat/user-auth的工作树
│ └── fix-login-error/ # fix/login-error的工作树
├── src/
└── ...
创建工作树命令
# 获取仓库根目录
REPO_ROOT=$(git rev-parse --show-toplevel)
# 定义工作树目录(将/替换为-作为目录名)
BRANCH_NAME="feat/user-authentication"
WORKTREE_DIR="$REPO_ROOT/.worktrees/${BRANCH_NAME//\//-}"
# 确保.worktrees目录存在
mkdir -p "$REPO_ROOT/.worktrees"
# 从main/master创建新分支的工作树
git worktree add -b "$BRANCH_NAME" "$WORKTREE_DIR" origin/main
工作流程
import subprocess
import os
def create_worktree(branch_name: str, base_branch: str = "main") -> str:
"""为给定分支创建新的工作树。"""
# 获取仓库根目录
result = subprocess.run(
["git", "rev-parse", "--show-toplevel"],
capture_output=True, text=True, check=True
)
repo_root = result.stdout.strip()
# 创建工作树目录名(将/替换为-)
worktree_dir_name = branch_name.replace("/", "-")
worktree_path = os.path.join(repo_root, ".worktrees", worktree_dir_name)
# 确保.worktrees目录存在
os.makedirs(os.path.join(repo_root, ".worktrees"), exist_ok=True)
# 从远程获取最新
subprocess.run(["git", "fetch", "origin"], check=True)
# 创建新分支的工作树
subprocess.run(
["git", "worktree", "add", "-b", branch_name, worktree_path, f"origin/{base_branch}"],
check=True
)
return worktree_path
步骤4:推送分支到远程
设置与远程仓库的跟踪:
# 在新工作树内
cd "$WORKTREE_DIR"
# 推送并设置上游
git push -u origin "$BRANCH_NAME"
工作流程
def push_branch(worktree_path: str, branch_name: str):
"""将新分支推送到远程并设置跟踪。"""
subprocess.run(
["git", "-C", worktree_path, "push", "-u", "origin", branch_name],
check=True
)
步骤5:导航到工作空间
创建后,导航到新的工作树:
cd "$WORKTREE_DIR"
pwd
git status
重要: 告知用户新工作空间的路径,以便他们可以在终端中导航到那里。
完整示例
import subprocess
import os
import re
def generate_branch_name(task_type: str, description: str) -> str:
"""生成约定分支名称。"""
valid_types = ["feat", "fix", "hotfix", "docs", "refactor", "test", "chore", "perf", "ci", "style"]
if task_type not in valid_types:
raise ValueError(f"无效类型。必须是以下之一:{', '.join(valid_types)}")
normalized = description.lower().strip()
normalized = re.sub(r'[\s_]+', '-', normalized)
normalized = re.sub(r'[^a-z0-9-]', '', normalized)
normalized = re.sub(r'-+', '-', normalized)
normalized = normalized.strip('-')
return f"{task_type}/{normalized}"
def init_workspace(task_type: str, description: str, base_branch: str = "main") -> dict:
"""
使用约定分支命名初始化新的git工作树。
参数:
task_type: 工作类型(feat, fix, hotfix, docs, refactor, test, chore, perf, ci, style)
description: 任务的简短描述
base_branch: 新分支基于的分支(默认:main)
返回:
包含branch_name、worktree_path和success状态的字典
"""
# 生成分支名称
branch_name = generate_branch_name(task_type, description)
print(f"分支名称:{branch_name}")
# 获取仓库根目录
result = subprocess.run(
["git", "rev-parse", "--show-toplevel"],
capture_output=True, text=True, check=True
)
repo_root = result.stdout.strip()
# 创建工作树路径
worktree_dir_name = branch_name.replace("/", "-")
worktree_path = os.path.join(repo_root, ".worktrees", worktree_dir_name)
# 确保.worktrees存在
os.makedirs(os.path.join(repo_root, ".worktrees"), exist_ok=True)
# 获取最新
print("从origin获取最新...")
subprocess.run(["git", "fetch", "origin"], check=True)
# 创建新分支的工作树
print(f"创建工作树于:{worktree_path}")
subprocess.run(
["git", "worktree", "add", "-b", branch_name, worktree_path, f"origin/{base_branch}"],
check=True
)
# 推送分支到远程
print(f"推送{branch_name}到origin...")
subprocess.run(
["git", "-C", worktree_path, "push", "-u", "origin", branch_name],
check=True
)
# 验证
print(f"
工作空间已初始化!")
print(f" 分支:{branch_name}")
print(f" 路径:{worktree_path}")
print(f"
开始工作:")
print(f" cd {worktree_path}")
return {
"branch_name": branch_name,
"worktree_path": worktree_path,
"success": True
}
# 使用示例:
# init_workspace("feat", "user authentication")
# init_workspace("fix", "login validation error")
# init_workspace("docs", "API reference update")
快速参考
分支类型速查表
| 类型 | 使用时机 |
|---|---|
feat |
添加新功能 |
fix |
修复bug |
hotfix |
紧急生产修复 |
docs |
仅文档 |
refactor |
重构而不改变行为 |
test |
添加或修复测试 |
chore |
构建、依赖、工具 |
perf |
性能改进 |
ci |
CI/CD流水线变更 |
style |
格式化、空格 |
工作树命令
# 列出所有工作树
git worktree list
# 移除工作树(完成后)
git worktree remove <路径>
# 清理过时工作树
git worktree prune
合并后清理
PR合并后:
# 移除工作树
git worktree remove .worktrees/feat-user-authentication
# 删除本地分支(如果未自动删除)
git branch -d feat/user-authentication
# 清理远程跟踪分支
git fetch --prune
错误处理
分支已存在
fatal: 名为'feat/user-auth'的分支已存在。
解决方案: 选择更具体的名称或检查是否已有进行中的工作。
工作树路径已存在
fatal: '<路径>'已存在
解决方案: 工作树已存在。使用git worktree list查找。
未配置远程
fatal: 未配置推送目标。
解决方案: 先添加远程:git remote add origin <url>