Files
leleka/scripts/dev/worktree.sh
T

57 lines
2.3 KiB
Bash

#!/usr/bin/env bash
# Git worktrees of this repository live inside the main repository's .git directory (.git/wt/<name>), so ~/work stays one folder per project.
#
# scripts/dev/worktree.sh new <name> [<branch> [<start-point>]] create .git/wt/<name> on a new or existing branch
# scripts/dev/worktree.sh list every worktree with its state: dirty / merged into <base>
# scripts/dev/worktree.sh clean [--base <branch>] [--yes] remove the worktrees that are clean and merged into <base>
#
# `clean` never deletes work: a worktree with uncommitted changes is skipped, and removing one only deletes its directory, never its branch.
# Build outputs (target/) inside a removed worktree go with it; they are regenerable.
set -euo pipefail
main=$(cd "$(git rev-parse --git-common-dir)/.." && pwd)
wt_root="$main/.git/wt"
base=claude/port-gpu-bringup
cmd=${1:-list}
shift || true
case "$cmd" in
new)
name=${1:?usage: worktree.sh new <name> [<branch> [<start-point>]]}
branch=${2:-claude/$name}
start=${3:-HEAD}
mkdir -p "$wt_root"
if git show-ref --verify --quiet "refs/heads/$branch"; then
git worktree add "$wt_root/$name" "$branch"
else
git worktree add -b "$branch" "$wt_root/$name" "$start"
fi
echo "worktree: $wt_root/$name ($branch)"
;;
list | clean)
yes=0
while [ $# -gt 0 ]; do
case "$1" in
--base) base=$2; shift 2 ;;
--yes) yes=1; shift ;;
*) echo "unknown argument: $1" >&2; exit 2 ;;
esac
done
git worktree list --porcelain | awk '/^worktree /{w=$2} /^branch /{print w" "$2} /^detached/{print w" DETACHED"}' | while read -r w b; do
[ "$w" = "$main" ] && continue
dirty=$(git -C "$w" status --porcelain 2>/dev/null | grep -vc '^$' || true)
if [ "$b" = DETACHED ]; then merged=detached; else git merge-base --is-ancestor "${b#refs/heads/}" "$base" 2>/dev/null && merged=merged || merged=unmerged; fi
echo "$w ${b#refs/heads/} dirty=$dirty $merged"
if [ "$cmd" = clean ] && [ "$dirty" = 0 ] && { [ "$merged" = merged ] || [ "$merged" = detached ]; }; then
if [ "$yes" = 1 ]; then git worktree remove "$w" && echo " removed"; else echo " would remove (pass --yes)"; fi
fi
done
git worktree prune
;;
*)
echo "usage: worktree.sh new|list|clean" >&2
exit 2
;;
esac