|
#!/bin/bash |
|
|
|
# Interactive git branch selector |
|
# Shows local branches sorted by last modified date |
|
# Use arrow keys to navigate, Enter to checkout |
|
|
|
set -e |
|
|
|
# Check if fzf is installed |
|
if ! command -v fzf &> /dev/null; then |
|
echo "Error: fzf is required but not installed." |
|
echo "Install it with: brew install fzf (on macOS) or your package manager" |
|
exit 1 |
|
fi |
|
|
|
# Get current branch to highlight it |
|
current_branch=$(git branch --show-current) |
|
|
|
# Get local branches sorted by last commit date (most recent first) |
|
# Format the display line directly |
|
branches=$(git for-each-ref --sort='-committerdate' --format='%(refname:short)|%(committerdate:relative)|%(subject)' refs/heads/ \ |
|
| while IFS='|' read -r branch date subject; do |
|
if [ "$branch" = "$current_branch" ]; then |
|
printf "* %-50s (%s)\n" "$branch" "$date" |
|
else |
|
printf " %-50s (%s)\n" "$branch" "$date" |
|
fi |
|
done) |
|
|
|
# Use fzf to select branch interactively |
|
# Use --nth to search only on the branch name part (before the parentheses) |
|
selected=$(echo "$branches" | fzf \ |
|
--height=40% \ |
|
--layout=reverse \ |
|
--border-label ' Git Branch Select ' \ |
|
--border \ |
|
--padding 1,1 \ |
|
--input-label=' Select Branch ' \ |
|
--no-info \ |
|
--color 'border:#6699cc,label:#99ccff' \ |
|
--preview-border=none \ |
|
--preview-window=right:30%,noinfo \ |
|
--preview=' |
|
branch=$(echo {} | sed "s/^[* ] *//" | cut -d" " -f1) |
|
git log --oneline --graph --color=always -15 "$branch" |
|
' \ |
|
--header="↑↓ navigate • Enter: checkout • Esc: cancel" \ |
|
--bind="enter:accept" \ |
|
--no-multi \ |
|
--nth=1 \ |
|
--delimiter=' (' \ |
|
--no-sort) |
|
|
|
# Exit if no selection made (user pressed Esc) |
|
if [ -z "$selected" ]; then |
|
echo "No branch selected. Exiting." |
|
exit 0 |
|
fi |
|
|
|
# Extract branch name from selection |
|
branch_name=$(echo "$selected" | sed 's/^[* ] *//' | cut -d' ' -f1) |
|
|
|
# Don't checkout if already on the selected branch |
|
if [ "$branch_name" = "$current_branch" ]; then |
|
echo "Already on branch '$branch_name'" |
|
exit 0 |
|
fi |
|
|
|
# Checkout the selected branch |
|
echo "Checking out branch: $branch_name" |
|
git checkout "$branch_name" |