Skip to content

Instantly share code, notes, and snippets.

@Pondidum
Created November 3, 2021 07:43
Show Gist options
  • Select an option

  • Save Pondidum/d79e674273e9c37bfdca7ec042c2b4d3 to your computer and use it in GitHub Desktop.

Select an option

Save Pondidum/d79e674273e9c37bfdca7ec042c2b4d3 to your computer and use it in GitHub Desktop.
#!/usr/bin/env zsh
setopt extendedglob
[[ $XPLEASE ]] && set -x
if [[ -t 1 ]]; then
color_header=$(git config --get-color color.diff.meta bold)
color_hunk_header=$(git config --get-color color.diff.frag cyan)
color_new=$(git config --get-color color.diff.new green)
color_old=$(git config --get-color color.diff.old red)
color=1
fi
toplevel=$(git rev-parse --show-toplevel)
printprefix() {
printf '%s' "$@" ' '
}
parse_porcelain() {
reply=()
output=(${(f)"$(git -C $toplevel --no-pager blame --porcelain -L "$@")"})
output=(${(M)output:#[a-f0-9](#c40)*})
local line
for line in $output; do
reply+=(${line:0:7})
done
}
revs=(${(f)"$(git rev-parse --revs-only "$@")"})
if (( $#revs == 0 )); then
revs=(HEAD '')
elif (( $#revs == 1 )); then
revs=($revs '')
fi
git diff --cached ${color:+--color} "$@" | while IFS= read -r line; do
if [[ $line = $color_header+++* ]]; then
file=${line#*+++ [iwb2]/}
file=${file%$'\e'*}
elif [[ $line = $color_hunk_header@@* ]]; then
[[ $line =~ '@@ -([[:digit:]]*)(,[[:digit:]]*)? \+([[:digit:]]*)(,[[:digit:]]*)? @@' ]]
oldfrom=$match[1]
if [[ -n $match[2] && $match[2] != ,0 ]]; then
oldto=${match[2]#,}
else
oldto=$oldfrom
fi
newfrom=$match[3]
if [[ -n $match[4] && $match[2] != ,0 ]]; then
newto=${match[4]#,}
else
newto=$newfrom
fi
parse_porcelain $oldfrom,+$oldto $revs[1] -- $file
oldblame=($reply)
parse_porcelain $newfrom,+$newto $revs[2] -- $file
newblame=($reply)
oldindex=1
newindex=1
elif [[ $line = ' '* ]]; then
printprefix $newblame[newindex]
((newindex++))
((oldindex++))
elif [[ $line = $color_old-* ]]; then
printprefix $color_old $oldblame[oldindex++]
elif [[ $line = $color_new+* ]]; then
printprefix $color_new $newblame[newindex++]
fi
print -r $line
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment