How to view git change history of a Swift method
I knew git had a feature to get change history of a method. I used it all the time with ObjC but it never worked for swift files.
e.g., git log -L :myfunction:path/to/myfile.c
list all the commits that changed something in method/function named myfunction
in file myfile.c
[stackoverflow]
I always thought it was because of ObjC and C language similarities. Few years ago, I came across this tweet and I realized this is something I can define for git.
Before and After
How-to
You need to update a couple of meta files in your .git
directory of your git workspace. If you do not find these files in your git workspace, you can create an empty file and add the contents
# Step 1: Add this to your .git/info/attributes
*.swift diff=swift
# Step 2: Edit your `.git/config` and add
[diff "swift"]
xfuncname = "^ *(\\w+ +)*((class|struct|enum|protocol|extension|func) +|(de)?init\\b).*$"
I had tried a few other regex’s for xfuncname
, but the one above is my current version that I use. Here are some I found in github
# xfuncname = ^[ \t]*((class|func)[ \t].*)$
# xfuncname = "^ *(\\w+ +)*((class|struct|enum|protocol|extension|func) +.*|(de)?init\\b.*|(var|let) +(.+?): +(.+?)\\{)$"
References:
- https://twitter.com/kastiglione/status/1242113018474819584
- https://twitter.com/kastiglione/status/1242116999494242305
- https://stackoverflow.com/questions/4781405/git-how-do-i-view-the-change-history-of-a-method-function
- https://devhints.io/git-log-format
- https://www.git-scm.com/docs/gitattributes
This post was in my draft for a very long time. Recently, I had to set this up again for a new project. I realized I could clean up my draft and publish to get out of this pandemic writer’s block and also a quick reference for me in the future.
I spent a day to fixing my theme to support Hugo changes since my update :-)