Created
December 30, 2025 03:02
-
-
Save vikingmute/e85e0b4249a65e41d64315c7790e5987 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # ============================================= | |
| # Git Worktree 快速管理助手 | |
| # 用法: | |
| # ga <branch-name> # 在平行目录创建新 worktree + 新分支,并自动 cd 进去 | |
| # gd # 删除当前 worktree 和对应分支(带确认) | |
| # | |
| # 依赖: | |
| # - gum[](https://github.com/charmbracelet/gum) 用于美观的确认对话框 | |
| # - mise (可选,如果你用 mise 管理工具版本) | |
| # ============================================= | |
| ga() { | |
| if [[ -z "$1" ]]; then | |
| echo "Usage: ga <branch-name>" | |
| return 1 | |
| fi | |
| local branch="$1" | |
| local base="$(basename "$PWD")" | |
| local path="../${base}-${branch}" | |
| git worktree add -b "$branch" "$path" || return 1 | |
| [[ -n "$(command -v mise)" ]] && mise trust "$path" # 可选:信任新目录 | |
| cd "$path" || return 1 | |
| echo "✅ Created worktree and switched to: $path (branch: $branch)" | |
| } | |
| gd() { | |
| if ! command -v gum >/dev/null 2>&1; then | |
| echo "❌ gd 需要 gum 来进行确认,请先安装:brew install gum 或查看 https://github.com/charmbracelet/gum" | |
| return 1 | |
| fi | |
| if ! gum confirm "🚨 删除当前 worktree 和对应分支?此操作不可恢复!"; then | |
| echo "❎ 操作已取消" | |
| return 0 | |
| fi | |
| local cwd="$(pwd)" | |
| local worktree="$(basename "$cwd")" | |
| # 根据目录名规则 base-branch 提取 root 和 branch | |
| local root="${worktree%-*}" | |
| local branch="${worktree#*-}" | |
| # 安全检查:确保目录名包含 "-",避免误删主仓库 | |
| if [[ "$root" == "$worktree" || "$root" == "$branch" ]]; then | |
| echo "❌ 当前目录名不符合 worktree 命名规则(应为 repo-branch),已阻止删除" | |
| return 1 | |
| fi | |
| cd "../$root" || { echo "❌ 无法切换到主目录"; return 1; } | |
| git worktree remove "$worktree" --force | |
| git branch -D "$branch" | |
| echo "🗑️ 已删除 worktree '$worktree' 和分支 '$branch'" | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment