editione1.0.1
Updated August 7, 2023Development tools arenโt perfect, and sometimes our IDEs wonโt be aware of the entire structure of the codebase. Perhaps you have some code that is called dynamically or your language supports metaprogramming, both of which can be difficult for IDEs to understand. In some cases, you may need to use other tools like grep
or git grep
instead, which give you the ability to search your codebase for specific patterns such as variables, functions, class names, or constants.
For example, you may come across a function called findNearbyLocations()
while reading some code. In order to find all locations where that function is called, you can run the following command from your projects root directory:
$ grep -r findNearbyLocations *
That command will recursively search all directories in your codebase and output the lines where the term โfindNearbyLocationsโ occurs. With this information you can pull up each file to see how that function is used. When you can see where a certain term is used throughout the codebase, you gain a better understanding of what the program is doing.
Most of the time, youโll want to search recursively using the -r flag, although this means it will also search in folders we may not want to query, such as dependency directories that contain large amounts of third-party code. While grep
gives you the ability to exclude certain directories from your search, it may be annoying to have to manually exclude them every time.
Fortunately, if youโre using git
for version control, there is a command called git grep
that works similarly, except that it automatically ignores any files and directories that are defined in a file called .gitignore
. This makes it much easier to query your codebase without having to sift through files and directories youโre not interested in.
With these tools, you have a way to query your codebase any time you come across a function youโre not familiar with. This will help you learn how a function works, what parameters it expects, what the return values are, and where else itโs used in the codebase. Using these tools will help you to better understand what the code is doing and how it is organized, and will ultimately help you build and refine your mental model of the codebase.
grep โ Reference Page (man7.org)
git-grep โ Reference Page (git-scm.com)
ripgrep โ GitHub Repository (github.com)
When youโre reading through code, you may want to know when it was last changed. If youโre using git
, thereโs another tool called git-blame
, which displays the last revision and the author who most recently modified each line of a file that youโre interested in. This is useful for determining when certain functions were last modified and by whom.
Use the command below to view the last revision and last person to touch each line of a file:
$ git blame <file>