Keeping History Clean
local graph
Chapter 10 — Keeping History Clean
Section titled “Chapter 10 — Keeping History Clean”The previous chapter, Merging Changes Together, described how to join changes developed by different people (as described in Chapter 6, Collaborative Development with Git), or just developed in a separate feature branch (as shown in Chapter 8, Advanced Branching Techniques). One of the techniques was rebase, which can help bring a branch to be merged to a better state. However, if we are rewriting history, perhaps it would be possible to also modify the rebased commits to be easier for review, making the development steps of a feature clearer. If rewriting is forbidden, can one make history cleaner without it? How do we fix mistakes if we cannot rewrite project history?
This chapter will answer all those questions. It will explain why one might want to keep a clean history, when it can and should be done, and how it can be done. Here you will find step-by-step instructions on how to reorder, squash, and split commits. This chapter will also describe how to do large-scale history rewriting (for example, the clean-up after imports from other VCS) and what to do if one cannot rewrite history: in other words, using reverts, replacements, and notes.
To really understand some of the topics presented here, and to truly master their use, you need some basics of Git internals. These are presented at the beginning of this chapter.
In this chapter, we will cover the following topics:
- The basics of the object model of Git repositories
- Why you shouldn’t rewrite published history, and how to recover from doing so
- The interactive rebase: reordering, squashing, splitting, and testing commits
- Large-scale scripted history rewriting
- Reverting a revision, reverting a merge, and re-merging after a reverted merge
- Amending history without rewriting with replacements
- Appending additional information to objects with notes
An introduction to Git internals
Section titled “An introduction to Git internals”To really understand and make good use of at least some of the methods described in this chapter, you will need to understand at least the very basics of Git internals. Among other things, you will need to know how Git stores the information about revisions.
When describing Git internals, it will be useful to create different types of data to later examine. This can be achieved with a set of low-level commands that Git provides as a supplement to user-facing high-level commands. These low-level commands operate on the level of the internal representation instead of using friendly abstractions. That makes those commands very flexible and powerful, though perhaps not user-friendly.
Git objects
Section titled “Git objects”In Chapter 4, Exploring Project History, you learned that Git represents history as the Directed Acyclic Graph (DAG) of revisions, where each revision is a graph node represented as a commit object. Each commit is identified by the SHA-1 identifier. We can use this identifier (in its full or ambiguous shortened form) to refer to any given version.
The commit object consists of revision metadata, links to zero or more parent commits, and the snapshot of the project’s files at the revision that it represents. The revision metadata includes information about who made changes and when, who created the commit object (who entered changes into the repository) and when, and of course the commit message.
Beyond this fact, it is also useful, in some cases, to know how Git internally represents the snapshot of a project’s files at the given revision. Git uses tree objects to represent directories, and Binary Large Objects (blobs) to represent the contents of a file.
Aside from the commit, tree, and blobs, there might also be tag objects representing annotated and signed tags.
Each object is identified by the SHA-1 hash function over its contents, or to be more exact, over the type and the size of the object plus its contents. Such a content-based identifier does not require a central naming service. Thanks to this fact, each and every distributed repository of the same project will use the same identifiers, and we do not have to worry about name collisions:
# calculate SHA-1 identifier of blob object with Git$ printf "foo" | git hash-object -t blob --stdin19102815663d23f8b75a47e7a01965dcdc96468c# calculate SHA-1 identifier of blob object by hand$ printf "blob 3\0foo" | sha1sum19102815663d23f8b75a47e7a01965dcdc96468cObject identifier – SHA-1 to SHA-256 transition
Over time, flaws in the SHA-1 hash function have been discovered. Therefore, Git will transition to using SHA-256 while providing interoperability. At the time of writing this, Git was still using SHA-1 by default.
We can say that the Git repository is the content-addressed object database. That is, of course, not all there is; there are also references (branches and tags), various configuration files, and other things.
Let’s describe Git objects in more detail, starting from the bottom up. We can examine objects with the low-level git cat-file command:
- Blob: These objects store the contents of the file at the given revision. Such an object can be created using the low-level
git hash-object -wcommand. Note that if different revisions have the same contents of a file, it is stored only once thanks to content-based addressing:$ git cat-file blob HEAD:COPYRIGHTCopyright (c) 2014 CompanyAll Rights Reserved - Tree object: These objects represent directories. Each tree object is a list of entries, sorted by filename. Each entry is composed of combined permissions and type, the name of the file or directory, and the link (that is, SHA-1 identifier) of an object connected with the given path, either the tree object (representing the subdirectory), the blob (representing the file contents), or rarely the commit object (representing the submodule; see Chapter 11, Managing Subprojects). Note that if different revisions have the same contents of a subdirectory, it will be stored only once thanks to content-based addressing:
$ git cat-file -p HEAD^{tree}100644 blob 862aafd...COPYRIGHT100644 blob 25c3d1b...Makefile100644 blob bdf2c76...README040000 tree 7e44d2e...Note that the real output includes full 40-character SHA-1 identifiers, not shortened ones as in the preceding example. You can create tree objects out of the index (which you can create using thesrc
git update-indexcommand) withgit write-tree. - Commit object: These objects represent revisions. Each commit is composed of a set of headers (key-value data) that includes zero or more
parentlines and exactly one tree line with the link to thetreeobject representing a snapshot of the repository contents (the top directory of a project). You can create a commit with a given tree object as a revision snapshot by using the low-levelgit commit-treecommand, or by simply usinggit commit:$ git cat-file -p HEADtree 752f12f08996b3c0352a189c5eed7cd7b32f42c7parent cbb91914f7799cc8aed00baf2983449f2d806686parent bb71a804f9686c4bada861b3fcd3cfb5600d2a47author Joe Hacker <[email protected]> 1401584917 +0200committer Bob Developer <[email protected]> 1401584917 +0200Merge remote branch 'origin/multiple' - Tag object: These objects represent annotated tags, of which signed tags are a special case. Tags (lightweight and annotated) give a permanent name to a commit (such as
v0.2) or any object. Tag objects also consist of a series of headers (including links to the tagged object) and the tag message. You can create the tag object with a low-levelgit mktagcommand, or simply withgit tag:$ git cat-file tag v0.2object 5d2584867fe4e94ab7d211a206bc0bc3804d37a9type committag v0.2tagger John Tagger <[email protected]> 1401585007 +0200random v0.2
Internal datetime format
The Git internal format for the author, the committer, and the tagger dates is <unix timestamp> <timezone offset>. The Unix timestamp (POSIX time) is the number of seconds since the Unix epoch, which is 00:00:00 Coordinated Universal Time (UTC), Thursday, January 1st, 1970 (1970-01-01T00:00:00Z), not counting leap seconds. This denotes when the event took place. You can print the Unix timestamp with date "%s" and convert it into other formats with date --date="@<timestamp>".
The timezone offset is a positive or negative offset from UTC, in the HHMM (hours, minutes) format. For example, CET (the timezone that is 2 hours ahead of UTC) is +0200. This can be used to find the local time for an event.
The relationship between different types of Git objects mentioned here is shown in Figure 10*.1*. It represents a typical case, with a tag pointing to a commit and with commits sharing the same contents of at least some files.

