Anki/pylib/anki/_backend/genfluent.py
Damien Elmes b9251290ca run pyupgrade over codebase [python upgrade required]
This adds Python 3.9 and 3.10 typing syntax to files that import
attributions from __future___. Python 3.9 should be able to cope with
the 3.10 syntax, but Python 3.8 will no longer work.

On Windows/Mac, install the latest Python 3.9 version from python.org.
There are currently no orjson wheels for Python 3.10 on Windows/Mac,
which will break the build unless you have Rust installed separately.

On Linux, modern distros should have Python 3.9 available already. If
you're on an older distro, you'll need to build Python from source first.
2021-10-04 15:05:48 +10:00

103 lines
2.5 KiB
Python

# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import json
import sys
from typing import List, Literal, TypedDict
import stringcase
strings_json, outfile = sys.argv[1:]
modules = json.load(open(strings_json, encoding="utf8"))
class Variable(TypedDict):
name: str
kind: Literal["Any", "Int", "String", "Float"]
def legacy_enum() -> str:
out = ["class LegacyTranslationEnum:"]
for module in modules:
for translation in module["translations"]:
key = stringcase.constcase(translation["key"])
value = f'({module["index"]}, {translation["index"]})'
out.append(f" {key} = {value}")
return "\n".join(out) + "\n"
def methods() -> str:
out = [
"class GeneratedTranslations:",
" def _translate(self, module: int, translation: int, args: Dict) -> str:",
" raise Exception('not implemented')",
]
for module in modules:
for translation in module["translations"]:
key = translation["key"].replace("-", "_")
arg_types = get_arg_types(translation["variables"])
args = get_args(translation["variables"])
doc = translation["text"]
out.append(
f"""
def {key}(self, {arg_types}) -> str:
r''' {doc} '''
return self._translate({module["index"]}, {translation["index"]}, {{{args}}})
"""
)
return "\n".join(out) + "\n"
def get_arg_types(args: list[Variable]) -> str:
return ", ".join(
[f"{stringcase.snakecase(arg['name'])}: {arg_kind(arg)}" for arg in args]
)
def arg_kind(arg: Variable) -> str:
if arg["kind"] == "Int":
return "int"
elif arg["kind"] == "Any":
return "FluentVariable"
elif arg["kind"] == "Float":
return "float"
else:
return "str"
def get_args(args: list[Variable]) -> str:
return ", ".join(
[f'"{arg["name"]}": {stringcase.snakecase(arg["name"])}' for arg in args]
)
out = ""
out += legacy_enum()
out += methods()
open(outfile, "wb").write(
(
'''# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
# pylint: skip-file
from __future__ import annotations
"""
This file is automatically generated from the *.ftl files.
"""
import enum
from typing import Dict, Union
FluentVariable = Union[str, int, float]
'''
+ out
).encode("utf8")
)