"""CRLF-safe exact-replace helper. Usage from other scripts:
    from crlfpatch import patch
    patch(path, [(old, new), ...])
Each `old` must occur EXACTLY once (LF-normalized). Writes back with the
file's original line endings (CRLF if the file had any CR)."""
import sys


def patch(path, edits):
    raw = open(path, 'rb').read()
    crlf = b'\r\n' in raw
    text = raw.decode('utf-8').replace('\r\n', '\n')
    for i, (old, new) in enumerate(edits):
        n = text.count(old)
        if n != 1:
            sys.exit(f"{path}: edit {i} matched {n} times (need 1): {old[:80]!r}")
        text = text.replace(old, new)
    if crlf:
        text = text.replace('\n', '\r\n')
    open(path, 'wb').write(text.encode('utf-8'))
    print(f"patched {path}: {len(edits)} edit(s), crlf={crlf}")