Figure 10.1 – The Git repository object model
Some Git commands work on any type of object. For example, you can tag any type of object, not only commits. You can, among other things, tag a blob to keep some unrelated piece of data in the repository and have it available in each clone. Public keys can be such data.
Notes and replacements, which will be described later in this chapter, also work on any type of object.
Plumbing and porcelain Git commands
Section titled “Plumbing and porcelain Git commands”Git was developed in a bottom-up fashion. This means that its development started from basic blocks and built upward. Many of the user-facing commands were once built as shell scripts utilizing these basic low-level blocks to do their work. Thanks to this, we can distinguish between the two types of Git commands.
The better-known type is porcelain commands, which are high-level user-facing commands (porcelain is a play on words on calling engine-level commands plumbing). The output of these commands is intended for the end user. This means that their output can be changed to be more user-friendly. Therefore, their output can be different in different Git versions. The user is smart enough to understand what happens if they are presented with additional information, changed wording, or changed formatting (for example).
This is not the case for the scripts you may write in this chapter, such as those used for rewriting with git filter-repo. Here, you need unchanging output – well, at least for the scripts that are used more than once (as hooks, as .gitattribute drivers, and as helpers). You can often find a switch, usually named --porcelain, that ensures that the command output is immutable. For other commands, the solution is to specify the format fully. Alternatively, you can use low-level commands intended for scripting: plumbing commands. These commands usually do not have user-friendly defaults, not to mention a “do what I mean” quality. Their output also does not depend on the Git configuration; not many of them can be configured via the Git configuration file.
The git(1) manpage includes a list of all the Git commands, separated into porcelain and plumbing. The distinction between plumbing and porcelain commands was mentioned as a tip in Chapter 3, Managing Your Worktrees, when we encountered the first low-level plumbing command without a user-facing and user-friendly porcelain equivalent.
Rewriting history
Section titled “Rewriting history”Many times, while working on a project, you may want to revise your commit history. One reason for this could be to make it easier to review before submitting the changes upstream. Another reason would be to take reviewer comments into account in the next improved version of changes. Or perhaps you’d like to have a clear history while finding regressions using bisection, as described in Chapter 4, Exploring Project History.
One of the great things about Git is that it makes revising and rewriting history possible while providing a wide set of tools to revise history and make it clean.
Views on rewriting history
There are two conflicting views among users of the version control system. One states that history is sacred and that you should show the true history of the development, warts, and all. The other states that you should clean up the new history for better readability before publishing it.
An important issue to note is that even though we talk about “rewriting” the history, objects in Git (including commits) are immutable. This means that “rewriting” really means creating a modified copy of commits, a new path in the DAG of revisions. Then, the appropriate branch reference is switched to point to the just-created new path, to the changed copy of the history. The original, pre-rewrite commits are still there in the repository, referenced and available from the reflog (and also from ORIG_HEAD). Well, at least they will be there until they get pruned (that is, deleted) as unreferenced and unreachable objects during garbage collection, though this only happens after the reflog expires.
Amending the last commit
Section titled “Amending the last commit”The simplest case of history rewriting is correcting the latest commit on a branch.
Sometimes you might notice a typo (an error) in a commit message, or that you have committed an incomplete change in the last revision. If you have not pushed (published) your changes, you can amend the last commit. This is done with the --amend option to the git commit command.
The result of amending a commit is shown in Figure 6 in Chapter 2, Developing with Git. Note that there is no functional difference between amending the last commit and changing some commits deeper in the history. In both cases, you are creating a new commit, leaving the old version referenced by the reflog. The difference is in what happens to other commits.
Here, the index (that is, the explicit staging area for commits) shows its usefulness again. For example, if you want to simply fix only the commit message and you do not want to make any other changes, you can use git commit --amend (note the lack of an -a or --all option). This works even if you have started work on a new commit – at least, assuming that you didn’t add any changes to the index. If you did, you can put them away temporarily with git stash, fix the commit message of the last commit, and then pop stashed changes and restore the index with git stash pop --index.
If, on the other hand, you realize that you have forgotten some changes, you can just edit the files and use git commit --amend --all. If the changes are interleaved, you can use git add or its interactive version (utilizing knowledge from Chapter 3, Managing Your Worktrees) to create the contents you want to have, finalizing it with git commit --amend.
The interactive rebase
Section titled “The interactive rebase”Sometimes you might want to edit commits deeper in the history or reorganize commits into a logical sequence of steps. One of the built-in tools in Git that you can use for this purpose is git rebase --interactive.
Here, we will assume that you are working on a feature using a separate topic branch, as well as a topic branch workflow described and recommended in Chapter 8, Advanced Branching Techniques. We will also assume that you are doing the work in a series of logical steps rather than in one large commit.
When implementing a new feature, you usually won’t do it perfectly from the very beginning. You would want to introduce it in a series of small self-contained steps (see Chapter 15, Git Best Practices) to make code review, code audit, and bisection (finding the cause of regressions bugs) easier. Often, you will only see how to split it better after finishing the work. It is also unreasonable to expect that you would not make mistakes while implementing a new feature.
Before submitting the changes (by either pushing them to the central repository, pushing them to your own public repository and sending pull requests, or using some other workflow described in Chapter 6, Collaborative Development with Git), you will often want to update your branch to the up-to-date state of the project to make it easier to merge. By rebasing your changes on top of the current state and having them up-to-date, you will make it easier for the maintainer (the integration manager) to ultimately merge your changes when they are accepted for inclusion into the mainline. Interactive rebase allows you to clean up history, as described earlier, while doing this work.
Aside from tidying up changes before publishing them, there is also additional use for tools such as interactive rebases. While working on a more involved feature, the very first submission is not always accepted into an upstream and added to the project. Often, the process of patch review finds problems with the code, or with the explanation of the changes. Perhaps something is missing (for example, the feature might lack documentation or tests), some commit needs to be fixed, or the submitted series of patches (or the branch submitted in the pull request) should be split into smaller commits for easy review. In this case, you would also use an interactive rebase (or an equivalent tool) to prepare a new version to submit, taking into account the results of the code inspection.
Reordering, removing, and fixing commits
Section titled “Reordering, removing, and fixing commits”Rebase, as described in Chapter 9, Merging Changes Together, consists of taking a series of changes of the commits being rebased and reapplying them on top of a new base (a new commit). In other words, rebase moves changesets, not snapshots. Git starts the interactive rebase by opening the instructions sheet corresponding to those operations of reapplying changes in the editor.
Tip
You can configure the text editor used for editing the rebase instruction file separately from the default editor (which is used, for example, to edit commit messages) with the sequence.editor configuration variable, which can in turn be overridden by the GIT_SEQUENCE_EDITOR environment variable.
Like in the case of the template for editing commits, the instruction sheet is accompanied by the comments explaining what you can do with it (note that if you are using older Git, some interactive rebase commands might be missing from this sheet):
pick 89579c9 first commit in a branchpick d996b71 second commit in a branchpick 6c89dee third commit in a branch# Rebase 89579c9..6c89dee onto b8fffe1 (3 commands)## Commands:# p, pick = use commit# r, reword = use commit, but edit the commit message# e, edit = use commit, but stop for amending# s, squash = use commit, but meld into previous commit# f, fixup = like "squash", but discard this commit's log message# x, exec = run command (the rest of the line) using shell# d, drop = remove commit## These lines can be re-ordered; they are executed from top to bottom.## If you remove a line here THAT COMMIT WILL BE LOST.## However, if you remove everything, the rebase will be aborted.Note that empty commits will be marked with # empty at the end of the line. Depending on your version of Git and your configuration, the instruction sheet may include more commands.
As explained in the comments, the instructions are in the order of execution, starting from the instruction on the top to create the first commit (with the new base as its parent) and ending at the bottom with the instruction copying the commit at the tip of the branch being rebased. This means that revisions are listed in an increasing chronological order, with older commits first. This is the reverse order from the git log output, with the most recent commit first (unless you are using git log --reverse). This is quite understandable; the rebase reapplies changesets in the order in which they were added to the branch, while the log operation shows commits in the order of reachability from the tips.
Each line of the instruction sheet consists of three elements, separated by spaces:
- First, there is a one-word command. By default, the interactive rebase starts with
pick. Each command has a one-letter shortcut that you can use instead of the long form, as shown in the comments (for example, you can usepin place ofpick). - Next, there is a uniquely shortened SHA-1 identifier of a commit to be used with the command. Strictly speaking, it is the identifier of a commit being rebased, which it had before the rebase process started. This shortened SHA-1 identifier is used to pick the appropriate commit (for example, when reordering lines of the interactive rebase instruction sheet, which effectively means reordering commits).
- Lastly, there is the description (subject) of a commit. It is taken from the first line of the commit message. More specifically, it is the first paragraph of the commit message with the line breaks removed, where a paragraph is defined as the set of subsequent lines of text, separated from other paragraphs by at least one empty line – that is, two or more end-of-line characters. This is one of the reasons why the first line of the commit message should be a short description of changes (see Chapter 15, Git Best Practices). This description is for you to help decide what to do with the commit; Git uses its SHA-1 identifier and ignores the rest of the line.
Reordering commits with the interactive rebase is as simple as reordering lines in the instruction sheet. Note, however, that if the changes are not independent, you might need to resolve conflicts, even if there would be no merge conflicts without reordering. In such cases, as instructed by Git, you will need to fix conflicts, mark conflicts as resolved (for example, with git add), and then run git rebase --continue. Git will remember that you are in the middle of an interactive rebase, so you don’t need to repeat the -- interactive option.
The other possibility of dealing with a conflict is skipping a commit, rather than resolving a conflict, by running git rebase --skip. By default, rebase removes changes that are already present in upstream; you might want to use this command in case the rebase didn’t detect correctly that the commit in question is already there in the branch we are transplanting revisions onto. In other words, do skip a commit if you know that the correct resolution of a conflict is an empty changeset.
Tip
You can also make Git present you with the instruction sheet again at any time when rebase stops for some reason (including an error in the instruction sheet, such as using the squash command with the first commit). You can do this with the git rebase --edit-todo command. After editing it, you can continue the rebase.
To remove changes you simply need to remove the relevant line from the instruction sheet or comment it out, or better yet, use the drop command. You can use it to drop failed experiments or to make it easier on the rebase by deleting changesets that you know are already present in the upstream being rebased onto (though perhaps in a different form). Note though that removing the instruction sheet altogether aborts the rebase.
To fix a commit, change the pick command preceding the relevant commit in the instruction sheet to edit (or just e). This would make the rebase stop at this commit, that is, at this step of reapplying changes, similar to what happens in the case of a conflict. To be precise, the interactive rebase applies the commit in question, making it the HEAD commit, and then stops the process, giving control to the user. You can then fix this commit as if it were the current one with git commit --amend, as described in Amending the last commit. After changing it to your liking, run git rebase --continue, as explained in the instruction that Git prints.
Tip
A proper Git-aware command line prompt, such as the one from the Git `contrib/` directory in the Git source code, would tell you when you are in the middle of the rebase (see Chapter 13, Customizing and Extending Git). If you are not using such a prompt, you can always check what’s happening with git status, which says that there is a rebase in progress in such cases. You can also find instructions on what you can do next there.
Alternatively, you can always go to the state before starting the rebase with the git rebase -- abort command.
If you only want to change the commit message (for example, to fix a spelling error or to include additional information), you can skip the need to run git commit --amend and then git rebase --continue by using reword (or r) instead of edit. Git will then automatically open the editor with the commit message. Saving changes and exiting the editor will commit the changes, amend the commit, and continue the rebase.
Squashing commits
Section titled “Squashing commits”Sometimes you might need to make one commit out of two or more, squashing them together. Maybe you decided that it didn’t make sense to split the changes and that they are better together.
With the interactive rebase you can reorder these commits as needed, so that they are next to each other. Then, keep the pick command for the first of the commits to be concatenated together (or change it to the edit command). For the rest of the commits, replace the pick command with either the squash or the fixup command. Git will then accumulate the changes and create the commit with all of them together. The suggested commit message for the folded commit is the commit message of the first commit, with the messages of the commits with the squash command appended. Commit messages with the fixup command are omitted. This means that the squash command is useful for squashing changes, while fixup is useful for adding fixes. If commits had different authors, the folded commit will be attributed to the author of the first commit. The committer will be you, the person performing the rebase.
Let’s assume that you noticed that you forgot to add some parts of the changes to the commit. Perhaps it is missing tests (or just negative tests) or documentation. The commit is in the past, so you cannot simply add to it by amending it. You could use the interactive rebase or the patch management interface to fix it, but it is often more effective to create the commit with forgotten changes and squash it later.
Similarly, when you notice that the commit you created a while ago has a bug, instead of trying to edit it immediately, you can create a fixup commit with a bug fix to be squashed later.
If you use this technique, there might be some delay between noticing the need to make changes or fix a bug and creating the appropriate commit. This gap includes the time taken for the rebase operation.
How do you then mark the commit being created for squashing or fixup? If you use the commit message beginning with the magic squash! ... or fixup! ... strings, respectively, preceding the description (the first line of the commit message, sometimes called the subject) of a commit to be squashed into, you can then later ask Git to autosquash them, thus automatically modifying the to-do list of rebase -i. You can request this on an individual basis with the --autosquash option, or you can enable this behavior by default with the rebase.autoSquash configuration variable. To create an appropriate “magic” commit message, you can use git commit --squash/--fixup (when creating the commit to be squashed into or the bugfix commit).
Splitting commits
Section titled “Splitting commits”Sometimes, you might want to make two commits or more out of one commit, splitting it into two or more parts. You may have noticed that the commit is too large, perhaps because it tries to do too much, and should be split into smaller pieces. Or perhaps you have decided that some part of a changeset should be moved from one commit to another, and extracting it into a separate commit is a first step toward accomplishing that.
Git does not provide a one-step built-in command for this operation. Nevertheless, splitting commits is possible with the clever use of the interactive rebase.
To split a given commit, first mark it with the edit action. As described earlier, Git will stop at the specified commit and give the control back to the user. In the case of splitting a commit, when returning control to Git with git rebase --continue, you would want to have two commits in place of one.
The problem of splitting a commit is comparable to the problem of having different changes tangled together in the working directory from Chapter 2, Developing With Git (the section about the interactive commit), and Chapter 3, Managing Your Worktrees. The difference is that in the case of splitting a commit with the interactive rebase, when the rebase stops for editing, the commit is already created and copied from the branch being rebased. This is simple to fix with git reset HEAD^; as described in Chapter 3, Managing Your Worktrees, this command will keep the working area at the (entangled) state of the commit to be split while moving the HEAD pointer and the staging area for the commit to the state before this revision. Then you can interactively add those changes that you want to have in the first commit to the index, by composing the intermediate step in the staging area. Next, you should check whether you have what you want in the index, then create a commit from it using git commit without the -a or --all option. Repeat these last two steps as often as necessary.
For the last commit in the series (which would be the second one, if you are splitting the commit in two), you can do one of two things. The first option is to add everything to the index, making the working copy clean, and create a commit from the index. The other option is to create a commit from the state of the working area (git commit --all). If you want to keep or start from the commit message of the original commit to be split, you can provide it with the --reuse-message=<commit> or the --reedit-message=<commit> option while creating a commit. I think the simplest way of naming a commit that was split (or that is being split) is to use reflog – it will be the HEAD@{n} entry just before reset: moving to HEAD^ in the git reflog output.
Instead of crafting the commit in the staging area (the index) starting from the parent of the commit to be split and adding changes, perhaps interactively, you could start directly from the final state—the commit to be split—and remove the changes intended for the second step. This can be done, for example, with git reset --patch HEAD^. Frankly, you can use any combination of techniques from Chapter 3, Managing Your Worktrees. I find graphical commit tools such as git gui quite useful for this purpose (you can find out about graphical commit tools, including some examples, in Chapter 13, Customizing and Extending Git).
If you are not absolutely sure that the intermediate revisions you are creating in the index are consistent (they compile, pass the test suite, and so on), you should use git stash save --keep-index to stash away the not-yet-committed changes, bringing the working area to the state composed in the index. You can then test the changes and amend the staging area if fixes are necessary.
Alternatively, you can create the commit from the index and use a plain git stash command to save the state of the working area after each commit. You can then test and amend the created intermediate commit if fixes are necessary. In both cases, you need to restore the changes with git stash pop before working on a new commit in the split.
Testing each rebased commit
Section titled “Testing each rebased commit”A good software development practice is to test each change before committing it. However, this practice is not always followed. Let’s assume that you forgot to test some commit or skipped it because the change seemed trivial and you were pressed for time. The interactive rebase allows you to execute tests (to be precise: any command) during the rebase process with the exec (or x) action. It is run between steps of rebasing commits. The exec command itself is formatted in a different way from the commands described earlier in this chapter: instead of SHA-1 and a summary of a commit, you provide the command to run.
The exec command launches the provided command (given by the rest of the line) in a shell: the one specified in the SHELL environment variable, or the default shell if SHELL is not set. This means that you can use shell feature. For the POSIX shell, this would mean using cd to change directories, > to redirect command output, ; and && to sequence multiple commands, and so on. It is important to remember that the command to be executed is run from the root of the working tree, not from the current directory (i.e., not from the subdirectory you were in when starting the interactive rebase).
If you are strict about not publishing untested changes, you might have worried about the fact that rewritten commits rebased on top of the new changes might not pass tests, even if the original commits did. You can, however, make the interactive rebase test each commit with the --exec option. Here is an example:
$ git rebase --interactive --exec "make test"This would modify the starting instruction sheet, inserting exec make test after each entry:
pick 89579c9 first commit in a branchexec make testpick d996b71 second commit in a branchexec make testpick 6c89dee third commit in a branchexec make testExternal tools – patching management interfaces
Section titled “External tools – patching management interfaces”You might prefer to fix the old commit immediately at the time when you notice the bug, instead of postponing it until the time when the branch is rebased. The latter is usually done just before the branch is sent for review (to publish it). This might be quite some time after realizing the need to edit the past commit.
Git itself doesn’t make it easy to fix the found bug straight away, or at least, not with built-in tools. You can, however, find third-party external tools that implement the patch management interface on the top of Git. Examples of such tools include Stacked Git (StGit) and Git Quilt (Guilt) – the latter is unmaintained, but still usable.
These tools provide similar functionality to Quilt (that is, pushing or popping patches to and from a stack). With such tools, you have a set of work-in-progress “floating” patches in the Quilt-like stack. You also have accepted changes in the form of proper Git commits. You can convert between patch and commit and vice-versa, move and edit patches around, move and edit commits (which is done by turning the commit and its children into patches, reordering or editing patches, and then turning patches back into commits again), squash patches, and so on.
This is, however, an additional tool to install, an additional set of operations to learn (even if they make your work easier), and an additional set of complications coming from the boundary between Git and the tool in question. An interactive rebase is powerful enough nowadays, and, with autosquash, the need for another layer on top of Git is lessened.
Rewriting project history with Git filter-repo
Section titled “Rewriting project history with Git filter-repo”In some use cases, you might need to use a more powerful tool for rewriting and cleaning up history than the interactive rebase. You might want something that would rewrite full history non-interactively when given some specified algorithm for doing the rewrite. Such a situation is a task for the git filter-repo command.
This is an external project that needs to be installed in addition to Git. However, as it is a single-file Python script, installing it is trivial in most cases. It is now recommended by the Git project to use git filter-repo project instead of the built-in git filter-branch command (which is now deprecated).
The calling convention of this command is rather different than the convention for the interactive rebase. By default, it operates on the whole history of the project, changing the full graph of revisions, though you can limit the operation to a selected branch or set of branches with the -- refs option.
This command rewrites the Git revision history by applying custom filters on each revision to be rewritten. That’s another difference: rebase works by reapplying changesets, while filter-branch works with snapshots. One of the consequences of this is that for git filter-repo, a merge is simply a kind of a commit object, while the rebase drops merges and puts commits into a line, at least unless you use the -- rebase-merges option.
Of course, with git filter-repo, you describe how to do the rewrite with appropriate options instead of doing the rewriting interactively. This means that the speed of the operation is not limited by the speed of user interaction but by I/O.
Safety check
Since git filter-repo is usually used for massive rewrites and does irreversible rewriting of the project’s history, it needs to be run from the fresh clone. This means that the user would always have a good backup in the form of a separate clone. If anything goes wrong, you can simply delete your clone and restart.
You can make git filter-repo ignore the fresh clone check with the -- force option.
Running filter-repo without filters
Section titled “Running filter-repo without filters”If you specify no filters, filter-repo will error out unless you specify --force. In this case, the commits will be recommitted without any changes. Such usage would normally have no effect, but it is permitted to allow you to compensate for some Git bugs in the future.
This means that git filter-repo --force, without other options, can be used to make effects implemented by replacement refs permanent. This way, you can use the following technique: use git replace on specified commits to alter history, ensure that it looks correct, and then make the modification permanent. This is the simplest way to do commit parent rewriting.
Important Note
The git filter-repo command command respects replacements (refs in the refs/replace/ namespace). Replacements is a technique to affect the history (or rather, a view of it) without rewriting any revisions. It will be explained later in the Replacements mechanism section.
Available filter types for filter-repo
Section titled “Available filter types for filter-repo”There is a large set of different filtering options to specify how to rewrite history. You can specify more than one option; they are applied in the order in which they are presented.
You can run the command multiple times to achieve your desired results. The --analyze option can be used to analyze repository history, creating a directory of reports, which (among other things) mention renames and list object sizes. This information may be useful in choosing how to filter your repo and to verify the changes.
The git filter-repo command supports the following types of filters:
- Filtering based on paths, which specifies the paths to select or exclude. Note that renames are not followed, so you may need to specify both the old and new names of the path.
- Renaming paths, which may be combined with path filtering.
- Content editing filters, which involve replacing text in a project’s files, removing large blobs (files), or removing specified blobs (versions of file contents).
- Filtering commit messages with special support for filtering author names and emails with the help of
.mailmapor a mailmap-like file. - Renaming tags, which involves replacing one tag prefix with another.
For flexibility, filter-repo also allows you to specify functions in Python to further filter all changes using custom API, with various --<something>-callback options, such as (for example) --filename-callback or --commit-callback.
You can also configure how commits are rewritten and pruned. For example, you can decide whether to re-encode commit message into UTF-8, or whether to prune commits that have become empty (that is, ones that bring no changes to the project).
Examples of using filter-repo
Section titled “Examples of using filter-repo”Let’s assume that you committed the wrong file to the repository by mistake, and you want to remove that file from history. Perhaps this was a site-specific configuration file with passwords or their equivalent. Or perhaps, during git add ., you included a generated file that was not properly ignored (such as perhaps a large binary file). Alternatively, it might have turned out that you don’t have the distribution rights to a file and you need to have it removed to avoid copyright violations. Using git rm --cached would only remove it from future commits. You can also quite easily remove the file from the latest version by amending the commit (as described earlier in this chapter).
Let’s assume that the file is called passwords.txt. To excise it from the entire history, you can use the following command:
$ git filter-repo --path 'passwords.txt' --invert-pathsIf you want to delete all .DS_Store files in any directory (and not only from the top directory of the project), you can use one of two commands. Here is the first option:
$ git filter-repo --invert-paths --path '.DS_Store' --use-base-nameYou can also use the following option:
$ git filter-repo --invert-paths --path-glob '*/.DS_Store' --path '.DS_Store'You can use filter-repo to remove all API keys or passwords from the history by specifying the text to replace in files. You can match literal text, shell globs, or regular expressions, and specify the replacement (it will be ***REMOVED*** if the replacement is not specified). For example, to remove accidentally committed GitHub Personal Access Tokens, you can use the file specifying the list of expressions, one per line. Let’s say that you create an expressions.txt file with the following contents:
regex:ghp_ua[A-Za-z0-9]{20,}==><access_token>Then you need to run the following command:
$ git filter-repo --replace-text expressions.txtYou can use filter-repo to permanently join two repositories, connecting histories. You can also use it to split history in two. The simplest solution is to use replacements, check that the joined or split history has rendered correctly, and then make the replacements permanent. For example, to split history and remove everything later than v1.0 tag, you can use the following:
$ git replace --graft v1.0^{commit}$ git filter-repo --forceAnother common case is to fix erroneous names or email addresses in commits. Perhaps you forgot to run git config to set your name and email address before you started working and Git guessed them incorrectly (if it couldn’t guess, it would ask before allowing a commit). Maybe you want to open the sources of a formerly proprietary closed source program and need to change your internal corporate email to your personal address. We’ll say that you want the change to be permanent instead of relying on the .``mailmap file.
In any case, you can change email addresses in a whole history with filter-repo:
$ git filter-repo --use-mailmapIf you are open-sourcing a project, you could also want to add the Signed-off-by: lines for the Digital Certificate of Origin (see Chapter 15, Git Best Practices), and add the trailer to the commit message if one is not already present:
$ git filter-repo --message-callback ' if b"Signed-off-by:" not in message: message += "\n\nSigned-off-by: Joe Hacker <[email protected]>" return messageSuppose that you have noticed a typo in the name of a subdirectory, such as inlude/ instead of include/. This can be fixed simply by running the following:
$ git filter-repo --path-rename inlude/:include/Often, some part of a larger project will take on a life on its own. In those instances, it begins to make sense to separate the part from the project it started in. We would want to extract the history of this part to make its subdirectory the new root. To rewrite history in this way and discard all other history, you can run the following:
$ git filter-repo --subdirectory-filter lib/fooHowever, perhaps a better solution would be to use a specialized third-party tool, namely git subtree. This tool (and its alternatives) will be discussed in Chapter 11, Managing Subprojects.
External tools for large-scale history rewriting
Section titled “External tools for large-scale history rewriting”The git filter-repo project is not the only solution for a large-scale rewriting of the project’s history. There are other tools that are more specialized, perhaps including lots of predefined clean-up operations or providing some level of interactivity with the ability for scripted rewrites (with a Read–Evaluate–Print Loop (REPL), similar to interactive shells in some interpreted programming languages).
Removing files from the history with the BFG Repo Cleaner
Section titled “Removing files from the history with the BFG Repo Cleaner”The BFG Repo Cleaner is a specialized alternative to using git filter-repo. It is specialized for the purpose of cleaning bad data out of your Git repository history by removing files and directories and replacing text in files (for example, accidentally committed passwords or API keys with their placeholders). It can use multiple cores with parallel processing – BFG is written in Scala and uses JGit as a Git implementation.
BFG provides a set of command-line parameters that are specialized for removing files and fixing them, such as --delete-files or --replace-text, a “query language” of sorts. It lacks the flexibility of other tools. Nowadays, filter-repo can do everything it can. There is even bfg-ish, a reimplementation of BFG based on filter-repo.
One issue you need to remember is that BFG assumes that you have fixed the contents of your current commit.
Editing the repository history with reposurgeon
Section titled “Editing the repository history with reposurgeon”The reposurgeon project was originally created to help clean up artifacts created by the repository conversion (migrating from one version control system to another). It relies on being able to parse, modify, and emit the command stream in the git fast-import format, which is a common export and import format among source control systems nowadays thanks to it being version control-agnostic. The git filter-repo tool, which was described earlier in this chapter, is also based on processing fast-import streams.
It can be used for history rewriting, including editing past commits and metadata, excising commits, squashing (coalescing) and splitting commits, removing files and directories from history, and splitting and joining history.
The advantage that reposurgeon has over git filter-repo is that it can be run in two modes: either as an interactive interpreter, a kind of debugger or editor for history, with command history and tab completion; or in a batch mode to execute commands given as arguments. This allows users to interactively inspect history and test changes, and then batch run them for all the revisions.
The disadvantage is in having to install and then learn to use a separate tool.
The perils of rewriting published history
Section titled “The perils of rewriting published history”There is, however, a very important principle to know about: you should never (or at least not without a very, very good reason) rewrite published history, especially when it comes to those commits that were pushed to the public repository or were otherwise made public. What you can do is change the parts of the graph of revisions that are private.
The reason behind this rule is that rewriting published history could cause trouble for downstream developers if they have based their changes on revisions that were rewritten.
This means that it is safe to rewrite and rebuild those public branches that are explicitly stated and documented to be in flux, for example, as a way of showing work in progress (such as ' proposed-updates ' type of branch, that is used to test merge all feature branches – see the Visibility without integration and Progressive-stability branches sections in Chapter 8*, Advanced Branching Techniques*). Another possibility for the safe rewriting of a public branch is to do it at specific stages of the project’s life, namely after creating a new release; again, this needs to be documented.
The consequences of upstream rewrites
Section titled “The consequences of upstream rewrites”Now you will see, in a simple example, the perils of rewriting published history (for example, rebasing) and how it causes trouble. Let’s assume that there are two public branches that are of interest: master and subsys. The latter is based on (forked from) the former. Let’s also assume that a downstream developer (who might be you) created a new topic branch based on the subsys branch for their own work, but did not publish it yet; it is only present in their local repository. This situation is shown in Figure 10*.2* (the revisions below the dashed lines, denoted by darker color, are present only in the local repository of the downstream developer).

