Created
October 31, 2023 06:53
-
-
Save misberner/8d3269b6888f6950702c93219e7b4262 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -euo pipefail | |
git_dir="$(git rev-parse --git-dir)" | |
list_reflog_entries() { | |
git log --walk-reflogs --grep-reflog '^checkout: moving from ' --format='%gs' | |
} | |
reflog_regex="^checkout: moving from [^[:space:]]+ to ([^[:space:]]+)$" | |
list_branches_with_duplicates() { | |
while IFS= read -r line ; do | |
[[ "$line" =~ $reflog_regex ]] || continue | |
target_branch="${BASH_REMATCH[1]}" | |
echo "$target_branch" | |
done < <(list_reflog_entries) | |
} | |
list_branches_unique() { | |
list_branches_with_duplicates \ | |
| awk '{print NR " " $0}' \ | |
| sort -u -k 2 \ | |
| sort -n -k 1 \ | |
| cut -d' ' -f 2- | |
} | |
filter_valid_branches() { | |
while IFS= read -r branch ; do | |
if git show-ref --verify --quiet "refs/heads/${branch}" 2>/dev/null ; then | |
echo "$branch" | |
fi | |
done | |
} | |
if [[ -x "$(which fzf 2>/dev/null)" ]]; then | |
selected_branch="$(list_branches_unique | filter_valid_branches | fzf || true)" | |
if [[ -n "${selected_branch}" ]]; then | |
git checkout "$selected_branch" | |
fi | |
else | |
list_branches_unique | tail -r | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment