Git Merge Strategies and Algorithms

Jul 29, 2023

How does git merge one or more branches? A look at the different merge strategies and algorithms.

Recursive. If more than one common ancestor can be used for a three-way merge, it creates a merged tree of the common ancestors and uses that tree as a reference for the three-way merge. If there are conflicts, it can use heuristics to try and automatically resolve them (e.g., picking the file that’s been modified most recently).

ort (“Ostensibly Recursive’s Twin”). The new default merge strategy in git. Instead of using the in-memory index, it creates a new merge result as a tree without touching the working tree or index.

Avoiding the working tree or index, there are opportunities for significant speedups and optimizations — everything from how partial clones are handled, to more accurate identification of file renames, to caching.

Depending on the scenario (e.g., many renames or long rebases), merge-ort can be orders of magnitude faster.

The name is also a pun on merge sort, as you can specify it with either git merge -s ort or git merge -sort.

Resolve. Instead of creating a merged common ancestor, it picks the best one. It sometimes results in fewer merge conflicts and a more straightforward history, but it doesn’t handle complex scenarios well.

Octopus. Merges the first two branches, then the result with the third branch, and then continues until all branches are merged. Aborts if there are any conflicts. Efficient and quick, but requires all branches to merge cleanly.

Ours. Ignores the incoming changes and keeps the content of the current branch. Creates a new commit that matches the current state of the branch and records a history that includes the merged branch.

Subtree. Modifies the project that is being merged by prefixing all of its file paths with a specific path. Then, performs a merge using the default strategy (ort).