| 1 |
#!/usr/bin/env python |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import glob |
| 6 |
import json |
| 7 |
import os |
| 8 |
|
| 9 |
from babel.core import get_global |
| 10 |
from babel.dates import PATTERN_CHARS |
| 11 |
from babel.dates import tokenize_pattern |
| 12 |
from babel.localedata import LocaleDataDict |
| 13 |
from babel.localedata import load |
| 14 |
from babel.localedata import normalize_locale |
| 15 |
from babel.plural import PluralRule |
| 16 |
from babel.plural import _binary_compiler |
| 17 |
from babel.plural import _GettextCompiler |
| 18 |
from babel.plural import _unary_compiler |
| 19 |
from babel.plural import compile_zero |
| 20 |
from cleo.application import Application |
| 21 |
from cleo.commands.command import Command |
| 22 |
from cleo.helpers import argument |
| 23 |
|
| 24 |
from pendulum import __version__ |
| 25 |
|
| 26 |
|
| 27 |
class _LambdaCompiler(_GettextCompiler): |
| 28 |
"""Compiles the expression to lambda function.""" |
| 29 |
|
| 30 |
compile_v = compile_zero |
| 31 |
compile_w = compile_zero |
| 32 |
compile_f = compile_zero |
| 33 |
compile_t = compile_zero |
| 34 |
compile_and = _binary_compiler("(%s and %s)") |
| 35 |
compile_or = _binary_compiler("(%s or %s)") |
| 36 |
compile_not = _unary_compiler("(not %s)") |
| 37 |
compile_mod = _binary_compiler("(%s %% %s)") |
| 38 |
|
| 39 |
def compile_relation(self, method, expr, range_list): |
| 40 |
code = _GettextCompiler.compile_relation(self, method, expr, range_list) |
| 41 |
code = code.replace("&&", "and") |
| 42 |
code = code.replace("||", "or") |
| 43 |
if method == "in": |
| 44 |
expr = self.compile(expr) |
| 45 |
code = f"({expr} == {expr} and {code})" |
| 46 |
return code |
| 47 |
|
| 48 |
|
| 49 |
class LocaleCreate(Command): |
| 50 |
name = "locale create" |
| 51 |
description = "Creates locale translations." |
| 52 |
|
| 53 |
arguments = [argument("locales", "Locales to dump.", optional=False, multiple=True)] |
| 54 |
|
| 55 |
TEMPLATE = """from .custom import translations as custom_translations |
| 56 |
|
| 57 |
|
| 58 |
\"\"\" |
| 59 |
{locale} locale file. |
| 60 |
|
| 61 |
It has been generated automatically and must not be modified directly. |
| 62 |
\"\"\" |
| 63 |
|
| 64 |
|
| 65 |
locale = {{ |
| 66 |
'plural': {plural}, |
| 67 |
'ordinal': {ordinal}, |
| 68 |
'translations': {translations}, |
| 69 |
'custom': custom_translations |
| 70 |
}} |
| 71 |
""" |
| 72 |
|
| 73 |
CUSTOM_TEMPLATE = """\"\"\" |
| 74 |
{locale} custom locale file. |
| 75 |
\"\"\" |
| 76 |
|
| 77 |
translations = {{}} |
| 78 |
""" |
| 79 |
|
| 80 |
LOCALE_DIR = os.path.join("pendulum", "locales") |
| 81 |
|
| 82 |
def handle(self): |
| 83 |
locales = self.argument("locales") |
| 84 |
if not locales: |
| 85 |
return |
| 86 |
|
| 87 |
for locale in locales: |
| 88 |
data = {} |
| 89 |
parts = locale.split("-") |
| 90 |
if len(parts) > 1: |
| 91 |
parts[1] = parts[1].upper() |
| 92 |
|
| 93 |
normalized = normalize_locale(locale.replace("-", "_")) |
| 94 |
if not normalized: |
| 95 |
self.line(f"<error>Locale [{locale}] does not exist.</error>") |
| 96 |
continue |
| 97 |
|
| 98 |
self.line(f"<info>Generating <comment>{locale}</> locale.</>") |
| 99 |
|
| 100 |
content = LocaleDataDict(load(normalized)) |
| 101 |
|
| 102 |
# Pluralization rule |
| 103 |
rule = content["plural_form"] |
| 104 |
plural = self.plural_rule_to_lambda(rule) |
| 105 |
|
| 106 |
# Ordinal rule |
| 107 |
rule = content["ordinal_form"] |
| 108 |
ordinal = self.plural_rule_to_lambda(rule) |
| 109 |
|
| 110 |
# Getting days names |
| 111 |
days = content["days"]["format"] |
| 112 |
data["days"] = {} |
| 113 |
for fmt, names in days.items(): |
| 114 |
data["days"][fmt] = {} |
| 115 |
for value, name in sorted(names.items()): |
| 116 |
data["days"][fmt][value] = name |
| 117 |
|
| 118 |
# Getting months names |
| 119 |
months = content["months"]["format"] |
| 120 |
data["months"] = months |
| 121 |
|
| 122 |
# Units |
| 123 |
patterns = content["unit_patterns"] |
| 124 |
units = [ |
| 125 |
"year", |
| 126 |
"month", |
| 127 |
"week", |
| 128 |
"day", |
| 129 |
"hour", |
| 130 |
"minute", |
| 131 |
"second", |
| 132 |
"microsecond", |
| 133 |
] |
| 134 |
data["units"] = {} |
| 135 |
for unit in units: |
| 136 |
pattern = patterns[f"duration-{unit}"]["long"] |
| 137 |
if "per" in pattern: |
| 138 |
del pattern["per"] |
| 139 |
|
| 140 |
data["units"][unit] = pattern |
| 141 |
|
| 142 |
# Relative |
| 143 |
data["relative"] = {} |
| 144 |
for key in content["date_fields"]: |
| 145 |
if key not in [ |
| 146 |
"year", |
| 147 |
"month", |
| 148 |
"week", |
| 149 |
"day", |
| 150 |
"hour", |
| 151 |
"minute", |
| 152 |
"second", |
| 153 |
]: |
| 154 |
continue |
| 155 |
|
| 156 |
data["relative"][key] = content["date_fields"][key] |
| 157 |
|
| 158 |
# Day periods |
| 159 |
data["day_periods"] = content["day_periods"]["format"]["wide"] |
| 160 |
|
| 161 |
# Week data |
| 162 |
data["week_data"] = content["week_data"] |
| 163 |
|
| 164 |
result = self.TEMPLATE.format( |
| 165 |
locale=locale, |
| 166 |
plural=plural, |
| 167 |
ordinal=ordinal, |
| 168 |
translations=self.format_dict(data, tab=2), |
| 169 |
) |
| 170 |
|
| 171 |
dest_dir = os.path.join(self.LOCALE_DIR, locale.replace("-", "_")) |
| 172 |
if not os.path.exists(dest_dir): |
| 173 |
os.mkdir(dest_dir) |
| 174 |
|
| 175 |
init = os.path.join(dest_dir, "__init__.py") |
| 176 |
main = os.path.join(dest_dir, "locale.py") |
| 177 |
custom = os.path.join(dest_dir, "custom.py") |
| 178 |
|
| 179 |
if not os.path.exists(init): |
| 180 |
with open(init, "w"): |
| 181 |
os.utime(init) |
| 182 |
|
| 183 |
with open(main, "w") as fw: |
| 184 |
fw.write(result) |
| 185 |
|
| 186 |
if not os.path.exists(custom): |
| 187 |
with open(custom, "w") as fw: |
| 188 |
fw.write(self.CUSTOM_TEMPLATE.format(locale=locale)) |
| 189 |
|
| 190 |
def format_dict(self, d, tab=1): |
| 191 |
s = ["{\n"] |
| 192 |
for k, v in d.items(): |
| 193 |
v = ( |
| 194 |
self.format_dict(v, tab + 1) |
| 195 |
if isinstance(v, (dict, LocaleDataDict)) |
| 196 |
else repr(v) |
| 197 |
) |
| 198 |
|
| 199 |
s.append(f"{' ' * tab}{k!r}: {v},\n") |
| 200 |
s.append(f"{' ' * (tab - 1)}}}") |
| 201 |
|
| 202 |
return "".join(s) |
| 203 |
|
| 204 |
def plural_rule_to_lambda(self, rule): |
| 205 |
to_py = _LambdaCompiler().compile |
| 206 |
result = ["lambda n: "] |
| 207 |
for tag, ast in PluralRule.parse(rule).abstract: |
| 208 |
result.append(f"'{tag}' if {to_py(ast)} else ") |
| 209 |
result.append("'other'") |
| 210 |
return "".join(result) |
| 211 |
|
| 212 |
def convert_ldml_format(self, fmt): |
| 213 |
result = [] |
| 214 |
|
| 215 |
for tok_type, tok_value in tokenize_pattern(fmt): |
| 216 |
if tok_type == "chars": |
| 217 |
result.append(tok_value.replace("%", "%%")) |
| 218 |
elif tok_type == "field": |
| 219 |
fieldchar, fieldnum = tok_value |
| 220 |
limit = PATTERN_CHARS[fieldchar] |
| 221 |
if limit and fieldnum not in limit: |
| 222 |
raise ValueError( |
| 223 |
f"Invalid length for field: {(fieldchar * fieldnum)!r}" |
| 224 |
) |
| 225 |
result.append( |
| 226 |
self.TOKENS_MAP.get(fieldchar * fieldnum, fieldchar * fieldnum) |
| 227 |
) |
| 228 |
else: |
| 229 |
raise NotImplementedError(f"Unknown token type: {tok_type}") |
| 230 |
|
| 231 |
return "".join(result) |
| 232 |
|
| 233 |
|
| 234 |
class LocaleRecreate(Command): |
| 235 |
name = "locale recreate" |
| 236 |
description = "Recreate existing locales." |
| 237 |
|
| 238 |
def handle(self): |
| 239 |
# Listing locales |
| 240 |
|
| 241 |
locales_dir = os.path.join("pendulum", "locales") |
| 242 |
locales = glob.glob(os.path.join(locales_dir, "*", "locale.py")) |
| 243 |
locales = [os.path.basename(os.path.dirname(locale)) for locale in locales] |
| 244 |
|
| 245 |
self.call("locale create", "locales " + " ".join(locales)) |
| 246 |
|
| 247 |
|
| 248 |
class WindowsTzDump(Command): |
| 249 |
name = "windows dump-timezones" |
| 250 |
description = "Dumps the mapping of Windows timezones to IANA timezones." |
| 251 |
|
| 252 |
MAPPING_DIR = os.path.join("pendulum", "tz", "data") |
| 253 |
|
| 254 |
def handle(self): |
| 255 |
raw_tznames = get_global("windows_zone_mapping") |
| 256 |
sorted_names = sorted(raw_tznames.keys()) |
| 257 |
|
| 258 |
tznames = {} |
| 259 |
for name in sorted_names: |
| 260 |
tznames[name] = raw_tznames[name] |
| 261 |
|
| 262 |
mapping = json.dumps(tznames, indent=4).replace('"', "'") |
| 263 |
|
| 264 |
with open(os.path.join(self.MAPPING_DIR, "windows.py"), "w") as f: |
| 265 |
f.write(f"windows_timezones = {mapping}\n") |
| 266 |
|
| 267 |
|
| 268 |
app = Application("clock", __version__) |
| 269 |
app.add(LocaleCreate()) |
| 270 |
app.add(LocaleRecreate()) |
| 271 |
app.add(WindowsTzDump()) |
| 272 |
|
| 273 |
|
| 274 |
if __name__ == "__main__": |
| 275 |
app.run() |