Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 78 ยท Branching and Merging

Merge Strategies and Custom Merge Drivers

Go beyond the default git merge: ort options, octopus merges, the subtree strategy, the built-in union driver and your own custom merge drivers for special files.

Most of the time git merge just works, and you never think about how. But two situations make you look deeper. First, the merge is technically correct and still wrong for your project: a lock file, a changelog or a generated file conflicts again and again. Second, you need something other than "merge two branches": combine five topic branches at once, or pull another project into a subdirectory.

Git has two extension points for this. A merge strategy decides how whole trees are combined, and a merge driver decides how one particular kind of file is combined. This lesson covers the useful options of the default strategy, the octopus and subtree strategies, the built-in union driver, and how to write your own driver. For the algorithm underneath, read How Merge, Rebase and Diff Work Inside first; for day-to-day merging see Merging Branches and Resolving Merge Conflicts.

Strategies and strategy options

git merge -s <strategy> picks the strategy; git merge -X <option> passes an option to it. The strategies you may meet:

Strategy What it does Typical use
ort Default for two branches. Fast, detects renames, handles several merge bases Almost always
recursive The older default, now an alias for ort Old scripts
resolve A simple three-way merge, no rename detection Rare, very large trees where ort struggles
octopus Merges more than two branches; refuses to resolve conflicts Combining many clean topics
ours Records a merge but keeps our tree unchanged Declaring old history "merged"
subtree A variant of ort that shifts trees to match a subdirectory Merging a project that lives in a subfolder

The ours strategy and the -X ours and -X theirs options are explained in How Merge, Rebase and Diff Work Inside. The other options of ort are worth knowing, because they solve concrete annoyances:

  • -X ignore-space-change, -X ignore-all-space, -X ignore-space-at-eol: treat whitespace-only differences as equal. Useful when one branch re-indented a file.
  • -X renormalize: re-normalize line endings before merging. Use it when one side converted a file between CRLF and LF (see Attributes and LFS).
  • -X find-renames=<n> and -X no-renames: tune or disable rename detection when Git pairs the wrong files.
  • -X patience (and histogram, minimal): choose the diff algorithm used inside the merge, sometimes turning a messy conflict into a clean one.
  • -X subtree[=<path>]: described below.

Options can be combined, for example git merge -X patience -X ignore-space-change topic. If a merge goes badly, git merge --abort returns to the state before it; options are cheap to retry.

The octopus strategy

When you give git merge more than one branch, Git switches to octopus automatically. It creates a single merge commit with several parents, which is handy for gathering independent topic branches (for example a release candidate made from five finished features). The strategy is deliberately cautious: if any of the branches conflict with the result so far, the merge stops and nothing is committed. For conflicting branches, merge them one at a time.

flowchart LR
  M0["main"] --> OM(("Octopus<br/>merge"))
  A["topic-a"] --> OM
  B["topic-b"] --> OM
  C["topic-c"] --> OM

One merge commit with four parents: the previous main and three topic branches.

Bash One merge commit, four parents

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The first merge produces one commit with four parents: the old main first, then the three topics. In the second part the two branches add different content to the same new file. The octopus strategy refuses to resolve that: it reports a failure and leaves the conflict in your working tree without creating a commit. git merge --abort puts everything back, and you then merge x1 and x2 one at a time and resolve the conflict by hand.

The subtree strategy

The subtree strategy solves a specific problem: you have the history of project B and want it inside a subdirectory of project A (for example vendor/b/), while still being able to merge future changes from B. A normal merge would fail to line the files up, because in B they sit at the top level and in A they sit under vendor/b/. -X subtree=<path> tells ort to shift one tree to match the other before merging. The setup has three steps:

  1. Import B's history with --allow-unrelated-histories, without committing.
  2. Place B's files under the prefix with git read-tree --prefix=.
  3. For later updates, merge with -X subtree=vendor/b.
