Files

52 lines
1.3 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
BASE_REF="${BASE_REF:-}"
usage() {
cat <<'EOF'
Usage:
bash scripts/new-branch.sh <branch-name>
Creates a new development branch from the latest origin/main.
Environment:
BASE_REF Base ref to create from. Defaults to origin/main when available.
EOF
}
if [[ "${1:-}" == "-h" || "${1:-}" == "--help" || $# -ne 1 ]]; then
usage
[[ $# -eq 1 ]] && exit 0 || exit 1
fi
branch="$1"
if [[ -n "$(git -C "${ROOT}" status --porcelain=v1 --untracked-files=all)" ]]; then
echo "New branch check failed: current worktree is not clean." >&2
git -C "${ROOT}" status --short --untracked-files=all >&2
exit 1
fi
if git -C "${ROOT}" remote get-url origin >/dev/null 2>&1; then
git -C "${ROOT}" fetch origin --prune
fi
if [[ -z "${BASE_REF}" ]]; then
for candidate in origin/main origin/master main master; do
if git -C "${ROOT}" rev-parse --verify --quiet "${candidate}" >/dev/null; then
BASE_REF="${candidate}"
break
fi
done
fi
git -C "${ROOT}" rev-parse --verify --quiet "${BASE_REF}" >/dev/null || {
echo "New branch check failed: base ref not found: ${BASE_REF}" >&2
exit 1
}
git -C "${ROOT}" switch -c "${branch}" "${BASE_REF}"
echo "Created ${branch} from ${BASE_REF}."