Skip to content

Instantly share code, notes, and snippets.

@thomasaarholt
Created March 14, 2024 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasaarholt/8509d3649129aa95cd4b494ae6d48a95 to your computer and use it in GitHub Desktop.
Save thomasaarholt/8509d3649129aa95cd4b494ae6d48a95 to your computer and use it in GitHub Desktop.
A zsh function to list git stashes using fzf with a preview of the changed files for quickly identifying the relvant stash
function stash() {
# Check if stash is empty
if ! git stash list &>/dev/null; then
echo "No stashes found."
return
fi
# Fetch relative dates and messages from git stash
local relative_dates=$(git stash list --format="%ar")
local messages=$(git stash list --format="%gs" | sed 's/^On //; s/^WIP on //')
# Convert strings to arrays
local date_array=("${(@f)relative_dates}")
local message_array=("${(@f)messages}")
# Initialize combined string
local combined_info=""
# Loop through arrays to combine elements with ANSI color codes
for i in {1..${#date_array[@]}}; do
combined_info+=$'\033[34m'${date_array[$i]}$'\033[0m \033[31m'${message_array[$i]}$'\033[0m\n'
done
# Pipe the combined string into fzf for interactive selection
local chosen_stash=$(echo "$combined_info" \
| awk '{print NR,$0}' \
| fzf --with-nth 2.. \
--preview-window 'up:50%' \
--preview 'N=$(echo {} | cut -d" " -f1); git stash show -p stash@{$((N-1))} --stat --color=always'
)
# Validate selection
if [[ -z "$chosen_stash" ]]; then
echo "No stash selected."
return
fi
local N=$(echo "$chosen_stash" | cut -d" " -f1)
git stash pop "stash@{$((N-1))}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment