Skip to content

Instantly share code, notes, and snippets.

@unrevised6419
Created April 24, 2026 12:31
Show Gist options
  • Select an option

  • Save unrevised6419/85d10341567f080224951af6fe72b37c to your computer and use it in GitHub Desktop.

Select an option

Save unrevised6419/85d10341567f080224951af6fe72b37c to your computer and use it in GitHub Desktop.
Replication of Claude Hooks WorktreeCreate and WorktreeRemove
#!/bin/bash
set -e
INPUT=$(cat)
NAME=$(echo "$INPUT" | jq -r .name)
CWD=$(echo "$INPUT" | jq -r .cwd)
DIR="$CWD/.claude/worktrees/$NAME"
BRANCH="worktree-$NAME"
cd "$CWD"
# If already registered as a worktree, nothing to do
if git -C "$CWD" worktree list --porcelain | grep -q "^worktree $DIR$"; then
echo "$DIR"
exit 0
fi
# Directory exists but not registered — clean it up first
if [ -d "$DIR" ]; then
rm -rf "$DIR"
fi
if git -C "$CWD" show-ref --quiet --verify "refs/heads/$BRANCH"; then
git -C "$CWD" worktree add --quiet "$DIR" "$BRANCH"
else
git -C "$CWD" worktree add --quiet "$DIR" -b "$BRANCH"
fi
echo "$DIR"
#!/bin/bash
set -e
INPUT=$(cat)
WORKTREE_PATH=$(echo "$INPUT" | jq -r .worktree_path)
# Derive main repo path from the worktree's common git dir
GIT_COMMON=$(git -C "$WORKTREE_PATH" rev-parse --git-common-dir 2>/dev/null)
MAIN_REPO=$(dirname "$GIT_COMMON")
# Read branch before removing the worktree
BRANCH=$(git -C "$WORKTREE_PATH" branch --show-current 2>/dev/null)
if git -C "$MAIN_REPO" worktree list --porcelain | grep -q "^worktree $WORKTREE_PATH$"; then
git -C "$MAIN_REPO" worktree remove -f "$WORKTREE_PATH"
fi
if [ -d "$WORKTREE_PATH" ]; then
rm -rf "$WORKTREE_PATH"
fi
if git -C "$MAIN_REPO" show-ref --quiet --verify "refs/heads/$BRANCH"; then
git -C "$MAIN_REPO" branch --quiet -D "$BRANCH"
fi
{
"$schema": "https://json.schemastore.org/claude-code-settings.json",
"hooks": {
"WorktreeCreate": [
{
"hooks": [
{
"type": "command",
"command": ".claude/hooks/worktree-create.sh",
"statusMessage": "Creating and preparing the worktree"
}
]
}
],
"WorktreeRemove": [
{
"hooks": [
{
"type": "command",
"command": ".claude/hooks/worktree-remove.sh",
"statusMessage": "Removing the worktree"
}
]
}
],
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment