No description
  • Python 80.3%
  • Cython 19.5%
  • Just 0.2%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
renovate-bot b95182d709
Some checks failed
Tag new version / test (push) Successful in 10s
Tests / test (3.11) (push) Failing after 8s
Tests / test (3.12) (push) Successful in 35s
Tests / test (3.14) (push) Successful in 43s
Tests / test (3.13) (push) Successful in 43s
Merge pull request 'chore(deps): update astral-sh/setup-uv action to v10.4.1' (#31) from renovate/astral-sh-setup-uv-10.x into main
2026-12-02 00:06:02 +00:00
.forgejo/workflows chore(deps): update astral-sh/setup-uv action to v10.4.1 2026-12-02 00:03:05 +00:00
.vscode fix: to git extended misses line break in conflict when conflict ist last or single line of content 2026-11-03 17:32:17 +01:00
docs docs: document version identity decision 2026-11-10 18:15:09 +00:00
src docs: document output formats and multi-line conflict grouping 2026-11-15 15:40:30 +00:00
.gitignore build: switch build backend to setuptools with cython 2026-11-10 07:33:23 +00:00
.python-version fix: to git extended misses line break in conflict when conflict ist last or single line of content 2026-11-03 17:32:17 +01:00
AGENTS.md docs: document version identity decision 2026-11-10 18:15:09 +00:00
justfile test: init 2026-09-26 16:30:11 +02:00
MANIFEST.in build: switch build backend to setuptools with cython 2026-11-10 07:33:23 +00:00
pyproject.toml chore(deps): update min python version 2026-11-10 09:30:36 +01:00
README.md docs: document output formats and multi-line conflict grouping 2026-11-15 15:40:30 +00:00
renovate.json5 ci: add renovate config 2026-10-02 08:18:41 +00:00
setup.py build: switch build backend to setuptools with cython 2026-11-10 07:33:23 +00:00
uv.lock chore(deps): sync lockfile with minimum python version 3.10 2026-11-10 15:11:22 +00:00

n-way-merge

N-way merge that extends classic git merge behaviour.

Classic git can only merge two sides against a base (3-way). This project merges iteratively: the result (including unresolved conflict blocks) is used as the base for the next merge, so conflicts can accumulate n versions.

Quick start

from n_way_merge import NWayMerger

merger = NWayMerger()

base = "a\nb\nc"
ours = "a\nX\nc"
theirs = "a\nY\nc"

merged = merger.merge(base, ours, theirs)

print(merged.to_git())
# a
# <<<<<<< ours
# X
# =======
# Y
# >>>>>>> theirs
# c

Merging more than two versions

Pass further versions as additional arguments. The first two are merged against the base; each additional version is merged into the accumulated result, so conflicts can accumulate n versions:

merged = merger.merge(base, ours, theirs, third, fourth)

print(merged.to_git_extended())

Merging versions one at a time

If versions arrive incrementally (e.g. one user at a time), keep the original base fixed and carry the accumulated result forward. Each new version is merged against the base; conflict blocks that already exist in the result are preserved, so they accumulate n versions just like with merge(base, …, *more):

base = "a\nb\nc\nd"
u1 = "a\nU1\nc\nd"
u2 = "a\nU2\nc\nd"
u3 = "a\nU3\nc\nd"

current = base
for user in (u1, u2, u3):
    current = merger.merge(base, current, user)

print(current.to_git_extended())
# a
# <<<<<<< ours
# U1
# =======
# U2
# =======
# U3
# >>>>>>> theirs
# c
# d

Existing conflict blocks in current are kept because conflict versions are read from the base, ours and theirs — not only from the base. That is what lets an accumulated result hold its conflicts even though the base is the original, conflict-free document.

Working with units directly

parse() is available to inspect or transform units before merging; every merge argument accepts both str and Units:

base_units = merger.parse(base)

merged = merger.merge(base_units, ours, merger.parse(theirs))

Output formats

Call any of them on the merge result:

merged.to_git()  # classic git conflict block (first 2 versions)
merged.to_git_extended()  # git conflict block with any number of versions
merged.to_structured()  # text with conflicts as inline JSON units
merged.to_json_string()  # whole document as JSON
merged.to_json_lines()  # list of unit dicts

The following examples all use this merge, where both lines b and c are changed differently by both sides:

base = "a\nb\nc\nd"
ours = "a\nX1\nX2\nd"
theirs = "a\nY1\nY2\nd"
merged = merger.merge(base, ours, theirs)

Git formats

to_git() and to_git_extended() render the document as a git conflict document: clean units verbatim, each conflict as a block.

a
<<<<<<< ours
X1
X2
=======
Y1
Y2
>>>>>>> theirs
d

to_git() renders only the first two versions (classic block); to_git_extended() renders all versions, separated by additional ======= markers. Adjacent per-line conflicts that come from the same sources are rendered as one multi-line block — see Multi-line conflicts.

Structured text

to_structured() writes clean lines verbatim and each conflict as a single inline JSON line — one line per unit:

a
{"type": "conflict", "base": "b\n", "versions": ["X1\n", "Y1\n"], "version_ids": ["vff599458f0b1", "v47642d923ce8"]}
{"type": "conflict", "base": "c\n", "versions": ["X2\n", "Y2\n"], "version_ids": ["vff599458f0b1", "v47642d923ce8"]}
d

The result can be parsed again with parse() and used as the base of a further merge; the version_ids are carried through, so multi-line grouping survives the round trip.

JSON

to_json_string() is the whole document as a JSON array; to_json_lines() is the same list of unit dicts:

[
  {"type": "clean", "lines": "a\n"},
  {"type": "conflict", "base": "b\n", "versions": ["X1\n", "Y1\n"], "version_ids": ["vff599458f0b1", "v47642d923ce8"]},
  {"type": "conflict", "base": "c\n", "versions": ["X2\n", "Y2\n"], "version_ids": ["vff599458f0b1", "v47642d923ce8"]},
  {"type": "clean", "lines": "d"}
]

Unit dict shape:

  • clean: {"type": "clean", "lines": "..."}
  • conflict: {"type": "conflict", "base": "...", "versions": ["...", ...]}, plus "anchor": true for units parsed from a git conflict block and "version_ids": [...] (one id per version) when the provenance is known

Multi-line conflicts

The merge core is line-based: two adjacent changed lines produce two adjacent single-line ConflictUnits, while git shows a multi-line block as one unit. To reconcile the two, conflict versions carry an identity (version_ids, one id per version — see docs/version-identity.md):

  • to_git()/to_git_extended() group runs of adjacent conflict units with an equal version_ids sequence into one multi-line block, so per-line conflicts render as a classic multi-line conflict (as above, the two one-line units form the single X1/X2 vs Y1/Y2 block)
  • The structured/JSON formats keep the per-line units but carry the version_ids, so the identity survives parse(to_structured(x)) round trips
  • Parsing a git block splits equal-length versions into one unit per line sharing the id sequence, so a parsed multi-line block stays grouped through a merge and renders as one block again
  • Conflicts from different user sets (different id sequences) stay separate blocks — the honest representation
  • Units without ids (hand-built, legacy JSON) never group and render exactly as before; the git text output itself never contains ids

Error handling

  • parse() and every merge() argument must be str or Units; anything else raises TypeError
  • Malformed documents raise ParseError (a ValueError subclass) with the 1-based line number of the offending line:
    • unclosed git conflict block (missing ======= or >>>>>>>)
    • unit line that looks like JSON but is not valid JSON
    • unit JSON with missing keys (base, versions, lines)
    • unknown unit type
from n_way_merge import NWayMerger, ParseError

try:
    merger.parse("a\n<<<<<<< ours\nX\n")
except ParseError as e:
    print(e)  # line 2: unclosed conflict block: missing '======='

How it works

  • A document is a list of units (see src/n_way_merge/units.py):
    • CleanUnit – a clean region of lines
    • ConflictUnit – a conflict with a base and one or more versions
  • Flow: parse(String) -> Doc -> merge(base, ours, theirs[, *more]) -> Doc -> to_*() -> String
  • Conflict versions carry an identity (version_ids) that drives multi-line grouping — see Multi-line conflicts
  • merge() accepts str or parsed Units for every argument; the first three arguments form the classic 3-way merge, each further argument is one additional 3-way round on the accumulated result
  • Semantics per region:
    • ours == theirs (and != base) → resolved, clean (common value)
    • ours == theirs == base → unchanged; existing conflicts are kept
    • clean base region → classic 3-way (one side changed → clean, differing changes → conflict)
    • conflict region → conflict remains; versions = versions of any conflict block present in base/ours/theirs + ours/theirs changes (dedup, base does not count as a version, anchor units excluded)
  • A merge neither adds nor removes a trailing newline: lines are normalized at parse time and the original state is carried in Units.ends_with_newline — see docs/newline-handling.md

Tests

just tests            # all tests
just tests --filter=unit   # filter by test directory
# or directly:
uv run pytest src/test/unit

Project layout

src/n_way_merge/
├── __init__.py        # package entry point (NWayMerger, ParseError)
├── errors.py          # ParseError
├── n_way_merger.pyx   # NWayMerger: parse + 3-way merge logic (Cython)
├── unit_parser.py     # parses strings (git blocks/JSON) into units
├── units.py           # CleanUnit, ConflictUnit
├── merged.py          # Units document + serializers (Git/JSON/structured)
└── utils.py           # small helpers
src/test/unit/         # pytest tests
docs/                  # architectural decisions (newline handling)

CI

Forgejo workflows in .forgejo/workflows/: tests, version tags and package publish.