Created
December 30, 2025 14:09
-
-
Save vikingmute/0c641db6a834a7a6bee7bd677323bc97 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 快速管理助手 (路径增强版) | |
| # ============================================= | |
| # 定义绝对路径,绕过 PATH 查找问题 | |
| # 如果你的 gum 也是 homebrew 安装的,通常也在同一个目录下 | |
| GIT_EXE="/opt/homebrew/bin/git" | |
| GUM_EXE="/opt/homebrew/bin/gum" | |
| MISE_EXE="/opt/homebrew/bin/mise" | |
| # 备选方案:如果绝对路径失效,退回到 command 查找 | |
| [[ ! -f "$GIT_EXE" ]] && GIT_EXE="git" | |
| [[ ! -f "$GUM_EXE" ]] && GUM_EXE="gum" | |
| [[ ! -f "$MISE_EXE" ]] && MISE_EXE="mise" | |
| gwa() { | |
| if [[ -z "$1" ]]; then | |
| echo "Usage: gwa <branch-name>" | |
| return 1 | |
| fi | |
| local branch="$1" | |
| local base="$(basename "$PWD")" | |
| local path="../${base}-${branch}" | |
| # 使用硬编码的路径执行 | |
| $GIT_EXE worktree add -b "$branch" "$path" || return 1 | |
| # 检查并信任新目录 (mise) | |
| if command -v $MISE_EXE >/dev/null 2>&1; then | |
| $MISE_EXE trust "$path" | |
| fi | |
| cd "$path" || return 1 | |
| echo "✅ Created worktree and switched to: $path (branch: $branch)" | |
| } | |
| gwd() { | |
| # 1. 检查 gum 确认 | |
| if ! command -v $GUM_EXE >/dev/null 2>&1; then | |
| echo "❌ gd 需要 gum。请执行: brew install gum" | |
| return 1 | |
| fi | |
| # 2. 获取当前是否在 worktree 中,以及主仓库的路径 | |
| # git rev-parse --git-common-dir 会返回主仓库的 .git 目录路径 | |
| local common_dir=$($GIT_EXE rev-parse --git-common-dir 2>/dev/null) | |
| if [[ -z "$common_dir" ]]; then | |
| echo "❌ 当前不在 Git 仓库中" | |
| return 1 | |
| fi | |
| # 主仓库的实际物理路径 | |
| local main_repo_path=$(cd "$common_dir/.." && pwd) | |
| local current_dir=$(pwd) | |
| # 如果当前就在主仓库,禁止删除 | |
| if [[ "$current_dir" == "$main_repo_path" ]]; then | |
| echo "❌ 警告:你当前就在主仓库中,不能删除自己!" | |
| return 1 | |
| fi | |
| if ! $GUM_EXE confirm "🚨 确认删除当前 worktree 和对应分支?"; then | |
| echo "❎ 操作已取消" | |
| return 0 | |
| fi | |
| local worktree_name="$(basename "$current_dir")" | |
| local branch_name=$($GIT_EXE rev-parse --abbrev-ref HEAD) | |
| # 3. 先跳回主仓库目录,这样才能执行删除操作 | |
| cd "$main_repo_path" || { echo "❌ 无法回退到主仓库目录: $main_repo_path"; return 1; } | |
| # 4. 执行删除 | |
| $GIT_EXE worktree remove "$worktree_name" --force | |
| $GIT_EXE branch -D "$branch_name" | |
| echo "🗑️ 已清理完成!" | |
| echo "📍 当前已回到主仓库: $main_repo_path" | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment