Merging Changes Together
local graph
Chapter 9 — Merging Changes Together
Section titled “Chapter 9 — Merging Changes Together”The previous chapter, Advanced Branching Techniques, described how to use branches effectively for collaboration and development.
This chapter will teach you how to integrate changes from different parallel lines of development together (that is, branches) by creating a merge commit, or by reapplying changes with the rebase operation. Here, the concepts of merge and rebase are explained, including the differences between them and how they can be used. This chapter will also explain the different types of merge conflicts and teach you how to avoid them, examine them, and resolve them.
In this chapter, we will cover the following topics:
- Merging, merge strategies, and merge drivers
- Cherry-picking and reverting a commit
- Applying a patch and a patch series
- Rebasing a branch and replaying its commits
- A merge algorithm at file and contents level
- Three stages in the index
- Merge conflicts – how to examine and resolve them
- Reusing recorded
[conflict]resolutions withgit rerere - An external tool –
git-imerge
Methods of combining changes
Section titled “Methods of combining changes”Now that you have changes from other people in the remote-tracking branches (or in the series of emails), you need to combine them, perhaps also with your changes.
Alternatively, your work on a new feature, created and performed on a separate topic branch, is now ready to be included in the long-lived development branch and made available to other people. Maybe you have created a bug fix and want to include it in all the long-lived graduation branches. In short, you want to join two divergent lines of development by integrating their changes.
Git provides a few different methods to combine changes and variations of these methods. One of these methods is a merge operation, joining two lines of development with a two-parent commit. Another way to copy introduced work from one branch to another is via cherry-picking, which is creating a new commit with the same changeset on another line of development (this is sometimes necessary to use). Alternatively, you can reapply changes, transplanting one branch on top of another with rebase. We will now examine all these methods and their variants, see how they work, and when they can be used.
In many cases, Git will be able to combine changes automatically; the next section will talk about what you can do if it fails and if there are merge conflicts.
Merging branches
Section titled “Merging branches”The merge operation joins two (or more) separate branches together, including all the changes since the point of divergence into the current branch. You do this with the git merge command:
$ git switch master$ git merge bugfix123Here, we first switched to a branch we want to merge into (in this example, master) and then provided the branch to be merged (here, bugfix123).
No divergence – fast-forward and up-to-date cases
Section titled “No divergence – fast-forward and up-to-date cases”Let’s say that you need to create a fix for a bug somebody found. Let’s assume that you have followed the recommendations of the topic branch workflow from Chapter 8, Advanced Branching Techniques, and created a separate bugfix branch, named i18n.
In such cases, there is often no real divergence, which means that there were no commits on the maintenance branch (the branch we are merging into), since a bugfix branch was created. Because of this, Git would, by default, simply move the branch pointer of the current branch forward:
$ git switch maintSwitched to branch 'maint'$ git merge i18nUpdating f41c546..3a0b90cFast-forward src/random.c | 2 ++ 1 file changed, 2 insertions(+)You have probably seen this Fast-forward phrase among output messages during git pull, when there are no changes on the branch you pull into. The fast-forward merge situation is shown in Figure 9*.1*.

Figure 9.1 – The master branch is fast-forwarded to i18n during the merge
This case is important for the centralized and the peer-to-peer workflows (described in Chapter 6, Collaborative Development with Git), as it is the fast-forward merge that allows you to ultimately push your changes forward.
In some cases, that is not what you want. For example, note that after the fast-forward merge in Figure 9*.1*, we have lost the information that the C4 and C5 commits were done on the i18n topic branch. We can force the creation of a merge commit (which is described in the next section), even in a case where there are no changes to the current branch, using the git merge --no-ff command. The default is --ff; to fail instead of creating a merge commit, you can use --ff-only (ensuring fast-forward only).

Figure 9.2 – The master branch is up to date with respect to the i18n branch (i.e., it includes it)
There is another situation where the head (tip) of one branch is the ancestor of the other – namely, the up-to-date scenario where the branch we try to merge is already included (merged) in the current branch (Figure 9*.2*). Git doesn’t need to do anything in this case; it just informs the user about it:
$ git merge i18nAlready up to date.Creating a merge commit
Section titled “Creating a merge commit”When you are merging fully fledged feature branches, rather than merging bugfix branches as in the previous section, the situation is usually different from the previously described fast-forward case. In the case of feature branch workflow, the development of the feature branch and integration branch would usually have diverged.
Suppose that you have decided that your work on a feature (for example, work on adding support for internationalization on the i18n topic branch) is complete and ready to be included in the master stable branch. In order to do so with a merge operation, you need to first check out the branch you want to merge into and then run the git merge command, with the branch being merged as a parameter:
$ git checkout masterSwitched to branch 'master'$ git merge i18nMerge made by the 'ort' strategy. src/random.c |2 ++ 1 file changed, 2 insertions(+)Because the top commit on the branch you are on (and merging into) is not a direct ancestor or a direct descendant of the branch you merge in, Git has to do more work than just moving the branch pointer. In this case, Git does a merge of changes since the divergence and stores it as a merge commit on the current branch. This commit has two parents, denoting that it was created based on more than one commit (more than one branch); the first parent is the previous tip of the current branch, and the second parent is the tip of the branch you merge in.
Note that Git does start committing the result of merge if it can be done automatically, and if there are no conflicts. However, the fact that the merge succeeded at the text level doesn’t necessarily mean that the merge result is correct. You can either ask Git to not automatically commit a merge with git merge --no-commit to examine it first, or you can examine the merge commit and then use the git commit --amend command if it is incorrect (see Figure 2*.4*).

Figure 9.3 – Three revisions used in a typical merge and the resulting merge commit
Git creates contents of a merge commit (M in Figure 9*.3*), using by default (and in most cases) the three-way merge, which in turn uses the snapshots pointed to the tips of the branches being merged (master, C6, and i18n, C5) and the common ancestor of the two (C3 here, which you can find with the git merge-base command).
A very important issue is that Git creates the merge commit contents based usually only on the three revisions – merged into (ours), merged in (theirs), and the common ancestor (merge base). It does not examine what happened on the divergent parts of the branches; this is what makes merging fast. However, because of this, Git also does not know about the cherry-picked or reverted changes on the branches being merged, which might lead to surprising results (see, for example, the section about reverting merges in Chapter 10, Keeping History Clean).
Merge strategies and their options
Section titled “Merge strategies and their options”In the merge message, we have seen that it was made by the ‘ort’ strategy (known as recursive in older Git). The merge strategy is an algorithm that Git uses to compose the result of joining two or more lines of development.
There are a few merge strategies that you can select to use with the --strategy / -s option to the git merge command. By default, Git uses the ort merge strategy when joining two branches and a very simple octopus merge strategy when joining more than two branches. You can also choose the resolve merge strategy if the default one fails; it is fast and safe, although less capable of merging.
The two remaining merge strategies are special-purpose algorithms. The ours merge strategy can be used when we want to abandon changes in the merged-in branch but keep them in the history of the merged-into branch – for example, for documentation purposes. This strategy simply repeats the current snapshot (the ours version) as a merge commit. Note that this merge strategy, invoked with --strategy=ours or -s ours, should be not confused with the ours option to the default ort merge strategy, --strategy=ort --strategy-option=ours, or just -Xours, which means something different.
The subtree merge strategy can be used for subsequent merges from an independent project into a subdirectory (subtree) in a main project. It automatically figures out where the subproject was put. This topic, and the concept of subtrees, will be described in more detail in Chapter 11, Managing Subprojects.
The default ort (Ostensibly Recursive’s Twin) merge strategy, and its predecessor, the recursive merge strategy, are named after how such a strategy deals with multiple merge bases and criss-cross merges. In the case of more than one merge base (which means that there is more than one common ancestor that can be used for a three-way merge), such a strategy creates a merge tree (conflicts and all) from the ancestors as a merge base – that is, it merges recursively. Of course, again, these common ancestors being merged can have more than one merge base.
Some strategies are customizable and have their own options. You can pass an option to a merge algorithm with -X<option> (or --strategy-option=<option>) on the command line, or set it with the appropriate configuration variables. You will discover more about merge options in the section Resolving merge conflicts, when we will discuss solving merge conflicts.
A reminder – merge drivers
Section titled “A reminder – merge drivers”Chapter 3*, Managing Your* Worktrees, introduced git attributes – among others, merge drivers. These drivers are user-defined and deal with merging file contents if there is a conflict, replacing the default three-way file-level merge. Merge strategies, in contrast, deal with DAG-level merging (and tree-level – that is, merging directories), and you can only choose from the built-in options.
A reminder – signing merges and merging tags
Section titled “A reminder – signing merges and merging tags”In Chapter 6, Collaborative Development with Git, you learned about signing your work. While using merge to join two lines of development, you can either merge a signed tag, sign a merge commit, or both. Signing a merge commit is done with the -S / --gpg-sign option to use the git merge or git commit command; the latter is used if there are conflicts, or if the --no-commit option was used while merging.
Copying and applying a changeset
Section titled “Copying and applying a changeset”The merging operation is about joining two lines of development (two branches), including all the changes since their divergence. This means, as described in Chapter 8, Advanced Branching Techniques, that if there is one commit on the less stable branch (for example, master) that you want to have also in a more stable branch (for example, maint), you cannot use the merge operation. You need to create a copy of such a commit. A situation such as this should be avoided (using topic branches), but it can happen, and handling it is sometimes necessary.
Sometimes, the changes that need to be applied come not from the repository (as a revision in the DAG to be copied) but in the form of a patch – that is, a unified diff or an email generated with git format-patch (with a patch, plus a commit message).
Git includes the git am tool to handle the mass application of commit-containing patches.
Both of these commands are useful on their own, but understanding these methods of getting changes is also useful to understand how cherry-picking and rebasing work.
Cherry-pick – creating a copy of a changeset
Section titled “Cherry-pick – creating a copy of a changeset”You can create a copy of a commit (or a series of commits) with the cherry-pick command. Given a series of commits (usually just a single commit), it applies the changes each one introduces, recording a new commit for each change.

Figure 9.4 – Cherry-picking the C4 commit from master to maint
An example of a cherry-pick operation is shown in Figure 9*.4*. (Note that here the thick dotted arrow from C4 to C4’ denotes a copy; it is not a reference.)
The copying of changes does not mean that the snapshot (that is, the state of a project) is the same in the original (C4 in Figure 9*.4*) and in the copy (C4’ in Figure 9*.4*); the latter will include other changes while missing others. Also, while the changes will usually be the same (as they are in Figure 9*.4*, where the difference between C3 and C4 and the diff between C7 and C4’ is the same), they can also be different – for example, if part of the changes was already present in the earlier commits.
Note that, by default, Git does not save information about where the cherry-picked commit came from. You can append this information to an original commit message, as a (cherry-picked from the commit <sha-1>) line with git cherry-pick -x <commit>. This is only done for cherry-picks without conflicts. Remember that this information is only useful if you have access to the copied commit. Do not use it if you are copying commits from the private branch, as other developers won’t be able to make use of that information.
Revert – undoing the effect of a commit
Section titled “Revert – undoing the effect of a commit”Sometimes, it will turn out that, even with a code review, there will be some bad commits that you need to reverse (perhaps one turned out to be a not-so-good idea, or it contains bugs). If the commit is already made public, you cannot simply remove it; you need to undo its effects. This issue will be explained in detail in Chapter 10, Keeping History Clean.
This “undoing of a commit” can be done by creating a commit with a reversal of changes, something like cherry-picking but applying the reversal of changes. This is done with the revert command (see Figure 9*.5*).

Figure 9.5 – The effect of using ‘git revert master^’ on a ‘master’ branch – creating a new commit, denoted!C3, that undoes changes in the C3 commit
The name of this operation might be misleading. If you want to revert all the changes made to the whole working area, you can use git reset (in particular, with the --hard option). If you want to revert changes made to a single file, use git checkout <file> or git restore <file>. Both of these are explained in detail in Chapter 3, Managing Your Worktrees. The git revert command records a new commit to reverse the effect of the earlier commit (often, a faulty one).
Applying a series of commits from patches
Section titled “Applying a series of commits from patches”Some collaborative workflows include exchanging the changes as patches via email (or another communication medium). This workflow is often encountered in open source projects; it is often easier for a new or a sporadic contributor to create a specially crafted email (for example, with git format-patch) and send it to a maintainer or a mailing list, rather than setting up a public repository and sending a pull request.
You can apply a series of patches from a mailbox (in the mbox or maildir format; the latter is just a series of files) with the git am command. If these emails (or files) were created from the git format-patch output, you can use git am --3way to use the three-way file merge if there are conflicts. Resolving conflicts will be discussed in in the section, Resolving merge conflicts.
You can find both tools to help use the patch submission process by sending a series of patches – for example, from the pull request on GitHub (e.g., the GitGitGadget GitHub app, or the older submitGit web app, to submit patches from GitHub’s pull request to the Git project mailing list) – and tools that track web page patches sent to a mailing list (for example, the patchwork tool).
Cherry-picking and reverting a merge
Section titled “Cherry-picking and reverting a merge”This is all good, but what happens if you want to cherry-pick or revert a merge commit? Such commits have more than one parent; thus, they have more than one change associated with them.
In this case, you have to tell Git which change you want to pick up (in the case of cherry-pick), or back out (in the case of revert) with the -m <parent number> option – for example, -m1.
Note that reverting a merge undoes the changes, but it does not remove the merge from the history of the project. See the section on reverting merges in Chapter 10, Keeping History Clean.
Rebasing a branch
Section titled “Rebasing a branch”Besides merging, Git supports an additional way to integrate changes from one branch into another – namely, the rebase operation.
Like a merge, it deals with the changes since the point of divergence (at least, by default). However, while a merge creates a new commit by joining two branches, rebase takes the new commits from one branch (i.e., takes the commits since the divergence) and reapplies them on top of the other branch – see Figure 9*.6* for an example.

Figure 9.6 – The effects of the rebase operation
With merge, you first switch to the branch to be merged and then use the merge command to select a branch to merge in. With rebase, it is a bit different. First, you select a branch to rebase (i.e., the changes to reapply) and then use the rebase command to select where to put it. In both cases, you first check out the branch to be modified, where a new commit or commits would be (a merge commit in the case of merging, and a replay of commits in the case of rebasing):
$ git switch i18nSwitched to branch 'i18n'$ git rebase masterSuccessfully rebased and updated refs/heads/master.Alternatively, you can use git rebase master i18n as a shortcut. In this form, you can easily see that the rebase operation takes the master..i18n range of revisions (this notation is explained in Chapter 4, Exploring Project History), replays it on top of master, and finally, points i18n to the replayed commits.
Note that old versions of commits don’t vanish, at least not immediately. They will be accessible via a reflog (and ORIG_HEAD) for a grace period. This means that it is not that hard to check how replaying changed the snapshots of a project and, with a bit more effort, how changesets themselves have changed.
Merge versus rebase
Section titled “Merge versus rebase”We have these two ways of integrating changes – merge and rebase. How do they differ, and what are their advantages and disadvantages? We can see by comparing Figure 9*.2* in the Creating a merge commit section with Figure 9*.5* in the Rebasing a branch section.
First, merge doesn’t change history (see Chapter 10, Keeping History Clean). It creates and adds a new commit (unless it is a fast-forward merge; then, it just advances the branch head), but the commits that were reachable from the branch remain reachable. This is not the case with rebase. Commits get rewritten, old versions are forgotten, and the DAG of revisions changes. What was once reachable might no longer be reachable. This means that you should not rebase published branches.
Secondly, merge is a one-step operation, with one place to resolve merge conflicts. The rebase operation is multi-step; the steps are smaller (if you follow the recommended practices and keep changes small – see Chapter 15, Git Best Practices), but there are more of them.
Linked to this is the fact that the merge result is based (usually) on three commits only, and that it does not take into account what happens on either of the branches that are integrated step by step; only the endpoints matter. Conversely, rebase reapplies each commit individually, so the road to the final result matters here.
Third, the history looks different; you get a simple linear history with rebase, while using the merge operation leads to a complex history, with the lines of development forking and joining. The history is simpler for rebase, but you lose the information that the changes were developed on a separate branch and that they were grouped together, which you get with merge (at least with --no-ff). There is even the git-resurrect script in the Git contrib tools that uses the information stored in the commit messages of the merge commits to resurrect the old, long-deleted feature branches.
The last difference is that, because of the underlying mechanism, rebase does not, by default, preserve merge commits while reapplying them. You need to explicitly use the --rebase-merges option. The merge operation does not change the history, so merge commits are left as they are.
Rebase backends
Section titled “Rebase backends”The previous section described two mechanisms to copy or apply changes – the git cherry-pick command and the pipeline from git format-patch to git am --3way. Either of them can be used by git rebase to reapply commits.
The default is to use the merge-based workflow, as if git rebase was called with the --merge option. The default 'ort' merge strategy allows rebase to be aware of the renames on the upstream side (where we put the replayed commits). With this option, you can also select a specific merge strategy and pass options to it.
To switch to a patch-based strategy, use git rebase --apply. In this case, you can pass some options to git am that does the actual replaying of changesets.
These options will be described later when we discuss conflicts.
There is also an interactive rebase with its own set of options. This is one of the main tools in Chapter 10, Keeping History Clean. It can be used to execute tests after each replayed commit to check that the replay is correct.
Advanced rebasing techniques
Section titled “Advanced rebasing techniques”You can also have your rebase operation replay on something other than the target branch of the rebase with -- onto <newbase>.
Let’s assume that your featureA topic branch is based on the unstable development branch named next, as it is dependent on some feature that is not yet ready and not yet present in the stable branch (master). If the functionality on which featureA depends is deemed stable and merged into master, you would want to move this branch from being forked from next to being forked from master. Alternatively, perhaps you started the server branch from the related client branch, but you want to make it more obvious that they are independent.
You can do this with git rebase --onto master next featureA in the first case, and git rebase --onto master server client in the second one (which is shown in Figure 9*.7*).

Figure 9.7 – The rebasing branch, moving it from one branch to another
Alternatively, perhaps you want to rebase only a part of the branch. You can do this with git rebase --interactive, but you can also use git rebase --onto <new base> <starting point> <branch>. You can even choose to rebase the whole branch (usually, an orphan branch) with the --root option. In this case, you would replay the whole branch and not just a selected subset of it.
You can also keep the base commit as is with --keep-base, instead of following the upstream. With the --fork-point option, you can make Git find a better common ancestor using reflog (to find where the branch was created) if it is possible.
Squash merge
Section titled “Squash merge”If the changes made on a branch are not worth preserving in detail and only their result is, you can use squash merge as a way to integrate them as a single commit. This can happen if the branch you want to integrate is full of temporary, work-in-progress commits.
With git merge --squash, Git will produce the same result with respect to the working tree (and to the staging area) as if a real merge happened, but it will not perform the commit (the --commit option to git merge is incompatible with --squash). This is done in such a way that the next git commit will create an ordinary commit, not a merge commit. See Figure 9*.8* for a comparison of the merge types.