Figure 10.2 – The state of the local repository of a downstream developer before the rewrite of the published history, with the new local work that was put on a topic branch
Then, the upstream developer rewrites the subsys branch to start from the current (topmost) revision in the master branch. This operation is called rebase and was described in Chapter 9, Merging Changes Together (the previous chapter). Let’s assume that during the rewrite, one of the commits was dropped; perhaps the same change was already present in master and was skipped, perhaps it was dropped for some other reason, or perhaps it was or squashed into the previous commit with the interactive rebase. The public repository now looks as follows:

Figure 10.3 – The state of a public upstream repository after rewrite, with an emphasized old base of the rebased branch, plus a new base and rewritten commits (after the rebase)
Note that in the default configuration, Git would refuse to push rewritten history (it would deny a non-fast-forward push). You would need to force the push.
The problem is with merging changes based on the pre-rewrite versions of revisions, such as the topic branch in this example.

Figure 10.4 – The situation after merging the changes that were based on pre-rewrite revisions into post-rewrite branches
Notice that the merge brings the pre-rewrite version of revisions, including commits that were dropped during the rebase.
If neither the downstream developer nor the upstream one notices that the published history has been rewritten, and one of them merges changes from the topic branch into, for example, the subsys branch it was based on, the merge would bring about duplicated commits. As we can see in the example in Figure 10*.3*, after such a merge (denoted by M13 here), we have both the C3, C4, and C5 pre-rewrite commits brought by the topic branch and the C3’ and C5’ post-rewrite commits (see Figure 10*.4*). Note that the C4 commit that was removed in the rewrite is back – it might have been a security bug!
Recovering from an upstream history rewrite
Section titled “Recovering from an upstream history rewrite”However, what can we do if the upstream has rewritten the published history (for example, rebased it)? Can we avoid bringing the abandoned commits back and merging a duplicate or near-duplicate of the rewritten revisions? After all, if the rewrite is published, changing it would be yet another rewrite.
The solution is to rebase your work to fit with the new version from the upstream, moving it from the pre-rewrite upstream revisions to the post-rewrite ones.

