Project: pygitweb
"""Shared text helpers used by git tooling and the web UI."""
from __future__ import annotations
# Fallback encoding when bytes are not valid UTF-8 (gitweb: $fallback_encoding)
FALLBACK_ENCODING = "latin1"
def to_utf8(s: str | bytes | None) -> str | None:
"""Decode to UTF-8 string; use fallback encoding if not valid UTF-8. Port of to_utf8."""
if s is None:
return None
if isinstance(s, str):
return s
try:
return s.decode("utf-8")
except UnicodeDecodeError:
return s.decode(FALLBACK_ENCODING, errors="replace")