git: fixup automatically the commit a changed line belongs to

Viewed 139

Imagine making a typo in a comment or something trivially similar:

- // Do thigns
+ // Do things

Now, by doing git blame @ -- file you see the commit the line was originally added in:

decafbad ... // Do thigns

You can make the fixup to that line manually by running: git commit --fixup decafbad.

Is there any way to automate this git blame @ -- file |grep thigns, git commit --fixup decafbad cycle?

1 Answers

with bash I wrote a small script to obtain this. This script supposes that you only made one fixup change, so it looks only at the first file modified and the first line that was changed:

file=$(git diff | sed -n "s/.* a\/\(.*\) \+\+\+.*/\1/p")
line_removed=$(git diff | tail -n +6 | sed -n "s/^-\(.*\)/\1/p")
hash=$(git blame HEAD $file | grep $line_removed | awk "{print \$1}")
git commit -a --fixup $hash

if you put this code inside /usr/bin/git-auto-fixup (and make it executable), then you can invoke it like this: git auto-fixup

Related