Skip to content

lab 21 Using Git Blame to Find Help

Goals

Git Blame

The blame command allows you to see the commit that was responsible for a line of code in a file. It will also show you the author and when the line was committed. You can use this tool to figure out who to ask about some code you have questions about. You only have one author in this repository so the output here will be of limited usefulness, but in a multi-person team this becomes indispensible. Let’s try it out.

Execute:

git blame hello.rb

Output:

$ git blame hello.rb
3e56dbf1 (Jim Weirich 2022-10-24 19:02:01 +0000 1) # Default is World
3e56dbf1 (Jim Weirich 2022-10-24 19:02:01 +0000 2) # Author: Jim Weirich (jim@somewhere.com)
c72af6b9 (Jim Weirich 2022-10-24 19:02:01 +0000 3) names = ARGV || ["World"]
15c7573d (Jim Weirich 2022-10-24 19:02:00 +0000 4) 
c72af6b9 (Jim Weirich 2022-10-24 19:02:01 +0000 5) puts "Hello, #{names.join(" ")}!"
c72af6b9 (Jim Weirich 2022-10-24 19:02:01 +0000 6) puts "You have #{names.length} names!"

You can see the different commit hashes for each line of code indicating who changed them and when they changed. It is also possible to pass a commit to git blame to get the blame output starting at that commit. This is useful to follow the history of a line or multiple lines of code and learn the context around its changes. We’ll try it below starting at the previous commit.

Execute:

git blame HEAD^ hello.rb

Output:

$ git blame HEAD^ hello.rb
c72af6b9 (Jim Weirich 2022-10-24 19:02:01 +0000 1) names = ARGV || ["World"]
15c7573d (Jim Weirich 2022-10-24 19:02:00 +0000 2) 
c72af6b9 (Jim Weirich 2022-10-24 19:02:01 +0000 3) puts "Hello, #{names.join(" ")}!"
c72af6b9 (Jim Weirich 2022-10-24 19:02:01 +0000 4) puts "You have #{names.length} names!"
1dee7f9a (Jim Weirich 2022-10-24 19:02:01 +0000 5) puts "You have #{names.length} names!"

Wrapping Up

The git blame command is very useful in day-to-day usage. You can use it to learn the context and history around a file or to determine who to ask for help. Most git integrations for code editors support some form of the blame command. I recommend configuring a git integration for your editor just for this purpose so it is as easy as possible to use git blame.