Figure 10.5 – The situation after a downstream rebase of a topic branch
In the case of our example, it would mean rebasing the topic branch onto a new (post-rewrite) version of subsys, as shown in Figure 10*.5*.
Tip
You might not have a local copy of the subsys branch; in this case, do substitute subsys with the respective remote-tracking branch, for example, origin/subsys.
Depending on whether the topic branch is public or not, it might mean that you are now breaking the promise of unaltered public history for your downstream. Recovering from an upstream rewrite might then result in a ripple of rebases following the rewrite down the river of downstreams (dependent repositories).
An easy case is when subsys is simply rebased and the changes remain the same (which means that C4 vanished because C6 - C9 included it). Then you can simply rebase topic on top of its upstream, that is, subsys, with the following:
$ git rebase subsys topicThe topic part is not necessary if you are currently on it (if topic is the current branch). This rebases everything: the old version of subsys and your commits in topic. This solution, however, relies on the fact that git rebase would skip repeated commits (removing C3, C4, and C5, leaving only C10’ and C12’). It might be better and less error-prone to assume the more difficult case.
The hard case is when rewriting subsys involved some changes and was not a pure rebase, or when an interactive rebase was used. In this case, it is better to explicitly move just your changes, namely subsys@{1}..topic (assuming that the subsys@{1} entry in the subsys reflog comes from before rewrite), stating that they are moved on top of the new subsys. This can be done with the -- onto option:
$ git rebase --onto subsys subsys@{1} topicYou can make Git use the reflog to find a better common ancestor with the --fork-point option with the git rebase command, such as in the following example:
$ git rebase --fork-point subsys topicThe rebase would then move the changes to topic, starting with the result of the git merge-base --fork-point subsys topic command. However, if the reflog of the subsys branch does not contain necessary information, Git would fall back upstream, here to subsys.
Important note
You can use the interactive rebase instead of an ordinary rebase like in the narration mentioned earlier for better control at the cost of more work (for example, to drop commits that are already present, but are not detected by the rebase machinery as such).
Amending history without rewriting
Section titled “Amending history without rewriting”What should you do if what you need to fix is in the published part of the history? As described in The perils of rewriting published history, changing those parts of the history that were made public can cause problems for downstream developers. You had better not touch this part of the graph of revisions.
There are a few solutions to this problem. The most commonly used one is to put in a new fixup commit with appropriate changes (for example, a typo fix in documentation). If what you need is to remove the changes, deciding that they turned out to be bad to have in the history, you can create a commit to revert the changes.
If you fix a commit or revert one, it would be nice to annotate that commit with the information that it was buggy, as well as which commit fixed (or reverted) it. Even though you cannot (and should not) edit the fixed commit to add this information if the commit is public, Git provides the notes mechanism to append extra information to existing commits, which is a bit like publishing an addendum, errata, or amendment. However, remember that notes are not published by default; nonetheless, it is easy to publish them (you just need to remember to do it).
Reverting a commit
Section titled “Reverting a commit”If you need to back out an existing commit, undoing the changes it brought, you can use git revert. As described in Chapter 9, Merging Changes Together (see, for example, Figure 9*.5* in that chapter), the revert operation creates a commit with the reverse of any changes. For example, where the original adds a line, reversion removes it; where the original commit removes the line, reversion adds it.
Trivia
Note that different version control systems use the name revert for different operations. In particular, it is often used to mean resetting the changes to a file back to the latest committed version, throwing away uncommitted changes. It is something that git reset -- <file> does in Git.
This is best shown in an example. Let’s assume that the last commit on the multiple branch has the following summary of its changes:
$ git show --stat multiplecommit bb71a804f9686c4bada861b3fcd3cfb5600d2a47Author: Alice Developer <[email protected]>Date: Sun Jun 1 03:02:09 2014 +0200 Support optional <count> parameter src/rand.c | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-)Reverting this commit (which requires a clean working directory) would create a new revision. This revision undoes the changes that the reverted commit brought:
$ git revert bb71a80[master 76d9e25] Revert "Support optional <count> parameter" 1 file changed, 5 insertions(+), 21 deletions(-)Git would ask for a commit message, which should explain why you reverted the given revision: how it was faulty, and why it needed to be reverted rather than fixed. The default is to give the SHA-1 of the reverted commit:
$ git show --statcommit 76d9e259db23d67982c50ec3e6f371db3ec9efc2Author: Alice Developer <[email protected]>Date: Tue Jun 16 02:33:54 2015 +0200 Revert "Support optional <count> parameter" This reverts commit bb71a804f9686c4bada861b3fcd3cfb5600d2a47. src/rand.c | 26 +++++--------------------- 1 file changed, 5 insertions(+), 21 deletions(-)Compare the summary of changes for the commit and its revert. In the preceding example, the commit has 21 insertions and 5 deletions, while the revert has 5 insertions and 21 deletions (where line that changed from one version to the other counts as deletion of the old version and insertion of the new).
A common practice is to leave the subject alone (which allows you to easily find reverts) but replace the content with a description of the reasoning behind the revert.
Reverting a faulty merge
Section titled “Reverting a faulty merge”Sometimes, you might need to undo the effect of a merge. Suppose that you have merged changes, but it turned out that they were merged prematurely and that the merge brings regressions.
Let’s say that the branch that was merged is named topic, and that you were merging it into the master branch. This situation is shown in Figure 10*.6*.

