"""Replaces .tox/ paths in the lcov file with paths relative to repo root.

Context: When the CI build runs tests, it uses tox, which installs SQLFluff
in a virtual environment. Thus, the coverage.lcov file generated by the tests
contains paths to the virtual environment. This script replaces those paths
with paths relative to the repo root. This allows the lcov file to be used by
Coveralls. Without this, Coveralls has valid coverage info, but it generates
URLs that point to source files that don't exist in the SQLFluff GitHub repo.

For example, we want to change this:
SF:.tox/py/lib/python3.10/site-packages/sqlfluff/__init__.py

to this:
SF:src/sqlfluff/__init__.py
"""

import re
from pathlib import Path

path = Path("coverage.lcov")
if path.exists():
    lines = path.read_text().splitlines()
    modified_lines = []
    for line in lines:
        if line.startswith("SF:.tox"):
            m = re.search(r"^(SF:).*(sqlfluff/.*)", line)
            if m:
                modified_lines.append(f"{m.group(1)}src/{m.group(2)}")
            else:
                print(f"Could not patch line: {line}")
                modified_lines.append(line)
        else:
            modified_lines.append(line)
    path.write_text("\n".join(modified_lines))
