Two branches can each contain a valid change and still fail to merge automatically. In this lab, main changes a shipping rule to tracked while an express branch changes the same line to express. The intended result needs both features. Picking only one side would make Git happy while losing a requirement.
The complete downloadable lab creates its own temporary repository, reproduces the conflict, stages a combined resolution and records a merge commit. It does not fetch, push or use your existing checkout. All files and the nine-test verifier are included below and in the ZIP.
Requirements and a predictable run
Use Python 3.10 or later and Git 2.28 or later, both on PATH. There are no third-party Python packages. Extract the ZIP, enter its git-merge-conflict directory and run:
python lab.py
python -m unittest -v
The lab prints:
Conflict status: UU shipping.txt
Resolved: Shipping: tracked express
Merge parents: 2
Working tree clean: true
Verification ran with Python 3.13.3 and Git 2.45.1.windows.1 on Windows. These are the recorded available versions, not a recommendation to use an older patch release. Each run creates and later removes a new repository under the operating system's temporary directory. Re-running the lab starts from scratch instead of depending on the last run's state.
Build two changes from a common ancestor
The initial file contains Shipping: standard. The express branch changes it to Shipping: express, while main independently changes it to Shipping: tracked. Both commits descend from the initial commit, so neither later commit already contains the other branch's work.
Save the complete runner as lab.py. Its Git wrapper passes a demo identity, disables signing for these subprocesses and avoids inherited Git configuration/overrides. The fixture refuses an existing destination directory and initializes with an empty template. No global configuration file or existing repository is edited.
from pathlib import Path
from tempfile import TemporaryDirectory
import os
import subprocess
BASE = 'Shipping: standard\n'
MAIN = 'Shipping: tracked\n'
FEATURE = 'Shipping: express\n'
RESOLVED = 'Shipping: tracked express\n'
def git(repository, *arguments, check=True):
environment = os.environ.copy()
for name in list(environment):
if name.startswith('GIT_'):
del environment[name]
environment['GIT_CONFIG_NOSYSTEM'] = '1'
environment['GIT_CONFIG_GLOBAL'] = os.devnull
environment['GIT_TERMINAL_PROMPT'] = '0'
command = [
'git',
'-c', 'user.name=Toolzify Demo',
'-c', 'user.email=demo@example.test',
'-c', 'commit.gpgsign=false',
'-c', 'core.autocrlf=false',
'-c', 'merge.conflictStyle=merge',
*arguments,
]
result = subprocess.run(
command,
cwd=repository,
env=environment,
text=True,
encoding='utf-8',
capture_output=True,
check=check,
)
return result
def build_conflict(parent):
repository = Path(parent) / 'merge-lab'
repository.mkdir()
git(repository, 'init', '--template=', '--initial-branch=main')
shipping = repository / 'shipping.txt'
shipping.write_text(BASE, encoding='utf-8')
git(repository, 'add', 'shipping.txt')
git(repository, 'commit', '-m', 'Initial shipping rule')
git(repository, 'switch', '-c', 'express')
shipping.write_text(FEATURE, encoding='utf-8')
git(repository, 'add', 'shipping.txt')
git(repository, 'commit', '-m', 'Add express shipping')
git(repository, 'switch', 'main')
shipping.write_text(MAIN, encoding='utf-8')
git(repository, 'add', 'shipping.txt')
git(repository, 'commit', '-m', 'Add tracking')
merge = git(repository, 'merge', 'express', check=False)
if merge.returncode != 1:
raise RuntimeError('Expected a content conflict, not a completed merge.')
status = git(repository, 'status', '--porcelain=v1').stdout
if status != 'UU shipping.txt\n':
raise RuntimeError('The expected unmerged file was not found.')
return repository
def stage_resolution(repository):
shipping = repository / 'shipping.txt'
shipping.write_text(RESOLVED, encoding='utf-8')
git(repository, 'add', 'shipping.txt')
def complete_merge(repository):
git(repository, 'commit', '-m', 'Keep tracked express shipping')
def main():
with TemporaryDirectory(prefix='toolzify-merge-') as temporary:
repository = build_conflict(temporary)
status = git(repository, 'status', '--porcelain=v1').stdout.strip()
print('Conflict status: ' + status)
stage_resolution(repository)
complete_merge(repository)
shipping = repository / 'shipping.txt'
print('Resolved: ' + shipping.read_text(encoding='utf-8').strip())
parents = git(repository, 'rev-list', '--parents', '-n', '1', 'HEAD').stdout.split()
print('Merge parents: ' + str(len(parents) - 1))
clean = git(repository, 'status', '--porcelain=v1').stdout == ''
print('Working tree clean: ' + str(clean).lower())
if __name__ == '__main__':
main()
The runner expects merge to stop with an unmerged file. It checks the machine-readable status rather than parsing localized human-facing error messages. According to the git-status reference, UU represents an unmerged path modified on both sides. It is not simply an ordinary unstaged change.
Understand the conflict before choosing text
For this normal merge into main, HEAD is the current branch's version and express is the incoming version. The working file contains the conflict markers around their competing lines. The index also retains the base, current and incoming stages, which the tests inspect with git show.
The git-merge documentation describes examining those three versions, editing the file into the intended result, staging it and completing the merge. Here the chosen line is Shipping: tracked express. That is a domain decision for this fictional example, not a universal rule to concatenate conflicted text.
In an application, two code fragments may contradict each other even after every marker is removed. Read the requirements and run the relevant application checks. A successful merge command proves that Git can record the selected tree; it does not prove that business behavior is correct.
Editing, staging and committing are separate steps
The lab's stage_resolution function first writes the combined text, then stages shipping.txt. The git-add reference explains that the index supplies the content for the next commit. Once this chosen file is staged, its unmerged index entries are replaced by the resolved content.
complete_merge then records the merge commit. The verifier checks that its first parent is the original main tip and its second parent is the express tip. It also reads the committed file, so a clean working tree alone is not accepted as proof that both requirements survived.
The abort case uses a separate fresh fixture. Aborting returns this controlled example to the committed main version. Real merges may begin with uncommitted changes, so this test is not a guarantee that abort can reconstruct arbitrary work. Inspect status and preserve local changes before starting a real integration.
Nine tests against actual Git state
Save the complete verifier as test_lab.py. Every test gets an independent temporary repository, and unittest exits nonzero if a check fails.
from pathlib import Path
from tempfile import TemporaryDirectory
import unittest
from lab import build_conflict, complete_merge, git, stage_resolution
class MergeLabTests(unittest.TestCase):
def setUp(self):
self.temporary = TemporaryDirectory(prefix='toolzify-merge-test-')
self.addCleanup(self.temporary.cleanup)
self.repository = build_conflict(self.temporary.name)
def test_unmerged_status(self):
status = git(self.repository, 'status', '--porcelain=v1').stdout
self.assertEqual(status, 'UU shipping.txt\n')
def test_markers_show_both_branch_changes(self):
content = (self.repository / 'shipping.txt').read_text(encoding='utf-8')
self.assertIn('<<<<<<< HEAD', content)
self.assertIn('Shipping: tracked', content)
self.assertIn('=======', content)
self.assertIn('Shipping: express', content)
self.assertIn('>>>>>>> express', content)
def test_index_retains_base_ours_and_theirs(self):
self.assertEqual(git(self.repository, 'show', ':1:shipping.txt').stdout, 'Shipping: standard\n')
self.assertEqual(git(self.repository, 'show', ':2:shipping.txt').stdout, 'Shipping: tracked\n')
self.assertEqual(git(self.repository, 'show', ':3:shipping.txt').stdout, 'Shipping: express\n')
def test_commit_refuses_unresolved_index(self):
before = git(self.repository, 'rev-parse', 'HEAD').stdout
result = git(self.repository, 'commit', '-m', 'Must not succeed', check=False)
self.assertNotEqual(result.returncode, 0)
self.assertEqual(git(self.repository, 'rev-parse', 'HEAD').stdout, before)
def test_staging_removes_unmerged_entries_and_preserves_both_requirements(self):
stage_resolution(self.repository)
self.assertEqual(git(self.repository, 'ls-files', '-u').stdout, '')
staged = git(self.repository, 'show', ':shipping.txt').stdout
self.assertEqual(staged, 'Shipping: tracked express\n')
self.assertNotIn('<<<<<<<', staged)
def test_completed_merge_has_both_original_parents(self):
ours = git(self.repository, 'rev-parse', 'main').stdout.strip()
theirs = git(self.repository, 'rev-parse', 'express').stdout.strip()
stage_resolution(self.repository)
complete_merge(self.repository)
parents = git(self.repository, 'rev-list', '--parents', '-n', '1', 'HEAD').stdout.split()
expected_parents = [ours, theirs]
self.assertEqual(parents[1:], expected_parents)
def test_completed_merge_is_clean_and_keeps_combined_content(self):
stage_resolution(self.repository)
complete_merge(self.repository)
self.assertEqual(git(self.repository, 'status', '--porcelain=v1').stdout, '')
self.assertEqual(git(self.repository, 'show', 'HEAD:shipping.txt').stdout, 'Shipping: tracked express\n')
def test_abort_restores_premerge_main(self):
before = git(self.repository, 'rev-parse', 'HEAD').stdout
git(self.repository, 'merge', '--abort')
self.assertEqual(git(self.repository, 'rev-parse', 'HEAD').stdout, before)
self.assertEqual(git(self.repository, 'status', '--porcelain=v1').stdout, '')
self.assertEqual((self.repository / 'shipping.txt').read_text(encoding='utf-8'), 'Shipping: tracked\n')
def test_existing_directory_is_rejected_without_writes(self):
sentinel = self.repository / 'sentinel.txt'
sentinel.write_text('keep me', encoding='utf-8')
before = git(self.repository, 'rev-parse', 'HEAD').stdout
with self.assertRaises(FileExistsError):
build_conflict(self.temporary.name)
self.assertEqual(sentinel.read_text(encoding='utf-8'), 'keep me')
self.assertEqual(git(self.repository, 'rev-parse', 'HEAD').stdout, before)
if __name__ == '__main__':
unittest.main()
The original source and independently extracted ZIP each passed all nine tests and produced the exact demo output shown above. A temporary negative-control copy resolved the file with only the tracked requirement. The content-preservation tests failed even though Git could stage and commit that incomplete resolution.
| Checked state | Expected result |
|---|---|
| Stopped merge | UU status, markers containing both branch changes and all three index stages. |
| Commit before resolution | Nonzero result without moving HEAD. |
| Staged resolution | No unmerged entries; exact tracked express content in the index. |
| Completed merge | Both original parents, correct committed file and clean status. |
| Abort and existing-directory refusal | Pre-merge main restored in the clean fixture; existing sentinel file unchanged. |
Use the workflow, not the fixture paths
This lab intentionally cleans up its repository after printing the result. The temporary path is not a destination for real project work. For an actual conflict, inspect the current repository's status, review the competing edits, choose the intended result, stage only reviewed paths and run the project's meaningful checks before completing the merge.
If the program cannot find git, correct PATH before running it. If init rejects the initial-branch option, check the installed Git version. A nonzero merge exit alone is insufficient evidence of a conflict; missing tools and configuration errors can also fail. The runner therefore requires the expected unmerged file state before proceeding.
Comments (0)
Join the discussion