Figure 10.6 – An accidental or premature merge commit, a starting point for reverting merges and redoing reverted merges.
If you didn’t publish this merge commit before you noticed the mistake, and the unwanted merge exists only in your local repository, the easiest solution is to drop this commit with git reset --hard HEAD^ (see Chapter 3, Managing Your Worktrees, for an explanation of the hard mode of git reset).
What do you do if you realize only later that the merge was incorrect, for example after one more commit was created on the master branch and published? One possibility is to revert the merge.
However, a merge commit has more than one parent, which means more than one delta (or, more than one changeset). To run revert on a merge commit, you need to specify which patch you are reverting, or, in other words, which parent is the mainline. In this particular scenario, assuming that there was one more commit after the merge (and that the merge was two commits back in the history), the command to revert the merge would look like this:
$ git revert -m 1 HEAD^^[master b2d820c] Revert "Merge branch 'topic'"The situation after reverting a merge is shown in Figure 10*.7*.

Figure 10.7 The history from the previous figure after reverting merge; the square boxes attached to selected commits symbolize their changesets in a diff-like format
Starting with the new !M1 commit (the !M1 symbol is used to represent negation or reversal of the M1 commit), it’s as if the merge never happened, at least with regards to the changes.
Recovering from a reverted merge
Section titled “Recovering from a reverted merge”Let’s assume that you continued work on a branch whose merge was reverted. Perhaps it was prematurely merged, but it doesn’t mean that the development on it has stopped. If you continue to work on the same branch, perhaps by creating commits with fixes, they will get ready in some time, and then you will need to be able to merge them correctly into the mainline again. Or perhaps the mainline will mature enough to be able to accept a merge. Trouble lies ahead if you simply try to merge your branch again the same way as last time.

