Skip to content

Chapter 4 of 8

Merging and Conflict Resolution

Merging is Git's other way of combining work, and it offers several flags that change how branches are combined. The default git merge feature performs a fast-forward when possible and otherwise creates a merge commit. To require a linear history, git merge --ff-only feature aborts if a fast-forward is not possible. To always record a merge commit (useful in code review workflows where you want to see where a feature joined main), use git merge --no-ff feature. A merge in progress can always be cancelled with git merge --abort, which restores the branch and working tree to the pre-merge state.

Conflicts appear as <<<<<<<, =======, and >>>>>>> markers in the affected files. After editing to keep only the desired content and removing the markers, git add the file and continue the merge or rebase. To see which paths are still conflicted, run git status or git diff --name-only --diff-filter=U. For wholesale choices, git checkout --theirs file or git checkout --ours file accepts an entire side; note that --strategy=ours (a merge strategy, not a per-file option) keeps only our side and is rarely what you want, whereas -X theirs (an option to the recursive strategy) just biases automatic resolution toward their side.

Two conflict-related settings prevent recurring pain. The rerere feature, enabled globally with git config --global rerere.enabled true, records how you previously resolved identical conflicts and replays that resolution automatically on future merges. When you try to combine two repositories that share no common ancestor (such as an existing project into a freshly initialized folder), Git refuses with "fatal: refusing to merge unrelated histories"; the fix is to add --allow-unrelated-histories to the merge or pull, after first verifying that the histories really should be joined.

All chapters
  1. 1Undoing Commits and Local Changes
  2. 2Cleaning the Working Tree and Fixing .gitignore
  3. 3Rewriting History with Rebase
  4. 4Merging and Conflict Resolution
  5. 5Stashing Work in Progress
  6. 6Branches, Remotes, Tags, and Force-Push Safety
  7. 7Investigating and Searching History
  8. 8Advanced Recovery, Configuration, and Housekeeping

Drill it

Reading is not remembering. These come from the Git Recovering From Common Mistakes deck:

Q

Undo the last commit but keep changes staged.

git reset --soft HEAD~1

Q

Undo the last commit AND discard changes.

git reset --hard HEAD~1 &nbsp;⚠ destructive.

Q

Undo the last commit but keep changes unstaged in the working tree.

git reset --mixed HEAD~1 (the default).

Q

Amend the last commit message.

git commit --amend -m 'new message'