Git protip: track function changes with "log -L"
By Maxime Bréhin • Published on 10 October 2022 • 1 min

Have you ever wanted to track only code changes made within a function? That would be great! We could then find where a bug comes from or get a sharper view of the work done along the way.

Maybe you already knew how to get a list of the commits that changed a specific file:

git log <file-path>

A file log

Let me introduce its supercharged version with the -L option:

# git log -L :<function-name>:<file-path>
git log -L :sayHello:demo.js

"log -L" shows every update within the function through its commit history

With that specific option you can only track a single file but above all, you can focus on a specific part, here using a function name. Git will then only print the changes to that function, commit after commit.

Every once in a (long) while, you will likely get a little bit more than the function block: it may go a bit beyond the end of the function. That why I favor another syntax that expects line numbers as block delimiters:

# git log -L <line-start>,<line-end>:<file-path>
git log -L 5,20:demo.js

It will scan the text block within these lines and adjust that range when walking the history, so the relevant content is printed everytime. That syntax is more powerful because you’re not limited to function analysis (or to curlies-delimited functions) 🌈🦄!

Would you like to go one step further and fully master Git core concepts, or to get advice on how to guarantee the quality of your Git projects? We can help or train you - just tell us what you need!