-
-
Save robsimpsondev/4bcff48696c4c062fd6780cf3b05a37d to your computer and use it in GitHub Desktop.
Create and delete git worktrees quickly
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
| confirm() { | |
| # call with a prompt string or use a default | |
| read -r -p "${1:-Are you sure? [y/N]} " response | |
| case "$response" in | |
| [yY][eE][sS]|[yY]) | |
| true | |
| ;; | |
| *) | |
| false | |
| ;; | |
| esac | |
| } | |
| # Create a new worktree and branch from within current git directory. | |
| gwa() { | |
| if [ $# -eq 0 ]; then | |
| echo "Usage: gwa [branch name]" | |
| return 1 | |
| fi | |
| local branch="$1" | |
| local base="$(basename "$PWD")" | |
| local new="../${base}--${branch}" | |
| git worktree add -b "$branch" "$new" | |
| cd "$new" | |
| } | |
| # Remove worktree and branch from within active worktree directory. | |
| gwd() { | |
| if confirm "Remove current worktree and branch? [y/N]"; then | |
| local cwd base branch root | |
| cwd="$(pwd)" | |
| worktree="$(basename "$cwd")" | |
| # split on first `--` | |
| root="${worktree%%--*}" | |
| branch="${worktree#*--}" | |
| # Protect against accidentially nuking a non-worktree directory | |
| if [[ "$root" != "$worktree" ]]; then | |
| cd "../$root" | |
| git worktree remove "$worktree" --force | |
| git branch -D "$branch" | |
| fi | |
| fi | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment