#!/usr/bin/env bash
#
# Codey writes this file once and then leaves it alone, so it is yours to edit.
# Anything a fresh worktree needs — copying a .env, installing dependencies,
# running a migration — belongs at the bottom, before the path is printed.
#
# The contract with Codey is two lines wide:
#
# in the worktree's name, on stdin
# out the absolute path of the tree, as the last line of stdout
#
# Everything else the script has to say should go to stderr. Codey reads the
# path back from stdout and moves the session there, so a stray echo would be
# mistaken for the destination.
#
# The environment carries the rest:
#
# CODEY_REPO_ROOT the checkout /worktree was run from
# CODEY_WORKTREE_NAME the same name that arrives on stdin
# CODEY_WORKTREES_DIR where trees are kept
#
# Exit non-zero to refuse: Codey reports the failure and stays put.
set -euo pipefail
name="$(cat)"
name="${name//[[:space:]]/}"
if [ -z "$name" ]; then
echo "worktree: no name on stdin" >&2
exit 1
fi
repo="${CODEY_REPO_ROOT:-$PWD}"
trees="${CODEY_WORKTREES_DIR:-$HOME/.config/codey/worktrees}"
path="$trees/$name"
mkdir -p "$trees"
cd "$repo"
# A branch of this name may already exist — from an earlier tree that has since
# been removed, or from a colleague's push. Reusing it is friendlier than
# failing, and checking first keeps git's own error out of the way.
if git show-ref --quiet --verify "refs/heads/$name"; then
git worktree add "$path" "$name" >&2
else
git worktree add -b "$name" "$path" >&2
fi
# Whatever else a new tree needs goes here. For example:
#
# cp "$repo/.env" "$path/.env" 2>/dev/null || true
# (cd "$path" && npm install >&2)
echo "$path"