rich/tools/make_width_tables.py
2026-01-22 15:58:32 +00:00

54 lines
1.7 KiB
Python

import subprocess
from pathlib import Path
from wcwidth import list_versions
from wcwidth.table_vs16 import VS16_NARROW_TO_WIDE
from wcwidth.table_wide import WIDE_EASTASIAN
from wcwidth.table_zero import ZERO_WIDTH
from rich.cells import CellTable
UNICODE_VERSIONS: list[str] = list_versions()
path = Path("../rich/_unicode_data/_versions.py").resolve().absolute()
init = f"""\
VERSIONS = {UNICODE_VERSIONS!r}
"""
with open(path, "wt") as init_file:
init_file.write(init)
subprocess.run(f"black {path}", shell=True)
narrow_to_wide: set[str] = set()
for start, end in VS16_NARROW_TO_WIDE["9.0.0"]:
narrow_to_wide.update(chr(codepoint) for codepoint in range(start, end + 1))
for version in UNICODE_VERSIONS:
table: list[tuple[int, int, int]] = []
wide_east_asian: list[tuple[int, int]] = WIDE_EASTASIAN.get(version, [])
for start, end in wide_east_asian:
table.append((start, end, 2))
zero_wide: list[tuple[int, int]] = ZERO_WIDTH.get(version, [])
for start, end in zero_wide:
table.append((start, end, 0))
table.sort()
cell_table = CellTable(version, table, frozenset(narrow_to_wide))
table_file = f"""# Auto generated by tools/make_width_tables.py
# Data from wcwidth project (https://github.com/jquast/wcwidth)
from rich.cells import CellTable
cell_table = CellTable({cell_table.unicode_version!r}, {cell_table.widths!r}, frozenset({sorted(cell_table.narrow_to_wide)!r}))
"""
version_path = version.replace(".", "-")
path = Path(f"../rich/_unicode_data/unicode{version_path}.py").resolve().absolute()
with open(path, "wt") as file_out:
file_out.write(table_file)
subprocess.run(f"black {path}", shell=True)