Skip to content

Instantly share code, notes, and snippets.

@Talor-A
Created October 29, 2024 20:43
Show Gist options
  • Save Talor-A/91aa823fcd4814135a00fd6a68916ada to your computer and use it in GitHub Desktop.
Save Talor-A/91aa823fcd4814135a00fd6a68916ada to your computer and use it in GitHub Desktop.
#!/bin/bash
# creates a new worktree.
# Usage: git wt [revision] [command]
# If no revision is specified, it will use the current HEAD.
# you can use `.` as a shortcut for HEAD too.
# If no command is specified, it will open the worktree in your IDE:
# this is `cursor` for me, but you can change it to your favorite editor.
# Function to generate a unique worktree name
generate_worktree_name() {
local repo_name=$(basename "$(git rev-parse --show-toplevel)")
local date_str=$(date +%Y-%m-%d)
local random_hash=$(head -c 4 /dev/urandom | xxd -p)
echo "${repo_name}-${date_str}-${random_hash}"
}
# Check if we're in a git repository
if ! git rev-parse --git-dir > /dev/null 2>&1; then
echo "Error: Not in a git repository"
exit 1
fi
if [ "$#" -lt 1 ]; then
revision="HEAD"
command="cursor ."
else
revision=$1
shift
command="$*"
fi
if [[ "$revision" == "." ]]; then
revision="HEAD"
fi;
# Validate revision
if ! git rev-parse --verify "$revision" >/dev/null 2>&1; then
echo "Error: Invalid revision: $revision"
exit 1
fi
# prune old worktrees
git worktree prune
# Create temporary directory in /tmp
worktree_name=$(generate_worktree_name)
worktree_path="/tmp/$worktree_name"
# Create worktree
if ! git worktree add --detach "$worktree_path" "$revision"; then
echo "Error: Failed to create worktree"
exit 1
fi
# Change to worktree directory and execute command
cd "$worktree_path" || exit 1
if [[ ! -z "${command}" ]]; then
echo "Running command: $command"
eval "$command"
else
echo "no command specified"
fi
# Provide information about the worktree
echo
echo "Worktree is ready at: $worktree_path"
echo "To remove this worktree later, run:"
echo "git worktree remove $worktree_name"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment