Is there a way to customize the output of git blame?

Viewed 21745

git log has a nice --format option to specify how the output should be formatted.

But git blame doesn't seem to have an equivalent, although default output of blame is not quite human-friendly. I would like to see much less.

For example, instead of:

5600cab7 js/sidebar/VehicleGrid.js        (Rene Saarsoo    2009-10-08 18:55:24 +0000 127)    if (x > y) {
b5f1040c js/map/monitoring/VehicleGrid.js (Mihkel Muhkel   2010-05-31 07:20:13 +0000 128)        return x;

I would like to have:

5600cab7 Rene Saarsoo (1 year ago)     127:    if (x > y) {
b5f1040c Mihkel Muhkel (5 months ago)  128:        return x;

I figure that I could write a script to parse the output of git blame --porcelain but given the horrendous default output of blame I feel that somebody out there must have already done something about it.

Any ideas? Or any tips for implementing such a script?

7 Answers

Going further with VonC's great answer, I made a more complete scale for the color.blame.highlightRecent config:

[color "blame"]
    highlightRecent = 237, 20 month ago, 238, 19 month ago, 239, 18 month ago, 240, 17 month ago, 241, 16 month ago, 242, 15 month ago, 243, 14 month ago, 244, 13 month ago, 245, 12 month ago, 246, 11 month ago, 247, 10 month ago, 248, 9 month ago, 249, 8 month ago, 250, 7 month ago, 251, 6 month ago, 252, 5 month ago, 253, 4 month ago, 254, 3 month ago, 231, 2 month ago, 230, 1 month ago, 229, 3 weeks ago, 228, 2 weeks ago, 227, 1 week ago, 226

Which has a scale from 20 month ago to now (last 4 weeks with different colors):

If you improved it, comment the gist! And star if you liked it ❤️

Since git log provides way more customization options for output, you can combine git blame, awk, xargs and git log to achieve what you want. E.g.

git --no-pager blame <filepath> -L1,+1 --porcelain | awk 'NR==1 {print $1}' | xargs git --no-pager log -1 --pretty=format:"%h - (%cd) %s - %an" --date=relative

This outputs something like this:

f8a66e80c - (5 months ago) Add gem: devise - elquimista

Basically what git blame and awk does above is get a full commit SHA, and xargs passes it to git log as an argument.

You can add this to your .gitconfig to get relative time (n days ago etc)

[blame]
    date = human

git blame --porcelain gives the information you need in a form that should be easy for a script to read, but is hard for a human. This would be a good place to start writing a script.

Related