Bash Merge another project into a subdirectory and update it later

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The updated file ends up at vendor/libb/lib.txt even though the upstream path is lib.txt. The git subtree helper command (see Submodules and Subtrees) wraps exactly this recipe. Choose subtrees when you want contributors to clone one repository and never think about the other; choose submodules when you want to pin an exact version of an independent project.

Merge drivers: per-file rules

A strategy works on the whole tree. A merge driver works on one file at a time and is selected by .gitattributes. Every time a file needs a real three-way merge, Git looks at its merge attribute:

TEXT
CHANGELOG.md   merge=union
VERSION        merge=ours
data/*.json    merge=jsonmerge

Three kinds of values exist:

  • merge=union is built in. It keeps lines from both sides and never produces conflict markers. It is perfect for append-only files such as a changelog or a list of ignored words, where order does not matter and both sides add lines.
  • merge=binary (or -merge) marks a file as unmergeable: any difference is a conflict, and Git keeps the current side.
  • A custom name (ours, jsonmerge...) refers to a driver you define in the Git config: git config merge.<name>.driver "<command>".

The command receives placeholders: %O is the path of the common ancestor's version, %A is the current branch's version, and %B is the other branch's version. The driver must write the merged result into the %A file and exit with 0 if the merge is clean or non-zero if it still has conflicts. Define the drivers in the repository's .git/config or your global config, and commit only the .gitattributes file. Because the command lives in config, each developer has to set it up (a setup script or make init helps); it cannot be shared through a clone, for good security reasons.

A driver is also a fine place to encode a project rule. The example uses all three: the union driver for a changelog, the do-nothing driver true (which leaves %A untouched, so the current side wins) for a version file, and a small custom script that keeps the larger of two numbers.

Bash Union, ours and a custom driver in one merge

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Without the attributes, all three files would have conflicted, because each side changed the same lines. With them, the merge finishes by itself. You can inspect which driver applies to a file with git check-attr merge -- VERSION.

Be careful with drivers that hide conflicts. union can interleave lines in a meaningless order, and ours silently drops the other side's change. Use them only for files where that is truly the rule, and keep real source code on the normal merge.

Drivers do not apply to rebase-free tools alone: they run during git merge, git rebase, git cherry-pick and git stash pop, wherever a three-way file merge happens. If you resolve the same conflict repeatedly, git rerere (reuse recorded resolution) is an alternative that learns from your manual fix.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when you run git merge topic-a topic-b topic-c?

    With more than one branch, Git uses the octopus strategy. It creates a single merge commit with multiple parents, and fails if any of the merges would conflict.
  2. 2. Which option tells the ort strategy that the other project lives in a subdirectory of your repository?

    -X subtree=<path> shifts the trees so the files line up before merging, which makes later updates of an imported project work.
  3. 3. What does merge=union in .gitattributes do?

    The built-in union driver combines both sides line by line. It suits append-only files such as changelogs, but it can mix order.
  4. 4. A custom merge driver receives %O, %A and %B. Where must it write the result?

    Git takes the merged content from the %A file and treats exit status 0 as a clean merge. A non-zero status leaves the file conflicted.
  5. 5. Why can't the merge driver command be shared through git clone?

    Only the .gitattributes mapping is versioned. The command itself is configuration, which Git does not transfer so that a repository cannot run arbitrary commands on your machine.

Summary

  • -s <strategy> chooses how trees are merged (ort, octopus, ours, subtree, resolve); -X <option> tunes it (whitespace options, renormalize, rename detection, diff algorithms, subtree=<path>).
  • Merging several branches at once uses the octopus strategy: one commit, many parents, no conflicts allowed.
  • -X subtree=<path> lets you keep updating an imported project that lives in a subdirectory.
  • Merge drivers are chosen per file with .gitattributes: union and binary are built in, and your own driver is defined with git config merge.<name>.driver "<cmd %O %A %B>".
  • A driver writes the result to %A and exits with 0 for success; the command is local configuration and must be set up by each developer.
  • Use drivers that hide conflicts (union, ours) only where that really is the right rule.

Next: Revisions