Figure 9.8 – An ordinary merge versus a squash merge for the same set of branches
By default, the commit message of a squashing commit begins with Squashed commit of the following:, followed by (as shown in the example in Figure 9*.8*) the result of git log master..i18n. However, note that this technique should be used only if we intend to drop (delete) the “merged” branch. This is because Git might have trouble merging any further development on the squash-merged branch, as the graph of revisions does not indicate that the commit was the result of a merge.
The alternative is to use the squash command of an interactive rebase.
Resolving merge conflicts
Section titled “Resolving merge conflicts”Merging in Git is typically fairly easy. Since Git stores and has access to a full graph of revisions, it can automatically find where the branches diverged and merge only those divergent parts. This works even in the case of repeated merges, so you can keep a very long-lived branch up to date by repeatedly merging into it or rebasing it on top of new changes.
However, it is not always possible to automatically combine changes. There are problems that Git cannot solve because, for example, there were different changes to the same area of a file on different branches. These problems are called merge conflicts. Similarly, there can be problems while reapplying changes, although you would still get merge conflicts in case of problems.
The three-way merge
Section titled “The three-way merge”Unlike some other version control systems, Git does not try to be overly clever about merge conflict resolutions and try to solve them all automatically. Git’s philosophy is to be smart about determining the cases when a merge can be easily done automatically (for example, taking renames into account) and, if automatic resolution is not possible, to not be overly clever about trying to resolve it. It is better to bail out and ask users to resolve a merge, perhaps unnecessary with a smart algorithm, than to automatically create an incorrect one.
Git uses the three-way merge algorithm to come up with the result of the merge, comparing the common ancestors (base), the side merged in (theirs), and the side merged into (ours). This algorithm is very simple, at least at the tree level – that is, the granularity level of files. The following table explains the rules of the algorithm:
| ancestor (base) | HEAD (ours) | branch (theirs) | result |
|---|---|---|---|
| A | A | A | A |
| A | A | B | B |
| A | B | A | B |
| A | B | B | B |
| A | B | C | merge |
Table 9.1 – How a three-way merge algorithm works
As shown in the preceding table, the rules for the trivial tree-level three-way merges are as follows:
- If only one side changes a file, take the changed version
- If both sides have the same changes, take the changed version
- If one side has a different change from the other, there is a merge conflict at the content level
It is a bit more complicated if there is more than one ancestor, or if a file is not present in all the versions, but usually, it is enough to just know and understand these rules.
If one side changes a file differently from the other (where the type of the change counts – for example, renaming a file on one branch doesn’t conflict with the changing contents of the file on the other branch), Git tries to merge the files at the content level, using the provided merge driver if it is defined, and the content-level three-way merge otherwise (for text files).
The three-way file merge examines whether the changes touch different parts of a file (different lines are changed, and these changes are well separated by more than three lines (the context size) away from each other). If these changes are present in different parts of the file, Git resolves the merge automatically (and tells us which files are auto-merged).
However, if you change the same part of the same file differently in the two branches that you’re merging together, Git won’t be able to merge them cleanly:
$ git merge i18nAuto-merging src/rand.cCONFLICT (content): Merge conflict in src/rand.cAutomatic merge failed; fix conflicts and then commit the result.This problem (a merge conflict) is then left for the user to resolve.
Examining failed merges
Section titled “Examining failed merges”If Git is unable to automatically resolve a merge (or if you have passed the --no-commit option to the git merge command), it will not create a merge commit. It will pause the process, waiting for you to resolve the conflict.
You can then always abort the merging process with git merge --abort.
Conflict markers in the working tree
Section titled “Conflict markers in the working tree”If you want to see which files are still unmerged at any point after a merge conflict, you can run git status:
$ git statusOn branch masterYou have unmerged paths. (fix conflicts and run "git commit") (use "git merge --abort" to abort the merge)Unmerged paths: (use "git add <file>..." to mark resolution) both modified:src/rand.cAnything that has not been resolved is listed as unmerged. In the case of content conflicts, Git uses standard conflict markers, putting them around the place of conflict, with the ours and theirs versions of the conflicted area in question. Your file will contain a section that will look somewhat like the following:
<<<<<<< HEAD:src/rand.cfprintf(stderr, "Usage: %s <number> [<count>]\n", argv[0]);=======fprintf(stderr, _("Usage: %s <number> [<count>\n"), argv[0]);>>>>>>> i18n:src/rand.cThis means that the ours version on the current branch (HEAD) in the src/rand.c file is there at the top of this block, between the <<<<<<< and ======= markers, while the theirs version on the i18n branch being merged (also from src/rand.c) is there at the bottom, between the ======= and >>>>>>> markers.
You need to replace this whole block by the resolution of the merge, either by choosing one side (and deleting the rest) or combining both changes, for example:
fprintf(stderr, _("Usage: %s <number> [<count>]\n"), argv[0]);To help you avoid committing unresolved changes by mistake, Git by default checks whether committed changes include something that looks like conflict markers, refusing to create a merge commit if it finds them. You can force this check to be skipped with the -- no-verify option.
If you need to examine a common ancestor version to resolve a conflict, you can switch to diff3- or zdiff3- like conflict markers, which have an additional block, separated by |||||||. This new block shows the common ancestor (ours) version:
<<<<<<< HEAD:src/rand.cfprintf(stderr, "Usage: %s <number> [<count>]\n", argv[0]);|||||||fprintf(stderr, "Usage: %s <number> [<count>\n", argv[0]);=======fprintf(stderr, _("Usage: %s <number> [<count>\n"), argv[0]);>>>>>>> i18n:src/rand.cYou can replace merge conflict markers individually on a file-per-file basis by rechecking the file again, using the following command:
$ git checkout --conflict=diff3 src/rand.cIf you prefer to use this format all the time, you can set it as the default for future merge conflicts by setting merge.conflictStyle to diff3 or zdiff3 (from the default of merge).
Three stages in the index
Section titled “Three stages in the index”How does Git keep track of which files are merged and which are not? Conflict markers in the working directory files would not be enough. Sometimes, there are legitimate contents that look like commit markers (for example, a file that contains an example of a merge conflict or files in the AsciiDoc format), and there are more conflict types than CONFLICT(content). How does Git, for example, represent the case where both sides renamed the file but in a different way, or where one side changed the file and the other side removed it?
It turns out that it is another use for the staging area of the commit (a merge commit in this case), which is also known as the index. In the case of conflicts, Git stores all of the conflicted file versions in the index under stages; each stage has a number associated with it.
- Stage 1 is the common ancestor (base)
- Stage 2 is the merged-into version from
HEAD– that is, the current branch (ours) - Stage 3 is from
MERGE_HEAD, the version you’re merging in (theirs)
You can see these stages for the unmerged files with the low-level (plumbing) command, git ls-files --unmerged (or for all the files with git ls-files --stage):
$ git ls-files --unmerged100755 ac51efdc3df4f4fd318d1a02ad05331d8e2c9111 1src/rand.c100755 36c06c8752c78d2aaf89571132f3bf7841a7b5c3 2src/rand.c100755 e85207e04dfdd50b0a1e9febbc67fd837c44a1cd 3src/rand.cYou can refer to each version with the :<stage number>:<pathname> specifier. For example, if you want to view a common ancestor version of src/rand.c, you can use the following:
$ git show :1:src/rand.cIf there is no conflict, the file is in stage 0 of the index.
Examining differences – the combined diff format
Section titled “Examining differences – the combined diff format”You can use the status command to find which files are unmerged, and conflict markers do a good job of showing conflicts. But how do we see only conflicts before we work on them, and how do we see how they were resolved? The answer is git diff.
One thing to remember is that for merges, even merges in progress, Git will show the so-called combined diff format. It looks like the following (for a conflicted file during a merge):
$ git diffdiff --cc src/rand.cindex 293c8fc,4b87d29..0000000--- a/src/rand.c+++ b/src/rand.c@@@ -14,16 -14,13 +14,26 @@@ int main(int argc, char *argv[]return EXIT_FAILURE;}++<<<<<<< HEAD:src/rand.c +fprintf(stderr, "Usage: %s <number> [<count>]\n", argv[0]);++=======+ fprintf(stderr, _("Usage: %s <number> [<count>\n"), argv[0]);++>>>>>>> i18n:src/rand.cYou can see a few differences from the ordinary unified diff format described in Chapter 2, Developing with Git. First, this uses diff --cc in the header to denote that it uses the compact combined format (it would use diff --combined instead if you used the git diff -c command). The extended header lines, such as index 293c8fc,4b87d29..0000000, take into account that there is more than one source version. The chunk header, @@@ -14,16 -14,13 +14,26 @@@, is modified (and is different from the one for the ordinary patch) to prevent people from trying to apply a combined diff as a unified diff – for example, with the patch - p1 command.
Each line of the diff command is prefixed by two or more characters (two in the most common cases of merging two branches); the first character informs us about the state of the line in the first preimage (ours) as compared to the result, the second character informs us about the other preimage (theirs), and so on. For example, ++ means that the line was not present in either of the versions being merged (here, in this example, you can find it on the line with the conflict marker).
Examining differences is even more useful for checking the resolution of a merge conflict.
To compare the result (i.e., the current state of the working directory) with the version from the current branch (i.e., merged into) – that is, the ours version – you can use git diff –ours. This also applies to the version being merged (theirs) and the common ancestor version (base).
How did we get there – git log —merge
Section titled “How did we get there – git log —merge”Sometimes, we need more context to decide which version to choose or to resolve a conflict. One such technique is reviewing a little bit of history, recalling why the two lines of development that are merged touched the same area of code.
To get the full list of divergent commits that were included in either branch, we can use the triple-dot syntax that you learned about in Chapter 4, Exploring Project History, adding the --left-right option to make Git show which side the given commit belongs to:
$ git log --oneline --left-right HEAD...MERGE_HEADWe can further simplify this and limit the output to only those commits that touched at least one of the conflicted files, with a --merge option to git log, for example:
$ git log --oneline --left-right --mergeThis can be helpful in quickly giving you the context you need to understand why something conflicts and how to intelligently resolve it.
Avoiding merge conflicts
Section titled “Avoiding merge conflicts”While Git prefers to fail to auto-merge clearly, rather than trying elaborate merge algorithms, there are a few tools and options that you can use to help Git avoid merge conflicts.
Useful merge options
Section titled “Useful merge options”One of the problems while merging branches might be that they use different end-of-line normalization or clean/smudge filters (see Chapter 3, Managing Your Worktrees). This might happen when one branch added such a configuration (e.g., changing a git attributes file) and the other did not. In the case of end-of-line character configuration changes, you would get a lot of spurious changes, where lines differ only in the EOL (end-of-line) characters. In both cases, while resolving a three-way merge, you can make Git run a virtual checkout and check-in of all three stages of a file. This is done by passing the renormalize option to the 'ort' merge strategy (git merge -Xrenormalize). This would, as the name suggests, normalize end-of-line characters, making them the same for all stages.
Changing how end of line is defined can contribute to whitespace-related conflicts. It’s pretty easy to tell that this is the case when looking at the conflict, as every line is removed on one side and added again on the other, and git diff --ignore-whitespace shows a more manageable conflict (or even a conflict that is resolved). If you see that you have a lot of whitespace issues in a merge, you can abort and redo it, this time with -Xignore-all-space, -Xignore-space-change, -Xignore-space-at-eol, or -Xignore-cr-at-eol.
Note that whitespace changes mixed with other changes to a line are not ignored.
Sometimes, mis-merges occur due to unimportant matching lines (for example, braces from distinct functions). You can make Git spend more time minimizing differences by selecting patience, a histogram, or a minimal diff algorithm with, -Xdiff-algorithm=patience, and so on.
If the problem is mis-detected renamed files, you can adjust the rename threshold with -Xfind-renames=<n>.
Rerere – reuse recorded resolutions
Section titled “Rerere – reuse recorded resolutions”The rerere (reuse recorded resolutions) functionality is a bit of a hidden feature. As the name of the feature implies, it makes Git remember how each conflict was resolved chunk by chunk, so that the next time Git sees the same conflict, it will be able to resolve it automatically. However, note that Git will stop at resolving conflicts and does not automatically commit the said rerere-based resolution, even if it resolves it cleanly (if it is superficially correct).
Such a functionality is useful in many scenarios. One example is a situation when you want a long-lived (i.e., long development) branch to merge cleanly at the end of its cycle, but you do not want to create intermediate merge commits. In this situation, you can do trial merges (merge, and then delete merge), saving information about how merge conflicts were resolved to the rerere cache. With this technique, the final merge should be easy, as most of it will be cleanly resolved from the resolutions recorded earlier.
Another situation in which you can make use of the rerere cache is when you merge a bunch of topic branches into a testable permanent branch. If the integration test for a branch fails, you want to be able to rewind the failed branch but don’t want to lose the work spent on resolving a merge.
Alternatively, perhaps you have decided that you would rather use rebase than merge. The rerere mechanism allows us to translate the merge resolution into the rebase resolution.
To enable this functionality, simply set rerere.enabled to true, or create the .git/ rr-cache file.
Dealing with merge conflicts
Section titled “Dealing with merge conflicts”Let’s assume that Git was not able to auto-merge cleanly and that there are merge conflicts that you need to resolve to be able to create a new merge commit. What are your options?
Aborting a merge
Section titled “Aborting a merge”First, let’s cover how to get out of this situation. If you weren’t perhaps prepared for conflicts or you don’t know enough about how to resolve them, you can simply back out from the merge you started with git merge --abort.
This command tries to reset to the state before you started a merge. It might be not able to do this if you did not start from a clean state. Therefore, it is better to stash away changes, if there are any, before performing a merge operation (which you can do with --autostash, or the merge.autoStash / rebase.autoStash configuration options).
Selecting the ours or theirs version
Section titled “Selecting the ours or theirs version”Sometimes, it is enough to choose one version in the case of conflicts. If you want to resolve all the conflicts this way, forcing all the chunks to resolve in favor of ours or theirs version, you can use the -Xours or -Xtheirs merge strategy option, respectively. Note that -Xours (the merge option) is different from --strategy=ours (the merge strategy); the latter creates a merge commit where the project state is the same as the ours version, instead of taking the ours version only for conflicted files.
If you want to do this only for selected files, you can again check out the file with the ours or theirs version with git checkout --ours or git checkout--theirs, respectively. Note that during the rebase, the ours and theirs version may appear to be swapped.
You can examine the base, ours, or theirs version with git show :1:file, git show:2:file, or git show:3:file, respectively, as described earlier.
Scriptable fixes – manual file remerging
Section titled “Scriptable fixes – manual file remerging”There are types of changes that Git can’t handle automatically, but they are scriptable fixes. The merge can be done automatically, or at least is much easier, if we transform the ours, theirs, or base version first. Renormalization after changing how the file is checked out and stored in the repository (i.e., eol and clean/smudge filters) and handling the whitespace change are built-in options. Another example, but without built-in support, is changing the encoding of a file or another scriptable set of changes, such as renaming variables.
To perform a scripted merge, you first need to extract a copy of each of these versions of the conflicted file, which can be done with the git show command and with :<stage>:<file>:
$ git show :1:src/rand.c >src/rand.common.c$ git show :2:src/rand.c >src/rand.ours.c$ git show :3:src/rand.c >src/rand.theirs.cNow that you have in the working area the contents of all three stages of the files, you can fix each version individually – for example, with dos2unix or iconv. You can then remerge the contents of the file with the following command:
$ git merge-file -p \ rand.ours.c rand.common.c rand.theirs.c >rand.cUsing graphical merge tools
Section titled “Using graphical merge tools”If you want to use a graphical tool to help you resolve merge conflicts, you can run git mergetool, which fires up a visual merge tool and guides the invoked tool through all the merge conflicts.
It has a wide set of preconfigured support for various graphical merge helpers. You can configure which tool you want to use with merge.tool. If you don’t do this, Git will try all the possible tools in the sequence, which depends on the operating system and the desktop environment.
You can also configure a setup for your own tool.
Marking files as resolved and finalizing merges
Section titled “Marking files as resolved and finalizing merges”As described earlier, if there is a merge conflict for a file, it will have three stages in the index. To mark a file as resolved, you need to put the contents of a file into stage 0. This can be done by simply running git add <file> (running git status will give you this hint).
When all the conflicts are resolved, you need to simply run git commit to finalize the merge commit (or you can skip marking each file individually as resolved and just run git commit -a). The default commit message for merge summarizes what we merge, including a list of the conflicts, if any were present. You can make Git add a shortlog of the merged-in branches with the --log option for a single merge, or set it up permanently with the merge.log configuration variable.
Resolving rebase conflicts
Section titled “Resolving rebase conflicts”When there is a problem with applying a patch or a patch series, cherry-picking or reverting a commit, or rebasing a branch, Git will fall back to using the three-way merge algorithm. How to resolve such conflicts is described in the earlier sections.
Important note
Note that when using merging strategies (the default), for technical reasons, ours is the so-far rebased series – that is, the branch being integrated – while theirs is the working branch (the branch rebased onto).
However, for some of these methods, such as rebase, applying a mailbox (git am), or cherry-picking a series of commits, that are done stage by stage (a sequencer operation), there are other issues – namely, what to do if there is a conflict during such a stage.
You have three options:
- You can resolve the conflict and continue the operation with the
--continueparameter (or, in the case ofgit am, also--resolved) - You can abort the whole operation and reset
HEADto the original branch with--abort - You can use
--skipto drop a revision, perhaps because the commit is already present in the upstream and we can drop it during replaying
git-imerge – an incremental merge and rebase for git
Section titled “git-imerge – an incremental merge and rebase for git”Both rebase and merge have their disadvantages. With merge, you need to resolve one big conflict (although using test merges and rerere to keep up-to-date proposed resolutions could help with this) in an all-or-nothing fashion. There is almost no way to save partially a done merge or to test it; git stash can help, but it might be an inadequate solution.
Rebase, conversely, is done in a step-by-step fashion, but it is not ideal for collaboration; you should not rebase published parts of the history of the project. You can interrupt a rebase, but it leaves you in a strange state (on an anonymous branch).
That’s why the git imerge third-party tool was created. It presents conflicts pair-wise in small steps. It records all the intermediate merges in such a way that they can be shared, so one person can start merging and the other can finish it. The final resolution can be stored as an ordinary merge, an ordinary rebase, or a rebase with history.
Summary
Section titled “Summary”This chapter has shown us how to effectively join two lines of development together, combining commits they gathered since their divergence.
First, we got to know various methods of combining changes – merge, cherry-pick, and rebase. This part focused on explaining how these functionalities work at higher levels – at the level of the DAG of revisions. You learned how merge and rebase work and what the difference is between them. Some of the more interesting uses of rebase, such as transplanting a topic branch from one long-lived branch to another, were also shown.
Then, you learned what to do if Git is not able to automatically combine changes – that is, what can be done in the presence of a merge conflict. The important part of this process is to understand how the three-way merge algorithm works, as well as how the index and the working area are affected if there are conflicts. You now know how to examine failed merges, examine proposed resolutions, avoid conflicts, and finally, resolve them and mark them as resolved.
The next chapter, Keeping History Clean, will explain why we might want to rewrite history to keep it clean (and what that means). One of the tools to rewrite history is an interactive rebase, a close cousin of an ordinary rebase operation described in this chapter. You will learn various methods to rewrite commits: how to reorder them, how to split them if they are too large, how to squash the fixing commit with the commit it corrects, and how to remove a file from history. You will discover what you can do if you cannot rewrite history (understanding why rewriting published history is bad) but you still need to correct it, with git replace and git notes commands. We will also discuss other applications of these mechanisms.
Questions
Section titled “Questions”Answer the following questions to test your knowledge of this chapter:
- What are the advantages and disadvantages of using merge to integrate changes?
- What are the advantages and disadvantages of using rebase to integrate changes?
- How do we avoid resolving similar conflicts again and again during a merge or rebase?
- How can we discover whether we are in the middle of merge or rebase, and remind ourselves on how to resolve conflict or abort an operation?
Answers
Section titled “Answers”Here are the answers to the questions given above:
- With merge, you do the integration in a single step (which can be an advantage or disadvantage), and you need to test only a single commit – the result of the merge. You can easily see where the branch began and where it ended. The first-parent view can serve as a summary of the integrated branches.
- With rebase, you do the integration step by step (which can be a disadvantage or an advantage). Each of the rebased commits might need testing. The resulting history is much simpler, more linear, and easier to see. Using
bisectionto find regression bugs should be faster with linear history. - You can use the rerere mechanism, which automatically reapplies recorded conflict resolutions.
- Use the
gitstatuscommand.
Further reading
Section titled “Further reading”To learn more about the topics that were covered in this chapter, take a look at the following resources:
- Scott Chacon, Ben Straub: Pro Git, 2nd Edition (2014): https://git-scm.com/book/en/v2:
- Chapter 3.6, Git Branching – Rebasing
- Chapter 7.8, Git Tools – Advanced Merging
- Chapter 7.9, Git Tools – Rerere
- Chapter 3.6, Git Branching – Rebasing
- Julia Evans, git rebase: what can go wrong? (2023): https://jvns.ca/blog/2023/11/06/rebasing-what-can-go-wrong-/
- Julia Evans, How git cherry-pick and revert use 3-way merge (2023): https://jvns.ca/blog/2023/11/10/how-cherry-pick-and-revert-work/
- Junio C Hamano, Where do evil merges come from? (2013): https://git-blame.blogspot.com/2013/04/where-do-evil-merges-come-from.html
- Nick Quaranto, git ready – keep either file in merge conflicts (2009): https://gitready.com/advanced/2009/02/25/keep-either-file-in-merge-conflicts.html
- Learn to use email with git!: https://git-send-email.io/