Created
June 17, 2026 15:59
-
-
Save vikrum/7b36145ee54219a25ccba7831736ab0e to your computer and use it in GitHub Desktop.
worktree helpers
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
| # newt: fresh worktree off origin/main (ignores current branch/dirty state) + cd into it | |
| function newt() { | |
| local toplevel parent repo branch newdir | |
| toplevel=$(git rev-parse --show-toplevel 2>/dev/null) || { | |
| echo "newt: not inside a git repository" >&2 | |
| return 1 | |
| } | |
| repo=$(basename "$(dirname "$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null)")") | |
| parent=$(dirname "$toplevel") | |
| branch="$(whoami)-$(date +%s)" | |
| newdir="$parent/$repo-$branch" | |
| echo "newt: fetching origin/main..." >&2 | |
| git fetch origin main || { | |
| echo "newt: 'git fetch origin main' failed" >&2 | |
| return 1 | |
| } | |
| git worktree add -b "$branch" "$newdir" origin/main || { | |
| echo "newt: failed to create worktree at $newdir" >&2 | |
| return 1 | |
| } | |
| cd "$newdir" && echo "newt: now in $newdir on branch $branch" >&2 | |
| } |
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
| # rmwt: remove the current worktree and delete its local branch (cleanup after newt) | |
| function rmwt() { | |
| local toplevel branch common main_toplevel | |
| toplevel=$(git rev-parse --show-toplevel 2>/dev/null) || { | |
| echo "rmwt: not inside a git repository" >&2 | |
| return 1 | |
| } | |
| common=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null) | |
| main_toplevel=$(dirname "$common") | |
| branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null) | |
| if [[ "$toplevel" == "$main_toplevel" ]]; then | |
| echo "rmwt: refusing to remove the main worktree ($toplevel)" >&2 | |
| return 1 | |
| fi | |
| if [[ "$branch" == "main" ]]; then | |
| echo "rmwt: refusing, current branch is 'main'" >&2 | |
| return 1 | |
| fi | |
| cd "$main_toplevel" || return 1 | |
| git worktree remove "$toplevel" || { | |
| echo "rmwt: 'git worktree remove' failed; if it's just untracked/dirty files run: git worktree remove --force $toplevel" >&2 | |
| cd "$toplevel" 2>/dev/null | |
| return 1 | |
| } | |
| git branch -D "$branch" && echo "rmwt: removed worktree $toplevel and branch $branch" >&2 | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment