David Ruttka

I make computers do things

Git Bash Command Line Magic Searching Across Branches to Find Certain Files, Directories, Features

So, these commands might be old news to some. Isn’t gonna stop me from sharing :–)

Today, we weren’t sure where a certain bit of code was. Why we weren’t sure isn’t the point of this post, but we knew that the code had been written. We also knew, from some old conversation, a directory name. But the directory didn’t exist, at least not in our branches.

So on what branch might it have been done? Reflecting now, we could have looked at our issue tracking system and found the associated commits that way. What we ended up doing was having some fun at the command line.

Let’s say the feature had to do with diagnosing widgets, and we knew the directory name was tools/widgetDiagnosis.

Option 1: Search by branch name

git branch -a | grep -i diagnos

What does this do? Well, git branch -a lists all the branches both locally and remote, and then that’s piped in as input to grep -i diagnos which does a case insensitive pattern match. This gives us output like /origin/feature/Widget-Diagnostics, or maybe it was /origin/feature/Diagnose-Widgets, but you can see now why I used “diagnos” as the search pattern. Distinct enough to avoid a lot of false positives, but loose enough to match variants of the word. 

Option Two: Search by path

git log --all -- tools/widgetDiagnosis

What does this do? I stole this one from StackOverflow. There are other answers there too in case you don’t know the full exact path that you’re looking for. At any rate, this gets the log for all the refs but only where the commit can explain how the file exists. Then get a branch name with

git branch --contains <a commit hash from above>

In our case, the way we structure our branches and the way we format our commit messages, the log was enough to lead us to the correct branch.

So there you have it. Again, might be very old news to some, but if this helps at least one person, this write-up was worth it.

This post originally appeared on The DevStop.