Files
architecture/old2/skills/worktrees/scripts/create-worktree.sh
2026-01-15 17:28:06 +01:00

75 lines
2.1 KiB
Bash
Executable File

#!/bin/bash
set -euo pipefail
# Create a git worktree for issue work or PR review
#
# Usage:
# ./create-worktree.sh issue <issue-number>
# ./create-worktree.sh review <pr-number> <branch-name>
#
# Returns: Absolute path to created worktree (stdout)
MODE="$1"
REPO_PATH=$(git rev-parse --show-toplevel 2>/dev/null || pwd)
REPO_NAME=$(basename "$REPO_PATH")
WORKTREES_DIR="${REPO_PATH}/../worktrees"
# Ensure worktrees directory exists
mkdir -p "$WORKTREES_DIR"
# Fetch latest from origin
cd "$REPO_PATH"
git fetch origin >/dev/null 2>&1
case "$MODE" in
issue)
ISSUE_NUMBER="$2"
WORKTREE_NAME="${REPO_NAME}-issue-${ISSUE_NUMBER}"
WORKTREE_PATH="${WORKTREES_DIR}/${WORKTREE_NAME}"
# Get issue title for branch name (tea issues output has title on line 2: " # #1 Title here")
ISSUE_TITLE=$(tea issues "$ISSUE_NUMBER" 2>/dev/null | sed -n '2p' | sed 's/.*#[0-9]* //' | xargs || echo "untitled")
# Create safe branch name
BRANCH_NAME="issue-${ISSUE_NUMBER}-$(echo "$ISSUE_TITLE" | tr '[:upper:]' '[:lower:]' | tr ' ' '-' | tr -cd '[:alnum:]-' | cut -c1-50)"
# Remove worktree if it already exists
if [ -d "$WORKTREE_PATH" ]; then
git worktree remove "$WORKTREE_PATH" --force 2>/dev/null || true
fi
# Delete branch if it exists
git branch -D "$BRANCH_NAME" 2>/dev/null || true
# Create worktree with new branch from main
git worktree add "$WORKTREE_PATH" -b "$BRANCH_NAME" origin/main >/dev/null 2>&1
echo "$WORKTREE_PATH"
;;
review)
PR_NUMBER="$2"
BRANCH_NAME="$3"
WORKTREE_NAME="${REPO_NAME}-review-${PR_NUMBER}"
WORKTREE_PATH="${WORKTREES_DIR}/${WORKTREE_NAME}"
# Remove worktree if it already exists
if [ -d "$WORKTREE_PATH" ]; then
git worktree remove "$WORKTREE_PATH" --force 2>/dev/null || true
fi
# Create worktree from existing branch
git worktree add "$WORKTREE_PATH" "origin/${BRANCH_NAME}" >/dev/null 2>&1
echo "$WORKTREE_PATH"
;;
*)
echo "Error: Invalid mode '$MODE'. Use 'issue' or 'review'" >&2
echo "Usage:" >&2
echo " $0 issue <issue-number>" >&2
echo " $0 review <pr-number> <branch-name>" >&2
exit 1
;;
esac