Searching Through the Repository
local graph
Chapter 5 — Searching Through the Repository
Section titled “Chapter 5 — Searching Through the Repository”After selecting the parts of the project history that you want to search, the next task is to extract the information you want from selected commits. You can limit your search according to the revision metadata, such as the author of the commit, the date that the change was created, or the contents of the commit message. You can look at the changes themselves, or you may be interested in how a given file or subsystem evolved. With access to the project history, you can find who wrote a given section of the code or which commit introduced a regression (first buggy commit).
Another important skill is to format Git output so that it is easy to find the information you want. This task is made possible by various predefined pretty git log output formats and the ability to define and compose one’s own output format.
Here is the list of topics we will cover in this chapter:
- Limiting the history and history simplification
- Searching the history with the pickaxe tool and diff search
- Finding bugs with
git bisect - Line-wise history of file contents with
git blameand rename detection - Selecting and formatting output (the pretty formats)
- Summarizing contribution with
git shortlog - Specifying a canonical author name and email with
.mailmap - Viewing specific revisions, files at revision, and diff output options
The purpose of this chapter is to show how to extract information from the project history.
Searching the history
Section titled “Searching the history”A huge number and variety of useful options for the git log command are revising limiting options — that is, options that let you show only a subset of commits. This complements selecting commits to view by passing the appropriate revision range and allows us to search the history for specific versions, utilizing information other than the shape of the graph of revisions.
Limiting the number of revisions
Section titled “Limiting the number of revisions”The most basic way of limiting git log output is to show only the specified number of the most recent commits. This is done using the -<n> option (where n is any integer); this can also be written as -n <n>, or in long form as --max-count=<n>. For example, git log -2 would show the two last (most recent) commits in the current line of development, starting from the implicit HEAD revision.
You can skip the first few commits shown with --skip=<n>.
Matching revision metadata
Section titled “Matching revision metadata”History limiting options can be divided into those that check the information stored in the commit object itself (the revision metadata) and those that filter commits based on the changeset (based on changes from the parent commit or commits).
Time-limiting options
Section titled “Time-limiting options”If you are interested in commits created within some specific date range, you can use a number of options such as --since and --until, or --before and --after. For example, the following command returns the list of commits made in the last two weeks:
$ git log --since=2.weeksThese options work with various date formats. You can specify a specific date such as 2008-04-21, or a relative date such as 2 years 3 months 3 days ago; you can also use a dot in place of a space.
When using a specific date, you must remember that if the date does not include a time zone, it will be interpreted in the local time zone. It is important because, in such a situation, Git will not yield identical results when run by colleagues who may be situated in other time zones around the world. For example, --since="2014-04-29 12:00:00" would catch six hours’ worth more commits when issued in Birmingham, England, UK (where it means 2014-04-29Z11:00:00 universal time) than when issued in Birmingham, Alabama, USA (where it means 2014-04-29Z17:00:00). To get the same results, you need to include the time zone in the time limit — for example, - -after="2013-04-29T17:07:22+0200".
Note that commits in Git are described not by a single date, but by two possibly different dates: the author date and the committer date. Time-limiting options described here examine the committer date, which means the date and time when the revision object was created. This might be different from the author date, which means the date and time when a changeset was created (when the change was made).
The date of authorship can be different from the date of committership in a few cases:
- One case is when the commit was created in one repository, converted to email, and then applied by another person in another repository.
- Another way to have those two dates differ is to have the commit recreated while rebasing; by default, this keeps the author date and gets a new committer date (see Chapter 9, Merging Changes Together, the Rebasing a branch section, and Chapter 10, Keeping History Clean, the An interactive rebase section).
Matching commit contents
Section titled “Matching commit contents”If you want to filter your commit history to only show those done by a specific author or committer, you can use the --author or --committer options, respectively. For example, let’s say you’re looking for all the commits in the Git source code authored by Linus. You could use something like git log --author=Linus. The search is, by default, case-sensitive, and uses regular expressions. Git will search both the name and the email address of the commit author; to match the first name only, use --author=^Linus. Using ^ here means that the authorship information should start with Linus.
The --grep option lets you search commit messages (which should contain descriptions of the changes). Let’s say that you want to find all the security bug fixes that mention Common Vulnerabilities and Exposures (CVE) identifiers in the commit message. You could generate a list of such commits with git log --grep=CVE.
If you specify both --author and --grep options, or more than one --author or --grep option, Git will show commits that match either query. In other words, Git would logically OR all the commit matching options. If you want to find commits that match all the queries, with matching options logically AND-ed, you need to use the -- all-match option.
There is also a set of options to modify the meaning of matching patterns, similar to the ones used by the grep program. To make the search case-insensitive, use the -i / --regexp-ignore-case option. If you want to match simply a substring, you can use -F / --fixed-strings (you might want to do this to avoid having to escape regular expression metacharacters such as . and ?). To write more powerful search terms, you can use --extended-regexp or --perl-regexp (you can use the latter only if Git was compiled and linked with the Perl Compatible Regular Expressions (PCRE) library). To find non-matching commits, use --invert-grep.
When walking reflogs with git log -g (see the Reflog shortnames section), you can use the --grep-reflog=<regexp> option to show only positions with the matching reflog entry. For example, to show all operations on HEAD that were not a simple commit operation, you can use the following:
$ git log -g --invert-grep --grep-reflog="^commit:"Commit parents
Section titled “Commit parents”Git, by default, will follow all the parents of each merge commit when walking down the ancestry chain. To make it follow only the first parent, you can use the aptly named --first-parent option. This would show you the main line of history (sometimes called the trunk), assuming that you follow the specific practices with respect to merging changes; you will learn more about this in Chapter 8, Advanced Branching Techniques, and Chapter 9, Merging Changes Together.
Consider the following command (this example uses the very nice --graph option that makes an ASCII-art diagram of the history):
$ git log -5 --graph --oneline* 50f84e3 Update draft release notes to 2.1* 07768e0 Merge branch 'jc/shortlog-ref-exclude'|\| * eb07774 shortlog: allow --exclude=<glob> to be passed* | 251cb96 Merge branch 'mn/sideband-no-ansi'|\ \| * | 38de156 sideband.c: do not use ANSI control sequenceCompare it with this:
$ git log -5 --graph --oneline --first-parent* 50f84e3 Update draft release notes to 2.1* 07768e0 Merge branch 'jc/shortlog-ref-exclude'* 251cb96 Merge branch 'mn/sideband-no-ansi'* d37e8c5 Merge branch 'rs/mailinfo-header-cmp'* 53b4d83 Merge branch 'pb/trim-trailing-spaces'You can filter the list to show only the merge commits or only the non-merge commits with the --merges and --no-merges options, respectively. These options can be considered simply shortcuts for more generic options: --min-parents=<number> (--merges is --min-parents=2) and --max-parents=<number> (--no-merges is --max-parents=1).
Let’s say that you want to find the starting point(s) of your project. You can do this with the help of --max-parents=0, which would give all the root commits:
$ git log --max-parents=0 --oneline0ca71b3 basic options parsing and whatnot.16d6b8a Initial import of a python script...cb07fc2 git-gui: Initial revision.161332a first working version1db95b0 Add initial version of gitk to the CVS repository2744b23 Start of early patch applicator tools for git.e83c516 Initial revision of "git", the information manager from hellSearching changes in revisions
Section titled “Searching changes in revisions”Sometimes, searching through commit messages and other revision metadata is not enough. Perhaps descriptions of the changes were not detailed enough. Or, what if you are looking for a revision when a function was introduced, or where variable started to be used?
Git allows you to look through the changes that each revision brought (the difference between a commit and its parent). The faster option is called a pickaxe search.
With the -S<string> option, Git will look for differences that introduce or remove an instance of a given string. Note that this is different from the string simply appearing in the diff output. You can do a match using a regular expression with the --pickaxe-regex option. Git checks each revision to see whether there are files whose current side and parent side have a different number of the specified string, and show the revisions that match.
As a side effect, git log with the -S option would also show the changes that each revision made (as if the --patch option were used), but only those differences that match the query. To show differences for all the files and also differences where the change in number occurred, you need to use the -- pickaxe-all option:
$ git log -S'sub href'commit 06a9d86b49b826562e2b12b5c7e831e20b8f7dceAuthor: Martin Waitz <[email protected]>Date: Wed Aug 16 00:23:50 2006 +0200 gitweb: provide function to format the URL for an action link. Provide a new function which can be used to generate an URL for the CGI. This makes it possible to consolidate the URL generation in order to make it easier to change the encoding of actions into URLs. Signed-off-by: Martin Waitz <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>With -G<regex>, Git would literally look for differences whose added or removed line matches the given regular expression. Note that the unified diff format (that Git uses) considers the changed line to be a removal of the old version and adding of a new one; refer to Chapter 2, Developing with Git (the Examining the changes to be committed section) for an explanation of how Git describes changes.
To illustrate the difference between -S<regex> --pickaxe-regex and -G<regex>, consider a commit with the following diff:
if (lstat(path, &st))- return error("cannot stat '%s': %s", path,+ ret = error("cannot stat '%s': %s", path, strerror(errno));While git log -G"error\(" will show this commit (because the query matches both changed lines), git log -S"error\(" --pickaxe-regex will not (because the number of occurrences of that string did not change).
Tip
If you are interested in a single file, it is easier to use git blame (perhaps in a graphical blame browser, like with git gui blame) to check when the given change was introduced. However, git blame can’t be used to find a commit that deleted a line — you need a pickaxe search for that.
Selecting types of changes
Section titled “Selecting types of changes”Sometimes, you might want to see only those changes that added or renamed files. With Git, you can do this with git log --diff-filter=AR. You can select any combination of types of changes; see the git-log(1) manpage for details. For example, to find all renames while listing all changed files, you can use --diff-filter=R*, such as in the following example:
$ git log --diff-filter=R* --oneline –stat8b4dbde Rename random.js to gen_random.js index.html | 2 +- scripts/{random.js => gen_random.js} | 0 2 files changed, 1 insertion(+), 1 deletion(-)042a8af Directory structure index.html | 2 +- random.js => scripts/random.js | 0 2 files changed, 1 insertion(+), 1 deletion(-)The mnemonics for types of changes are the same as those used by git status --short or git log --name-status:
$ git log -1 --diff-filter=R --oneline --name-status8b4dbde Rename random.js to gen_random.jsR100 scripts/random.js scripts/gen_random.jsNext, we will examine how to search the history based on which files were changed, and later, also how to format the git log output.
History of a file
Section titled “History of a file”As described in the Whole-tree commits section at the beginning of the previous chapter, Git revisions are about the state of the whole project as one single entity.
In many cases, especially with larger projects, we are interested only in the history of a single file, or the history limited to the changes in the given directory (in the given subsystem).
Path limiting
Section titled “Path limiting”To examine the history of a single file, you can simply use git log <pathname>. Git will then only show all those revisions that affected the given pathname (a file or a directory), which means those revisions where there was a change to the given file or a change to a file inside the given subdirectory.
Disambiguation between branch names and path names
Git usually guesses what you mean by writing git log foo; did you mean to ask for the history of the foo branch (the line of development), or for the history of the foo file? However, sometimes, Git can get confused. To prevent confusion between pathnames and branch names, you can use -- (two dashes) to separate filename arguments from other options. Everything after -- would be taken to be a pathname, and everything before that would be taken to be the branch name or other option.
For example, writing git log -- foo explicitly asks for the history of the foo path.
One of the common situations where it is needed, besides when having the same name for a branch and a file, is when examining the history of a deleted file that is no longer present in a project.
You can specify more than one path; you can even look for changes that affect a given type of file with the help of wildcards (pattern match). For example, to find only changes to Perl scripts (files with the *.pl extension), you can use git log -- '*.pl'. Note that you need to protect the *.pl wildcard from being expanded by the shell before Git sees it — for example, via single quotes as shown here.
Pathspec magic
Most commands that accept <path> or <pathspec> as a parameter, such as git log, also support pathspec magic. A pathspec that starts with a colon ‘:’ has a special meaning: it is expected that this colon is then followed by either one or more magic signature letters, or a comma-separated list of zero or more magic words. An optional colon ‘:’ can be used to separate the magics from the pattern to match them. Here are a few examples: :(top):data/ or :/data/ would make the pattern match the data/directory at the top directory of the repository, regardless of where we are inside the repository (the current directory). The git log :(exclude):*.html or git log :^*.html command will list all revisions where there was at least one change to the file that is not an HTML file. You can find more magics in the gitglossary(7) manpage, in the pathspec entry.
However, because Git uses pathname parameters as limiters in showing the history of a project, querying for the history of a single file doesn’t automatically follow renames. You need to use git log --follow <file> to continue listing the history of a file beyond renames. Unfortunately, it doesn’t work in all cases. Sometimes, you need to use either the git blame command (see the Blame – the line-wise history of a file section), or examine the boundary commits with rename detection turned on (git show -M -C --raw --abbrev <rev>) and follow renames and file moving manually.
In modern Git, you can also trace the evolution of the line range within the file using git log -L, which is currently limited to the walk starting from a single revision (zero or one positive revision argument) and a single file. The range is given either denoting the start and end of the range with -L <start>,<end>:<file> (where either <start> or <end> can be a line number or a /regexp/), or a function to track with -L :<funcname regexp>:<file>. This technique cannot, however, be used together with the ordinary pathspec-based path limiting. For example, to see the history of the index.html file, limited to the changes in the <head> element, you can use the following command:
$ git log -L '/^<head>/','/^<\/head>/':index.htmlHistory simplification
Section titled “History simplification”By default, when requested for the history of a path, Git would simplify the history, showing only those commits that are required (that are enough) to explain how the files that match the specified paths came to be. Git would exclude those revisions that do not change the given file. Additionally, for non-excluded merge commits, Git would exclude those parents that do not change the file (thus excluding lines of development).
You can control this kind of history simplification with the git log options such as --full-history or --simplify-merges. Check the Git documentation for more details, such as the History simplification section in the git-log(1) manpage.
Blame — the line-wise history of a file
Section titled “Blame — the line-wise history of a file”The blame command is a version control feature designed to help you determine who made changes to a file. This command shows, for each line in the file, when the line was created, who authored the given line, and so on. It does this by finding the latest commit in which the current shape of each line was introduced. A revision introducing a given shape is the one where the given line has its current form, but where the line is different in its revision parents. The default output of git blame annotates each line with appropriate line-authorship information.
Git can start annotating from the given revision (useful when browsing the history of a file or examining how an older version of a file came to be), or even limit the search to a given revision range. You can also limit the range of lines annotated to make blame faster — for example, to check only the history of an esc_html function, you can use the following:
$ git blame -L '/^sub esc_html {/,/}/' gitweb/gitweb.perlWhat makes the blame operation so useful is that it follows the history of a file across whole-file renames. It can optionally follow lines that were moved from one file to another (with the -M option), and even follow lines that were copied and pasted from another file (with the -C option); this includes internal code movement.
When following code movement, it is useful to ignore changes in whitespace to find when a given fragment of code was truly introduced and avoid finding when it was just re-indented (for example, due to refactoring repeated code into a function — code movement). This can be done by passing the diff-formatting option, –w / -- ignore-all-space.
Rename detection
A good version control system should be able to deal with renaming files and other ways of changing the directory structure of a project. There are two ways to deal with this problem. The first is rename tracking, which means that the information about the fact that a file was renamed is saved at the commit time; the version control systems mark renames. This usually requires using the rename and move commands to rename files. For example, you cannot use a file manager that is not version-control aware to move files. However, you can detect the rename when creating the revision.” It can involve some kind of file identity surviving across renames.
The second method, and the one used by Git, is rename detection. In this case, the mv command is only a shortcut for deleting a file with the old name and adding a file with the same contents and a new name. Rename detection means that the fact that the file was renamed is detected at the time it is needed: when doing a merge, when viewing the line-wise history of a file (if requested), or when showing a diff (if requested or configured). This has the advantage that the rename detection algorithm can be improved and is not frozen at the time of commit. It is a more generic solution, allowing it to handle not only the whole-file renames but also the code movement and copying within a single file and across different files, as can be seen in the description of git blame.
The disadvantage of rename detection, which in Git is based on the heuristic of the similarity of the file contents and the pathname, is that it takes resources to run and that in rare cases, it can fail: not detecting renames, or detecting a rename where there isn’t one.
Note that, in modern Git, basic rename detection is turned on for diffs by default.
Many graphical interfaces for Git include a graphical version of the blame operation. The git gui blame is an example of such a graphical interface for the blame operation (it is a part of git gui, a Tcl/Tk-based graphical interface). Such graphical interfaces can show the full description of changes and simultaneously show the history with and without considering renames. From such a GUI, it is usually possible to go to a specified commit, browsing the history of the lines of a file interactively. In addition, the GUI blame tool makes it very easy to follow files across renames:

Figure 5.1 – ‘git gui blame’ in action, showing the detection of copying or moving fragments of code
Finding bugs with git bisect
Section titled “Finding bugs with git bisect”Git provides a couple of tools to help you debug issues in your projects. These tools can be extremely useful, especially in the case of a software regression — that is, a software bug that makes a feature stop functioning as intended after a certain revision. If you don’t know where the bug can be, and there have been dozens or hundreds of commits since the last state where you know the code worked, you’ll likely turn to git bisect for help.
The bisect command searches semi-automatically, step by step, through project history, trying to find the revision that introduced the bug. In each step, it bisects the history into roughly equal parts and asks whether there is a bug in the dividing commit. It then uses the answer to eliminate one of the two sections and reduces the size of the revision range where there can be a commit that introduced the bug:

Figure 5.2 – An example of git bisect in action, finding the buggy commit after 4 steps
Starting the git bisect process
Section titled “Starting the git bisect process”Suppose version 1.14 of your project worked, but the release candidate for the new version, 1.15-rc0, crashes. You go back to the 1.15-rc0 version, and it turns out you can reproduce the issue (this is very important!), but you can’t figure out what is going wrong.
You can bisect the code history to find out. You need to start the bisection process with git bisect start, and then tell Git which version is broken with git bisect bad. Then, you must tell the bisect process the last known good state (or set of states) with git bisect good:
$ git bisect start$ git bisect bad v1.15-rc0$ git bisect good v1.14Bisecting: 159 revisions left to test after this (roughly 7 steps)[7ea60c15cc98ab586aea77c256934acd438c7f95] Merge branch 'mergetool'Finding the buggy commit
Section titled “Finding the buggy commit”Git figured out that about 300 commits came between the commit you marked as the last good commit (v1.14) and the bad version (v1.15-rc0), and checked out the middle one (7ea60c15) for you. If you run git branch or git status at this point, you’ll see that git has temporarily moved you to (``no branch):
$ git branch* (no branch, bisect started on master) master$ git statusHEAD detached at 7ea60c15ccYou are currently bisecting, started from branch 'master'. (use "git bisect reset" to get back to the original branch)At this point, you need to run your test to check whether the issue is present in the commit currently checked out by the bisect operation. If the program crashes, mark the current commit as bad with git bisect bad. If the issue is not present, mark it as correct with git bisect good. After about seven steps, Git would show the suspect commit:
$ git bisect goodb047b02ea83310a70fd603dc8cd7a6cd13d15c04 is first bad commitcommit b047b02ea83310a70fd603dc8cd7a6cd13d15c04Author: PJ Hyett <[email protected]>Date: Tue Jan 27 14:48:32 2009 -0800 secure this thing:040000 040000 40ee3e7… f24d3c6… M configThe last line in the preceding example output is in the so-called raw diff output, showing which files changed in a commit. You can then examine the suspected commit with git show. From there, you can find the author of the said commit, and ask them for clarification or ask them to fix it (by sending them a bug report). If the good practice of creating small, incremental changes was followed during the development of the project, the amount of code to examine after finding the bad commit should be small.
If, at any point, you land on a commit that broke something unrelated and is not a good one to test, you can skip such a commit with git bisect skip. You can even skip a range of commits by giving the revision range to the skip subcommand.
When you’re finished, you should run git bisect reset to return you to the branch you started from:
$ git bisect resetPrevious HEAD position was b047b02... secure this thingSwitched to branch 'master'To finish bisection while staying on the bad commit you found, you can use git bisect reset HEAD.
Automating testing during the git bisect process
Section titled “Automating testing during the git bisect process”You can even fully automate finding bad revisions with git bisect run. For this, you need to have a script that will test for the presence of a bug and exit with a value of 0 if the project works all right, or a non-0 value if there is a bug. The special exit code, 125, should be used when the currently checked-out code cannot be tested. In this case, you also start the bisect operation by providing the known bad and good commits. You can do this by simply listing them with the bisect start command if you want, listing the known bad commit first and the known good commit(s) second. You can even cut down the number of trials, if you know what part of the tree is involved in the problem you are tracking down, by specifying path parameters (the double-dash before the path is not strictly necessary, but is helpful). Then, you start automated bisection:
$ git bisect start v1.5-rc0 v1.4 -- arch/i386$ git bisect run ./test-error.shDoing so automatically runs test-error.sh on each checked-out commit until Git finds the first broken commit.
If the bug is that the project stopped compiling (a broken build), you can use make as a test script (with git bisect run make).
Selecting and formatting the git log output
Section titled “Selecting and formatting the git log output”Now that you know how to select revisions to examine and limit which revisions are shown (selecting those that are interesting), it is time to see how to select which part of the information is associated with the queried revisions to show, and how to format this output. There is a huge number and variety of options for the git log command available for this.
Predefined and user-defined output formats
Section titled “Predefined and user-defined output formats”A very useful git log option is --pretty. This option changes the format of the log output. There are a few prebuilt formats available for you to use. The oneline format prints each commit on a single line, which is useful if you’re looking at a lot of commits; there exists the --oneline shorthand for --pretty=oneline --abbrev-commit used together. In addition, the short, medium (the default), full, and fuller formats show the output in roughly the same format, but with less or more information, respectively. The raw format shows commits in internal Git representation, and email or mboxrd in a git format-patch -like format, as an email. The reference format is intended to refer to another commit in a commit message, per the following example:
$ git show --no-patch --pretty=reference master^20cfc7c (Added COPYRIGHT, 2021-05-30)It is possible to change the format of dates shown in those verbose, pretty formats with an appropriate --date option: make Git show relative dates such as, for example, 2 hours ago, with --date=relative, dates in your local time zone with --date=local, and so on.
You can also specify your own log output format with --pretty=format:<string> (and its tformat variant, with terminator rather than separator semantics — output for each commit has the newline appended). This is especially useful when you’re generating output for machine parsing for use in scripts because when you specify the format explicitly, you know it won’t change with updates to Git. The format string works a little bit like in printf:
$ git log --pretty="%h - %an, %ar : %s"50f84e3 - Junio C Hamano, 7 days ago : Update draft release notes0953113 - Junio C Hamano, 10 days ago : Second batch for 2.1afa53fe - Nick Alcock, 2 weeks ago : t5538: move http push tests outThere is a very large number of placeholders. Selected ones of those are listed in the following table:
| Placeholder | Description of output |
|---|---|
%H | Commit hash (full SHA-1 identifier of revision) |
%h | Abbreviated commit hash |
% an | Author name |
% ae | Author email |
% ar | Author date, relative |
% cn | Committer name |
% ce | Committer email |
% cr | Committer date, relative |
%s | Subject (first line of a commit message, describing revision) |
%% | A raw % |
Table 5.1 – Placeholders and their description
Author versus committer
The author is the person who originally wrote the patch (authored the changes), whereas the committer is the person who last applied the patch (created a commit object with those changes, representing the revision in the DAG). So, if you send in a patch to a project and one of the core members applies the patch, both of you get credit — you as the author and the core member as the committer. Also, after rebase, for rebased revisions the original author of the commit is kept, while the person performing the rebase is made the committer.
The --oneline format option is especially useful together with another git log option called --graph, though the latter can be used with any format. The latter option adds a nice little ASCII graph showing your branch and merge history. To see where tags and branches are, you can use an option named --decorate (which in modern Git is now the default):
$ git log --graph --decorate --oneline origin/maint* bce14aa (origin/maint) Sync with 1.9.4|\| * 34d5217 (tag: v1.9.4) Git 1.9.4| * 12188a8 Merge branch 'rh/prompt' into maint| |\| * \ 64d8c31 Merge branch 'mw/symlinks' into maint| |\ \* | | | d717282 t5537: re-drop http tests* | | | e156455 (tag: v2.0.0) Git 2.0You might want to use a graphical tool to visualize your commit history. One such tool is a Tcl/Tk program called gitk that is distributed with Git. You can find more information about various types of graphical tools in Chapter 13, Customizing and Extending Git.
Including, formatting, and summing up changes
Section titled “Including, formatting, and summing up changes”You can examine a single revision with the git show command, which, in addition to the commit metadata, shows changes in the unified diff format, described in Chapter 2, Developing with Git, in the Unified Git diff format subsection. Sometimes, however, you might want to display changes alongside the selected part of the history in the git log output. You can do this with the help of the -p option. This is very helpful for code review, or to quickly browse what happened during a series of commits that a collaborator has added.
Ordinarily, Git would not show the changes for a merge commit. To show changes from all parents, you need to use the –c option (or –cc for compressed output), while to show changes from each parent individually, use –m.
Sometimes, it’s easier to review changes on the word level rather than on the line level. The git log accepts various options to change the format of the diff output. One of those options is --word-diff (with various variants, including color). This way of viewing differences is useful for examining changes in documents (for example, documentation):
commit 06ab60c06606613f238f3154cb27cb22d9723967Author: Jason St. John <[email protected]>Date: Wed May 21 14:52:26 2014 -0400 Documentation: use "command-line" when used as a compound adjective, and fix Signed-off-by: Jason St. John <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>diff --git a/Documentation/config.txt b/Documentation/config.txtindex 1932e9b..553b300 100644--- a/Documentation/config.txt+++ b/Documentation/config.txt@@ -381,7 +381,7 Set the path to the root of the working tree. This can be overridden by the GIT_WORK_TREE environment variable and the '--work-tree' [-command line-]{+command-line+} option. The value can be an absolute path or relative to the path to the .git directory, which is either specified by --git-dir or GIT_DIR, or automatically discovered.Another useful set of options is about ignoring changes in whitespace, including –w / --ignore-all-space to ignore all whitespace changes, and -b / --ignore-space-change to ignore changes in the amount of whitespace.
With color support, you can ask Git to show moved code with --color-moved, possibly ignoring whitespace changes (with --color-moved-ws).
Sometimes, you are interested only in the summary of changes and not the details. There is a series of diff summarizing options that you can use. If you want to know only which files changed, use --names-only (or --raw --abbrev). If you also want to know how much those files changed, you can use the --stat option (or perhaps its machine-parse-friendly version, --numstat) to see some abbreviated stats. If you are interested only in a short summary of changes, use --shortstat or --summary.
Summarizing contributions
Section titled “Summarizing contributions”Ever wondered how many commits you’ve contributed to a project? Or, perhaps, who the most active developer was during the last month (with respect to the number of commits)? Well, wonder no more, because this is what git shortlog is good for:
$ git shortlog -s -n 13885 Junio C Hamano 1399 Shawn O. Pearce 1384 Jeff King 1108 Linus Torvalds 743 Jonathan NiederThe -s option squashes all of the commit messages into the number of commits; without it, git shortlog would list a summary of all the commits, grouped by the developer. The -n option sorts the list of developers by the number of commits; otherwise, it is sorted alphabetically. You can add an –e option to also show an email address; note, however, that with this option, Git will separate contributions made by the same author under different emails. The git shortlog output can be configured to some extent with a pretty-like -- format option.
The git shortlog command accepts a revision range and other revision-limiting options such as --since=1.month.ago — anything that git log accepts and makes sense for shortlog. For example, to see who contributed what to the last release candidate, you can use the following command:
$ git shortlog -e v2.0.0-rc2..v2.0.0-rc3Jonathan Nieder <[email protected]> (1): shell doc: remove stray "+" in exampleJunio C Hamano <[email protected]> (14): Merge branch 'cl/p4-use-diff-tree' Update draft release notes for 2.0 Merge branch 'km/avoid-cp-a' into maint…Tip
One needs to remember that the number of revisions authored is only one way of measuring contribution. For example, somebody who creates buggy commits only to fix them later would have a larger number of commits than a developer who doesn’t make mistakes (or cleans the history before publishing changes).
There are other measures of programmer productivity — for example, the number of changed lines in authored commits, or the number of surviving lines. Those can be calculated with the help of Git, but there is no built-in command to calculate them.
Mapping authors
Section titled “Mapping authors”One problem with running git shortlog –s -n -e or git blame in Git repositories of long-running projects is that an author may change their name or email, or both, during the course of the project, due to many reasons: changing work (and work email), misconfiguration, spelling mistakes, and others. For example, you might have Bob Hacker [email protected] in one place, but Bob [email protected] in the other. When that happens, you can’t get proper attribution. Git allows you to coalesce author/email pairs with the help of the .mailmap file in the top directory of your project. This file allows you to specify canonical names for contributors, which in its simplest form looks like this:
Bob Hacker <[email protected]>(Actually, it allows you to specify a canonical name, canonical email, or both name and email, matching by email or by name and email.)
By default, those corrections are applied to all commands: git blame, git shortlog, and git log. With custom log output, you can use placeholders that output the original name or corrected name, and the original email or corrected email.
Viewing a revision and a file at revision
Section titled “Viewing a revision and a file at revision”Sometimes, you might want to examine a single revision (for example, a commit suspected to be buggy, found with git bisect) in more detail, together with changes and their descriptions. Or, perhaps, you want to examine the tag message of an annotated tag together with the commit it points to. Git provides a generic git show command for this; it can be used for any type of object.
For example, to examine the grandparent of the current version, you can use the following command:
$ git show HEAD^^commit ca3cdd6bb3fcd0c162a690d5383bdb8e8144b0d2Author: Bob Hacker <[email protected]>Date: Sun Jun 1 02:36:32 2014 +0200 Added COPYRIGHTdiff --git a/COPYRIGHT b/COPYRIGHTnew file mode 100644index 0000000..862aafd--- /dev/null+++ b/COPYRIGHT@@ -0,0 +1,2 @@+Copyright (c) 2014 VirTech Inc.+All Rights ReservedThe git show command can also be used to display directories (trees) and file contents (blobs). To view a file (or a directory), you need to specify where it is from (from which revision) and the path to the file, using : to connect them. For example, to view the contents of the src/rand.c file as it was in the version tagged v0.1, use the following:
$ git show v0.1:src/rand.cThis might be more convenient than checking out the required version of the file into the working directory with git checkout v0.1 -- src/rand.c. Before the colon may be anything that names a commit (v0.1 here), and after that, it may be any path to a file tracked by Git (src/rand.c here). The pathname here is the full path from the top of the project directory, but you can use ./ after the colon for relative paths — for example, v0.1:./rand.c if you are in the src/ subdirectory.
You can use the same trick to compare arbitrary files at arbitrary revisions; on the other hand, the git show :src/rand.c command (as if with an empty revision) will show the state of the file at the time git add was run — the state of the chosen file in the index (in the staging area).
If you want to find out what files are present at a given revision (to select one to examine), you can use git ls-tree <revision>. To find out what files are present in the worktree and in the index, use git ls-files with the appropriate option to select what you want to see.
Summary
Section titled “Summary”This chapter showed us the various ways of exploring project history: selecting and filtering revisions to display, searching through various parts of commit-related data, and formatting the output.
You have learned how to find all the revisions that were made by a given developer, how to search through the commit message and the changes made by the commit, and how to narrow the search to a specific range of time.
We can even try to find bugs in the code by exploring the history: finding when a function was deleted from the code with a pickaxe search, examining a file for how its code came to be and who wrote it with git blame, and utilizing semi-automatic or automatic search through the project history to find which version introduced a regression with git bisect.
When examining a revision, we can select the format in which the information is shown, even to the point of user-defined formats. There are various ways of summarizing the information, from the statistics of the changed files, to the statistics of the number of commits per author.
In the next chapter, we will examine how Git can help developers work together as a team on a single project.
Questions
Section titled “Questions”Answer the following questions to test your knowledge of this chapter:
- How would you list all commits made since yesterday on any remote-tracking branch?
- How would you find out who the original author of a given function or class was, to ask for clarification or a code review?
- How would you use Git to help find the source of regression — that is, a bug that is present in the new revision of the project, but was not there in older versions?
- You have noticed that your colleague made a few commits with a misconfigured email, using
[email protected]instead of[email protected]. How would you fix the attribution, assuming that it is not possible to rewrite those commits?
Answers
Section titled “Answers”Here are the answers to the questions given above:
- Combine time-limiting options with the
--remotesoption: git log --since=yesterday --remotes.- Use the
git blamecommand or an interactive GUI to do this, such asgit gui blame(or an integration with your editor or integrated development environment (IDE); you can also search through the history of the relevant fragment of a file withgitlog -L. - Use
git bisectto find the commit that introduced the bug, perhaps even by automating the search withgitbisect run. - Add the correct name and email to the
.``mailmapfile.
Further reading
Section titled “Further reading”To learn more about the topics that were covered in this chapter, take a look at the following resources:
- Scott Chacon, Ben Straub, Pro Git, 2nd Edition (2014), Apress, Chapter 7*.5 Git Tools –* Searching: https://git-scm.com/book/en/v2/Git-Tools-Searching
- Christian Couder, Fighting regressions with git bisect (slides from the Linux-Kongress 2009 conference): http://www.linux-kongress.org/2009/slides/fighting_regressions_with_git_bisect_christian_couder.pdf
- Junio C Hamano, Fun with first parent history (2013): https://git-blame.blogspot.com/2013/09/fun-with-first-parent-history.html
- Junio C Hamano, Measuring Project Activities (2) (2013): https://git-blame.blogspot.com/2013/03/measuring-project-activities-2.html
- Jan Goyvaerts, Regular Expressions Tutorial - Learn How to Use and Get The Most out of Regular Expressions: https://www.regular-expressions.info/tutorial.html