Files
dotfiles/.config/zsh/autoload/git/git-checkout-worktree
Julian Prein 02a0e17bcb git:checkout-worktree: Fix exit when not in repo
Fix the exit condition when the function is called outside of a git
repository.
Use zsh's `:t` History Expansion Modifier, as `$?` does not keep `git
rev-parse`'s exit code, but rather `basename`'s.
2022-03-31 15:33:53 +02:00

37 lines
934 B
Bash
Executable File

#!/usr/bin/env zsh
# Checks out the first argument in a worktree at a temporary directory. Then
# spawns an interactive shell inside of it.
# When the shell closes the worktree is tried to be removed. Until that works
# without problems (e.g. dirty), a new shell is spawned to resolve all conflicts
# (e.g. stashing). Finally the temporary directory is deleted.
local GIT_ROOT TEMP_DIR REPO_DIR
GIT_ROOT="${$(git rev-parse --show-toplevel):t}" || return
TEMP_DIR="$(mktemp -d)"
REPO_DIR="$TEMP_DIR/$GIT_ROOT"
git worktree add "$REPO_DIR" "$1"
[[ -e "$REPO_DIR" ]] || return 1
pushd -q "$REPO_DIR"
# Start subshell
"$SHELL"
errc=$?
# Cleanup when exiting
popd -q
# Restart the subshell until every issue is resolved and the worktree is
# removed
until [[ ! -e "$REPO_DIR" ]] || git worktree remove "$REPO_DIR"; do
pushd -q "$REPO_DIR"
"$SHELL"
errc=$?
popd -q
done
git worktree prune
command rm -rf "$TEMP_DIR"
return $errc