Figure 10.8 – The unexpectedly erroneous result of trying to simply redo a reverted merge
The unexpected result, as shown in Figure 10*.8*, is that Git has only brought the changes since the reverted merge. The changes brought by the commits on a side branch, whose merge got reverted, are not here. In other words, you would get a strange result: the new merge would not include the changes that were created on your branch (the side branch) before the merge that got reverted.
This is caused by the fact that git revert undoes changes (the data), but does not undo the history (the DAG of revisions). This means that the new merge sees C4, the commit on the side branch just before the reverted merge, as a common ancestor. Since the default three-way merge strategy looks only at the state of the ours, theirs, and base snapshots, it doesn’t search through the history to find that there was a revert there. It sees that both the common ancestor C4 and the merged branch (that is, theirs) C6 do include features brought by the C3 and C4 commits, namely f3 and f4, while the branch that we are merging into (that is, ours) doesn’t have them because of the revert.
For the merge strategy, it looks exactly like the case where one branch deleted something, which means that this change (the removal) is the result of the merge (it looks like the case where there was change on only one side). In particular, it looks like the base and the side branch have the feature, but the current branch doesn’t (because of the revert) – so the result doesn’t have it either. You can find an explanation of the merging mechanism in Chapter 9, Merging Changes Together.
There is more than one option to fix this issue and make Git re-merge the topic branch correctly, which means including the f3 and f4 features in the result. The option that you should choose depends on the exact circumstances, for example, whether the branch being merged is published or not. You don’t usually publish topic branches, and if you do, such as perhaps in the form of the proposed-updates branch with all the topic branches merged in, it is with the understanding that they can and probably will be rewritten.

Figure 10.9 The history after re-merging (as M2) a reverted M1 merge, with revering revert!!M1 (replay)
One option is to bring back deleted changes by reverting the revert. The result is shown in Figure 10*.9*. In this case, you have brought changes to match the recorded history.
Another option would be to change the view of the history (perhaps temporarily), for example, by amending it with git replace, or by changing the !M1 merge to a non-merge commit (this will be described later in the chapter). Both of those options are suitable in the situation where at least the parts of the branch being merged, namely topic, were published.
If the problem was some bugs in the commits being merged (on the topic branch), and the branch being merged was not published, you can fix these commits with the interactive rebase, as described earlier. Rebasing changes the history anyway. Therefore, if you additionally ensure that the new history you are creating with the rebase does not have any revision in common with the old history that includes the failed and reverted merge, re-merging the topic branch would pose no challenges.

Figure 10.10 – The history after re-merging the rebased branch, which had its merge reverted
Usually you would rebase a topic branch, topic in this case, on top of the current state of the branch it was forked from, which is the master branch here. This way, your changes are kept up to date with the current work, which makes a later merge easier. Now that the topic branch has a new history, merging it into master “again”, like in Figure 10*.10*, is easy and doesn’t give us any surprises or trouble.
A more difficult case would be if the topic branch is for some reason required to keep its base (such as being able to merge it into the maint branch too). This is not more difficult in the sense that there would be problems with re-merging the topic branch after the rebase, but in that we need to ensure that the branch doesn’t share history with the reverted merge arc after the rebase. The goal is to have history in the same shape as is shown in Figure 10. By default, a rebase tries to fast-forward revisions if they didn’t change (for example, leaving C3 in place if the rebase didn’t modify it), so we need to use -f or --force-rebase to force rebasing of unchanged skippable commits (or of --no-ff, which is equivalent) as well. The result is shown in Figure 10*.11*.

