Skip to content

Instantly share code, notes, and snippets.

@BebeSparkelSparkel
Created October 28, 2024 17:50
Show Gist options
  • Save BebeSparkelSparkel/bfe3aaaa5f00c69fab867651f21fcc1c to your computer and use it in GitHub Desktop.
Save BebeSparkelSparkel/bfe3aaaa5f00c69fab867651f21fcc1c to your computer and use it in GitHub Desktop.
Show the diff of the current file and the recovered file
#!/bin/sh
file="$1"
# Check if file exists
if [ ! -f "$file" ]; then
echo "Error: File '$file' not found" >&2
exit 1
fi
# Change to directory containing the file
cd "$(dirname "$file")" || exit 1
file=$(basename "$file")
# Get applicable swap files, storing only the filenames
applicable_swaps=$(vim -r 2>&1 | grep "^[0-9].*${file}" | grep -o -E '[^ ]+$' || true)
# If no swap files found
if [ -z "$applicable_swaps" ]; then
echo "No swap files found for '$file'" >&2
exit 1
fi
# Count number of applicable swap files
swap_count=$(echo "$applicable_swaps" | wc -l)
# If only one swap file, select it automatically
if [ "$swap_count" -eq 1 ]; then
swapfile=$applicable_swaps
else
while true; do
echo "$applicable_swaps" | cat -n
echo "Enter the number of the swap file to recover or q to quit: "
read -r choice
if [ "$choice" = "q" ]; then
exit 0
fi
# Validate numeric input and range
if ! echo "$choice" | grep -q '^[0-9]\+$'; then
echo "Error: Invalid input. Please enter a number or q to quit." >&2
continue
fi
if [ "$choice" -lt 1 ] || [ "$choice" -gt "$swap_count" ]; then
echo "Error: Please enter a number between 1 and $swap_count" >&2
continue
fi
swapfile=$(echo "$applicable_swaps" | awk "NR==$choice")
break
done
fi
if [ -n "$swapfile" ]; then
recovered_file=$(mktemp -t vim-recover.XXXXXXXXXX)
# Recover the swap file content
vim -n -r "$file" -c ":w! $recovered_file" -c ":q!"
# Show diff
diff "$file" "$recovered_file" | less
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment