Detect Merge Conflict Markers in a File with Python
Scan a file line by line to detect Git merge conflict markers (<<<<<<<, =======, >>>>>>>) and report their line numbers with context.
Python code
44 linesfrom pathlib import Path
def detect_merge_conflicts(file_path):
conflicts = []
with open(file_path, 'r') as f:
lines = f.readlines()
for i, line in enumerate(lines, 1):
if line.startswith('<<<<<<<'):
conflict_marker = 'conflict start'
conflicts.append((i, conflict_marker, line.strip()))
elif line.startswith('======='):
conflict_marker = 'divider'
conflicts.append((i, conflict_marker, line.strip()))
elif line.startswith('>>>>>>>'):
conflict_marker = 'conflict end'
conflicts.append((i, conflict_marker, line.strip()))
return conflicts
if __name__ == "__main__":
import sys
sample = """line1
<<<<<<< HEAD
my changes
=======
their changes
>>>>>>> branch-name
line5"""
# Write sample to temp file (alternative: use provided path instead)
from tempfile import NamedTemporaryFile
with NamedTemporaryFile('w', suffix='.txt', delete=False) as tmp:
tmp.write(sample)
tmp_path = tmp.name
conflict_lines = detect_merge_conflicts(tmp_path)
Path(tmp_path).unlink() # cleanup
if conflict_lines:
for line_num, marker, content in conflict_lines:
print(f"Line {line_num}: {marker} ({content})")
else:
print("No merge conflicts found")
Output
Line 2: conflict start (<<<<<<< HEAD)
Line 3: divider (=======)
Line 4: conflict end (>>>>>>> branch-name)
How it works
The function reads the file line by line and checks whether each line starts with a known conflict marker. Because markers always appear at the start of a line, using str.startswith is a reliable and simple detection method. Each detected marker is stored as a tuple of line number and marker type, and the results are printed in order. The __main__ block writes a sample conflict to a temporary file to demonstrate the detector, then cleans up with Path.unlink.
Common mistakes
- Using `in` instead of `startswith`, which may match markers appearing in the middle of a line.
- Forgetting to handle files that don't exist, causing an unhandled FileNotFoundError.
- Not stripping the trailing newline when printing or storing the marker content.
Variations
- Return a list of dictionaries with `line`, `type`, and `content` for easier downstream processing.
- Use a regex to also detect markers with whitespace before them.
Real-world use cases
- Automating pre-commit checks to block files that still contain unresolved conflict markers.
- Generating a detailed report for a merge bot to list all conflicting sections in changed files.
- Validating repository files after a bulk merge operation to ensure no accidental markers remain.
Sponsored
More from Git + Python
- Amend Last Commit Message in Python easy
- Bisect Good Bad Automation Script in Python easy
- Build a Simple Log Graph in Python easy
- Bump Semantic Version Git Tag in Python easy
- Count Unique Contributors from Git Shortlog in Python easy
- Create a Mock GitHub Release API in Python for Testing gh CLI easy
Keep learning
Related tutorials and quizzes for this topic.