Figure 10.11 The history after re-merging an in-place-rebased topic branch, where a pre-rebase merge was reverted
So, you should not be blindly reverting the revert of a merge. What to do with the problem of re-merging after a reverted merge depends on how you want to handle the branch being merged. If the branch is being rewritten (for example, using an interactive rebase), then reverting the revert would be an actively wrong thing to do because you could bring back errors that were fixed in the rewrite.
Storing additional information with notes
Section titled “Storing additional information with notes”The notes mechanism is a way to store additional information for an object, usually a commit, without touching the object itself. You can think of it as an attachment, or an appendix, that is “stapled” to an object. Each note belongs to some category of notes so that notes used for different purposes can be kept separate.
Adding notes to a commit
Section titled “Adding notes to a commit”Sometimes you want to add extra information to a commit, particularly information that is available only some time after its creation. It might be, for example, a note that there was a bug found in the commit, and perhaps even that it was fixed in some specified future commit (in case of regression). Perhaps we realized after the commit got published that we forgot to add some important information to the commit message, for example, to explain why it was done. Or maybe we realized after the fact that there is another way of doing it and we want to create a note to ensure that we do not forget about it, and for other developers to share the idea.
Since history is immutable in Git, you cannot do this without rewriting the history (creating a modified copy and forgetting the old version of the history). The immutability of history is important; it allows people to sign revisions and trust that, once inspected, history cannot change. What you can do instead is add the extra message as a note.
Let’s assume that codevelopers have switched from atoi() to strtol() because the former is deprecated. The change was made public since then. However, the commit message didn’t include an explanation of why it was deprecated and why it is worth it to switch, even if the code after the change is longer. Let’s add the information as a note:
$ git notes add \ -m 'atoi() invokes undefined behaviour upon error' v0.2~3We have added the note directly from the command line without invoking the editor by using the -m flag (the same flag as for git commit) to simplify the explanation of this example. The note will be visible when running git log or git show:
$ git show --no-patch v0.2~3commit 8c4ceca59d7402fb24a672c624b7ad816cf04e08Author: Bob Hacker <[email protected]>Date: Sun Jun 1 01:46:19 2014 +0200 Use strtol(), atoi() is deprecatedNotes: atoi() invokes undefined behaviour upon errorAs you can see from the preceding output, our note is shown after the commit message in the Notes: section. Displaying notes can be disabled with the --no-notes option, and (re)enabled with --show-notes.
How notes are stored
Section titled “How notes are stored”In Git, notes are stored using extra references in the refs/notes/ namespace. By default, commit notes are stored using the refs/notes/commits ref. This can be changed using the core.notesRef configuration variable, which can in turn be overridden with the GIT_NOTES_REF environment variable.
If the given ref does not exist, it is not an error, but it means that no notes should be printed. These variables decide both which type of notes are displayed with the commit after the Notes: line and where to write the note created with git notes add.
You can see that the new type of has reference appeared in the repository:
$ git show-ref --abbrev commitsfcac4a6 refs/notes/commitsIf you examine the new reference, you will see that each note is stored in a file named after the SHA-1 identifier of the annotated object. This means that you can have only one note of the given type for one object. You can always edit the note, append to it (with git notes append), or replace its content (with git notes add --force).
In interactive mode, Git opens the editor with the contents of the note, so edit, append, and replace operations work almost the same interactively. As opposed to commits, notes are mutable, or to be more exact, only the latest version of each note is used:
$ git show refs/notes/commitscommit fcac4a649d2458ba8417a6bbb845da4000bbfa10Author: Alice Developer <[email protected]>Date: Tue Jun 16 19:48:37 2015 +0200 Notes added by 'git notes add'diff --git a/8c4ceca59d7402fb24a672c624b7ad816cf04e08 b/8c4ceca59d7402fb24a672c624b7ad816cf04e08new file mode 100644index 0000000..a033550--- /dev/null+++ b/8c4ceca59d7402fb24a672c624b7ad816cf04e08@@ -0,0 +1 @@+atoi() invokes undefined behaviour upon error$ git log -1 --oneline \ 8c4ceca59d7402fb24a672c624b7ad816cf04e088c4ceca Use strtol(), atoi() is deprecatedNotes for commits are stored in a separate line of (meta) history, but this need not be the case for the other categories of notes. The notes reference can point directly to the tree object instead of the commit object such as for refs/notes/commits.
One important issue that is often overlooked in books and articles is that it is the full path to a file with the note’s contents, not the base name of the file, that identifies the object that the note is attached to. If there are many notes, Git can and will use a fan-out directory hierarchy, for example, storing the preceding note at the 8c/4c/eca59d7402fb24a672c624b7ad816cf04e08 path (note the slashes).
Other categories and uses of notes
Section titled “Other categories and uses of notes”Notes are usually added to commits. However, even for those notes that are attached to commits, it makes sense, at least in some cases, to store different pieces of information using different categories of notes. This makes it possible to decide which parts of information to display on an individual basis, and which parts to push to the public repository. It also allows us to query for specific parts of information individually.
To create a note in a namespace (category) that is different from the default one (where the default means notes/commits, or the value of the configuration variable core.notesRef if it is set), you need to specify the category of notes while adding it:
$ git notes --ref=issues add -m '#2' v0.2~3Now, by default, Git will only display the core.notesRef category of notes after the commit message. To include other types of notes, you must either select the category to display with git log --notes=<category> (where <category> is either the unqualified or qualified reference name, or a glob; you can therefore use --notes=* to show all categories) or configure which notes to display in addition to the default with the display.notesRef configuration variable (or the GIT_NOTES_DISPLAY_REF environment variable). You can either specify the configuration variable value multiple times, just like for remote.<remote-name>.push (or specify a colon-separated list of pathnames if you are using the environment variable), or you can specify a globing pattern:
$ git config notes.displayRef 'refs/notes/*'$ git log -1 v0.2~3commit 8c4ceca59d7402fb24a672c624b7ad816cf04e08Author: Bob Hacker <[email protected]>Date: Sun Jun 1 01:46:19 2014 +0200 Use strtol(), atoi() is deprecatedNotes: atoi() invokes undefined behaviour upon errorNotes (issues): #2There are many possible uses of notes. You can, for example, use notes to reliably mark which patches (which commits) were upstreamed (forward-ported to the development branch) or downstreamed (back-ported to the more stable branch or the stable repository), even if the upstreamed or downstreamed version is not identical, and mark a patch as being deferred if it is not ready for either upstream or downstream.
If you require manual input, this is a bit more reliable than relying on the git patch-id mechanism to detect when the changeset is already present (which you can do by rebasing, by using git cherry-pick, or with the --cherry, --cherry-pick, or --cherry-mark option of git log). This is, of course, in case we are not using topic branches from the start, but rather cherry-picking commits.
Notes can also be used to store the results of the post-commit (but pre-merge) code audit and to notify other developers of the reason(s) why this version of the patch was used.
Notes can also be used to handle marking bugs and bug fixes, as well as verifying fixes. You will often find bugs in commits long after they get published; that is why you need notes for this purpose. If you find a bug before publishing, you would rewrite the buggy commit instead.
In this case, when the bug gets reported, and if it was a regression, you would first find which revision introduced the bug (for example, with git bisect, as described in Chapter 4, Exploring Project History). Then you would want to mark this commit, putting the identifier of a bug entry in the issue tracker for the project (which is usually a number, or number preceded by some specific prefix such as Bug:1385) in the bugs, defects, or issues category of notes. Perhaps you would also want to include the description of a bug. If the bug affects security, it might be assigned a vulnerability identifier, for example, a Common Vulnerabilities and Exposures (CVE) number; this information could be put into the note in the CVE-IDs category.
Then, after some time, the bug will hopefully get fixed. Just like we marked the commit with the information that it contains the bug, we can additionally annotate it with the information on which commit fixes it, such as in a note in the fixes category. Unfortunately, it might happen that the first attempt at fixing it doesn’t handle the bug entirely correctly and you have to amend a fix, or perhaps even create a fix for a fix. If you are using bugfix or hotfix branches (topic branches for bugfixes), as described in Chapter 8, Advanced Branching Techniques, it will be easy to find and apply them together by merging the aforementioned bugfix branch. If you are not using this workflow, then it would be a good idea to use notes to annotate fixes that should be cherry-picked together with a supplementary commit, for example by adding a note in the alsoCherryPick or seeAlso category, or whatever you want to name this category of notes. Perhaps the original submitter, or a Q&A group, would also get to the fix and test that it works correctly. It would be better if the commit was tested before publishing, but it is not always possible, so refs/notes/tests it is.
Third-party tools use (or could use) notes to store additional per-commit tool-specific information. For example, Gerrit, which is a free web-based team code collaboration tool, stores information about code reviews in refs/notes/reviews. This includes the name and email address of the Gerrit user that submitted the change, the time the commit was submitted, the URL to the change review in the Gerrit instance, review labels and scores (including the identity of the reviewer), the name of project and branch, and so on:
Notes (review): Code-Review+2: John Reviewer <[email protected]> Verified+1: Jenkins Submitted-by: Bob Developer <[email protected]> Submitted-at: Thu, 20 Oct 2014 20:11:16 +0100 Reviewed-on: http://localhost:9080/7 Project: common/random Branch: refs/heads/masterNotes as cache
Section titled “Notes as cache”Going to a more exotic example, you can use the notes mechanism to store the result of a build (either the archive, the installation package, or just the executable), attaching it to a commit or a tag. Theoretically, you could store a build result in a tag, but you would usually expect a tag to contain a Pretty Good Privacy (PGP) signature and perhaps also the release highlights. Also, you would, in almost all cases, want to fetch all the tags, while not everyone wants to pay for the cost of disk space for the convenience of pre-build executables. You can select whether you want to fetch the given category of notes (for example to skip pre-built binaries) or not from case to case while you autofollow tags. That is why notes are better than tags for this purpose.
Here, the trouble is to correctly generate a binary note. You can binary-safely create a note with the following trick:
# store binary note as a blob object in the repository$ blob_sha=$(git hash-object -w ./a.out)# take the given blob object as the note message$ git notes --ref=built add --allow-empty –C "$blob_sha" HEADYou cannot simply use -F ./a.out, as this is not binary-safe – comments (or rather what was misdetected as comments, that is, lines starting with #) would be stripped.
The notes mechanism is also used as a mechanism to enable storing cache for the textconv filter (see the section on gitattributes in Chapter 3, Managing Your Worktrees). All you need to do is configure the filter in question, setting its cachetextconv to true:
[diff "jpeg"] textconv = exif cachetextconv = trueHere, notes in the refs/notes/textconv/jpeg namespace (named after the filter) are used to attach the text of the conversion to a blob.
Notes and rewriting history
Section titled “Notes and rewriting history”Notes are attached to objects they annotate (usually commits) by their SHA-1 identifier. What happens with notes when we are rewriting history then? In the new, rewritten history, SHA-1 identifiers of objects are different in most cases.
It turns out that you can configure this quite extensively. First, you can select which categories of notes should be copied along with the annotated object during the rewrite with the notes.rewriteRef multi-value configuration variable. This setting can be overridden with the GIT_NOTES_REWRITE_REF environment variable with a colon-separated list of fully qualified notes references and globs (denoting reference patterns to match). There is no default value for this setting; you must configure this variable to enable rewriting.
Second, you can also configure whether to copy a note during rewriting depending on the exact type of the command doing the rewriting (rebase and amend are currently supported as the value of the command). This can be done with the boolean-valued notes.rewrite.<command> configuration variable.
In addition, you can decide what to do if the target commit already has a note while copying notes during a rewrite, for example, while squashing commits using an interactive rebase. You have to decide between overwrite (taking the note from the appended commit), concatenate (which is the default value), cat_sort_uniq (like concatenate, but sorting lines and removing duplicates), and ignore (using the note from the original commit being appended to) for the notes.rewriteMode configuration variable or the GIT_NOTES_REWRITE_MODE environment variable.
Publishing and retrieving notes
Section titled “Publishing and retrieving notes”So, we have notes in our own local repository. What do we do if we want to share these notes? How do we make them public? How can we, and other developers, get notes from other public repositories?
We can employ our knowledge of Git here. The How notes are stored section explained that notes are stored in the object database of the repository using special references in the refs/notes/ namespace. The contents of the note is stored as a blob, referenced through this special ref. Commit notes (notes in refs/notes/commits) store the history of notes, though Git allows you to store notes without history as well. So, what you need to do is get this special ref. The contents of the notes will follow. This is the usual mechanism of repository synchronization (object transfer).
This means that to publish your notes, you need to configure appropriate push lines in the appropriate remote repository configuration (see Chapter 6, Collaborative Development with Git). Assuming that you are using a separate public remote (if you are the maintainer, you will probably simply use origin), which is perhaps set as remote.pushDefault, and that you would like to publish notes in any category, you can run the following:
$ git config --add remote.public.push '+refs/notes/*:refs/notes/*'If push.default is set to matching (or Git is old enough to have this as the default behavior), or the push lines use special refspecs such as : or +:, it is enough to push notes refs the first time, as they would be pushed automatically each time after:
$ git push origin 'refs/notes/*'The process of fetching notes is only slightly more involved. If you don’t produce specified types of notes yourself, you can fetch notes in the “mirror-like” mode to the ref with the same name:
$ git config --add remote.origin.fetch '+refs/notes/*:refs/notes/*'However, if there is a possibility of conflict, you would need to fetch notes from the remote into the remote-tracking notes reference, and then use git notes merge to join them into your notes. Please see the documentation for details.
Tip
If you want to make it easy to merge Git notes, perhaps even automatically, then following the convention of the Key: Value entries on separate lines for the content of notes, with duplicates removed, will help.
There is no standard naming convention for remote-tracking notes references, but you can use either refs/notes/origin/* (so that the shortened commits notes category from the origin remote is origin/commits, and so on), or go whole works and fetch refs/* from the origin remote into refs/remotes/origin/refs/* (so that the commits category lands in refs/remotes/origin/refs/notes/commits).
Using git replace
Section titled “Using git replace”The original idea for the replace- or replacement-like mechanism was to make it possible to join the history of two different repositories.
The original impulse was to be able to switch from the other version control system to Git by creating two repositories: the first one for the current work, starting with the most recent version in the empty repository, and the second one for the historical data, storing the conversion from the original system. That way, it would be possible to take time doing the faithful conversion of the historical data, and even fix it if the conversion were incorrect, without affecting the current work.
What was needed was some mechanism to connect the histories of those two repositories, to have a full history for inspection going back to the creation of a project (for example, for blame, that is, line-history annotation).
The replacements mechanism
Section titled “The replacements mechanism”The modern incarnation of such a tool is a replace (or replacements) mechanism. With it, you can replace any object with any object, or rather create a virtual history (virtual object database of a repository) by creating an overlay, so that most Git commands return a replacement in place of the original object.
However, the original object is still there, and Git’s behavior with respect to the replacement mechanism was done in such a way as to eliminate the possibility of losing data. You can get the original view with the --no-replace-objects option passed to the git wrapper, added before the command. You can also use the GIT_NO_REPLACE_OBJECTS environment variable, instead. For example, to view the original history, you can use git -- no-replace-objects log.
The information about replacements is saved in the repository by storing the ref named after the SHA-1 of the replaced object in the refs/replace/ namespace, with the SHA-1 of replacement as its sole content. However, there is no need to edit it by hand or with low-level plumbing commands – you can use the git replace command.
Almost all the commands use replacements unless they are told not to, as explained previously. The exception is reachability analysis commands. This means that Git would not remove the replaced objects because they are no longer reachable if we take replacement into account. Of course, replacement objects are reachable from the replace refs.
Important note
Currently, some of the mechanisms that are used to make Git faster for very large repositories (see Chapter 12, Managing Large Repositories) don’t work if git replace is used.
You can replace any object with any other object, though changing the type of an object requires telling Git that you know what you are doing with git replace -f <object> <replacement>. This is because such a change might lead to troubles with Git, since it was expecting one type of object, and getting another.
With git replace --edit <object>, you can edit its contents interactively. What really happens is that Git opens the editor with the object contents, and after editing, Git creates a new object and a replacement ref. The object format (in particular, the commit object format, as one would almost always edit commits) was described at the beginning of this chapter. You can change the commit message, commit parents and authorship, and so on.
Example – joining histories with git replace
Section titled “Example – joining histories with git replace”Let’s assume that you have split the repository into two, as described in an earlier section about filter-repo, perhaps for performance reasons. However, let’s say that you want to be able to treat the joined history as if it were one.
Or perhaps there was a natural history split after changing the version control system to Git, with the fresh repository with the current work (started after switching from the current state of a project, with an empty history) and the converted historical repository kept separate. This could be done to make the switch faster. This technique has the advantage of allowing you to improve the conversion after the split.
This situation is shown in Figure 10*.12*, with the historical repository added as a remote to the current work repository (one with new commits).

Figure 10.12 – The view of a split history, with the replacements turned off (git —no-replace-objects). The shortened SHA-1 in the left upper corner of a commit denotes its identifier.
In many cases, you might want to create a kind of informational commit on top of the “historical” repository (the one with the older part of the history), for example, adding the notification where one can find the current work repository to the README file. Such a commit is, for simplicity, not shown in Figure 10*.12*.
How to join history depends somewhat on whether the history was originally split or joined. If it was originally joined, then split, just tell Git to replace the post-split version with the pre-split version using git replace <post-split> <pre-split>. If the repository was split from beginning, use the --edit or --graft option of git replace.

Figure 10.13 – The view of a split history, joined using replacements
The split history is there, it is just hidden from view. For all Git commands, the history looks like in Figure 10*.13*. You can, as described earlier, turn it off using replacements; in this case, you would see the history as in Figure 10*.12*.
Historical note – grafts
Section titled “Historical note – grafts”The first attempt to create a mechanism to make it possible to join lines of history came about in the form of grafts. It is a simple .git/info/grafts file with the SHA-1 identifier of the affected commit and its replacement parents in line, separated by spaces.
This mechanism was only for commits, and allowed only to change the parentage of the commit. There was no support for transport, that is, for propagating this information from inside of Git. You could not turn the grafts mechanism off temporarily, at least not easily. Moreover, it was inherently unsafe because there were no exceptions for reachability-checking commands, making it possible for Git to remove needed objects by accident during pruning (garbage collecting).
However, you can find its use in examples. Nowadays, it is obsolete, especially with the existence of the git replace --graft option. If you use grafts, consider replacing them with replacements objects; the contrib/convert-grafts-to-replace-refs.sh script can help with this in the Git sources.
Other graft-like files in Git
The shallow clone (the result of git clone --depth=<N>, a clone with the shortened history) is managed with a graft-like .git/shallow file. This file is managed by Git, however, not by the user.
Publishing and retrieving replacements
Section titled “Publishing and retrieving replacements”How can you publish replacements, and how do you get them from the remote repository? Since replacements use references, this is quite simple.
Each replacement is a separate reference in the refs/replaces/ namespace. Therefore, you can get all the replacements with the globing fetch or push line:
+refs/replace/*:refs/replace/*There can be only one replacement for an object, so there are no problems with merging replacements. You can only choose between one replacement or the other.
Theoretically, you could also request individual replacements by fetching (and pushing) individual replacement references instead of using the ’*’ wildcard.
Summary
Section titled “Summary”This chapter, along with Chapter 8, Advanced Branching Techniques, provided all the tools required to manage a clean, readable, and easy-to-review history of a project.
You learned how to make history cleaner by rewriting it in this chapter. You also learned what rewriting history means in Git, when and why to avoid it, and how to recover from an untimely upstream rewrite. You have learned to use an interactive rebase to delete, reorder, squash and split commits, and how to test each commit during the rebase. You know how to do a large-scale scripted rewrite with filter-repo, as well as how to edit commits and commit metadata and how to permanently change history, such as by splitting it in two. You also got to know some third-party external tools, which can help with these tasks.
You learned what to do if you cannot rewrite history: how to fix mistakes by creating commits with appropriate changes (for example, with git revert), how to add extra information to the existing commits with notes, and how to change the virtual view of the history with replacements. You learned to handle reverting a faulty merge and how to re-merge after a reverted merge. You learned how to fetch and publish both notes and replacements.
To really understand advanced history rewriting and the mechanism behind notes and replacements, this chapter explained the basics of Git internals and low-level commands that are usable for scripting (including scripted rewrite).
The following chapter, Chapter 11, Managing Subprojects, will explain and show different ways to connect different subprojects in one repository, from submodules to subtrees.
In the subsequent chapter, Chapter 12, Managing Large Repositories, you will also learn techniques to manage (or mitigate managing) large-size assets inside a repository, or large numbers of files in a repository. Splitting a large project into submodules is one, but not the only, way to handle this issue.
Questions
Section titled “Questions”Answer the following questions to test your knowledge of this chapter:
- When working on a series of commits to implement a feature, how can you mark a bugfix commit for later squashing into the original commit before publishing the series?
- Why should you not rewrite (rebase or amend) published history if you are using merging to integrate changes?
- How can you recover from the upstream rebase?
- What can you do when you notice that you accidentally included some large file that should not be put in version control in a commit?
- How can you undo the effect of the commit if you cannot rewrite history?
- What mechanisms exist to amend history, or a view of history, without rewriting it?
Answers
Section titled “Answers”Here are the answers to the questions given above:
- You can use
git commit --fixupwhen creating a bugfix, and then latergit rebase --interactive --autosquashbefore publishing the series. - You should not rewrite published history because other developers can do their work based on the version before the changes, and then merging would bring older versions (from before the rewrite) back into existence.
- Rebase your own changes on top of the new, rebased version of the upstream.
- If the problem is in the most recent commit, you can amend it with
git commit --amend. If you need to rewrite the whole history of the project, you can use thegit filter-repotool. Note, however, the caveat that comes with rewriting published history, namely that it can cause problems for other developers when they will try to integrate their changes. - You can use
git revertto create the commit that undoes changes brought by an unwanted commit. - You can use
git notesto add extra information to commit objects after the fact, and you can usegit replaceto change the effective shape of the history.
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 and Ben Straub: Pro Git, 2nd Edition (2014) https://git-scm.com/book/en/v2.
- Chapter 7.6, Git Tools - Rewriting History
- Chapter 7.13, Git Tools - Replace
- Chapter 7.6, Git Tools - Rewriting History
- Aske Olsson and Rasmus Voss: Git Version Control Cookbook (2014)
- Chapter 5, Storing Additional Information in Your Repository
- Chapter 8, Recovering From Mistakes
- Chapter 5, Storing Additional Information in Your Repository
- Git Documentation HOWTOs
- How to revert a faulty merge https://github.com/git/git/blob/master/Documentation/howto/revert-a-faulty-merge.txt
- How to revert an existing commit https://github.com/git/git/blob/master/Documentation/howto/revert-branch-rebase.txt
- How to revert a faulty merge https://github.com/git/git/blob/master/Documentation/howto/revert-a-faulty-merge.txt
- Tyler Cipriani: Git Notes: Git’s Coolest, Most Unloved Feature (2022) https://tylercipriani.com/blog/2022/11/19/git-notes-gits-coolest-most-unloved-feature/
- Elijah Newren: git filter-repo https://github.com/newren/git-filter-repo
- Stacked Git: StGit Tutorial https://stacked-git.github.io/guides/tutorial/
- Jackson Gabbard: Stacked Diffs Versus Pull Requests (2018) https://jg.gg/2018/09/29/stacked-diffs-versus-pull-requests/