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.

Easy Python 3.9+ Aug 9, 2026 Git + Python 14 views 0 copies

Python code

44 lines
Python 3.9+
from 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

stdout
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

  1. Return a list of dictionaries with `line`, `type`, and `content` for easier downstream processing.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Git + Python

Related tutorials and quizzes for this topic.