| 1 |
import json |
| 2 |
from urllib.request import urlopen |
| 3 |
|
| 4 |
from babel.core import get_cldr_version |
| 5 |
from babel.localedata import locale_identifiers |
| 6 |
|
| 7 |
|
| 8 |
def write_dict(data): |
| 9 |
ids = set(locale_identifiers()) |
| 10 |
ids |= {l.partition("_")[0] for l in ids} |
| 11 |
|
| 12 |
print("PLURALS: dict[str, tuple[int, str]] = {") |
| 13 |
for key, info in sorted(data.items()): |
| 14 |
if key not in ids: |
| 15 |
continue |
| 16 |
|
| 17 |
n = info['plurals'] |
| 18 |
formula = info['formulas']['standard'] |
| 19 |
if not formula.isdigit() and "(" not in formula: |
| 20 |
formula = f"({formula})" |
| 21 |
tup = (n, formula) |
| 22 |
# We could be tempted to compare to `DEFAULT_PLURAL` |
| 23 |
# here and emit a reference to it, but CPython is |
| 24 |
# smart enough to do constant folding on constant tuples: |
| 25 |
# >>> p.PLURALS["ak"] is p.PLURALS["am"] |
| 26 |
# True |
| 27 |
# so it actually becomes cheaper to emit these tuples, |
| 28 |
# and avoid loading global values when the dict is |
| 29 |
# being constructed. |
| 30 |
# It also doesn't feel right to not emit DEFAULT_PLURAL |
| 31 |
# valued items, because then we'd spend more time doing |
| 32 |
# the fallback logic in `get_plural`. |
| 33 |
print(f" # {info['name']}") |
| 34 |
print(f" {key!r}: {tup!r},") |
| 35 |
print("} # fmt: skip") |
| 36 |
|
| 37 |
def main() -> None: |
| 38 |
# The PHP-Gettext project has more concise/optimal gettext conversions of the CLDR rules |
| 39 |
# than what our `_GettextCompiler` (correct, but not optimal) generates, so let's use those. |
| 40 |
|
| 41 |
version = get_cldr_version() |
| 42 |
if version == "48": # get_cldr_version only emits the major version |
| 43 |
version = "48.1" |
| 44 |
with urlopen(f"https://php-gettext.github.io/Languages/data/versions/{version}.json") as fp: |
| 45 |
data = json.loads(fp.read().decode('utf-8')) |
| 46 |
|
| 47 |
write_dict(data) |
| 48 |
|
| 49 |
|
| 50 |
if __name__ == '__main__': |
| 51 |
main() |