urfu-daddy/scripts/pybabel.py

104 lines
2.4 KiB
Python

# /// script
# requires-python = ">=3.13"
# dependencies = [
# "argparse",
# "pathlib",
# ]
# ///
import argparse
import subprocess
from pathlib import Path
LOCALES_DIR = Path("src/locales")
LOCALES_DOMAIN = "messages"
LOCALES_POT = LOCALES_DIR / f"{LOCALES_DOMAIN}.pot"
LOCALES_WIDTH = 80
def run_cmd(cmds: list[list[str]]) -> None:
try:
for cmd in cmds:
# INFO: User input is safe.
result = subprocess.run( # noqa: S603
cmd,
capture_output=True,
text=True,
check=True,
shell=False,
)
print(result.stderr) # noqa: T201
except Exception as error:
print(f"Error: {error}") # noqa: T201
def main() -> None:
parser = argparse.ArgumentParser(
description="Wrapper for pybabel operations."
)
parser.add_argument(
"operation",
choices=["extract", "update", "compile", "init"],
help="Type of pybabel operation.",
)
parser.add_argument(
"language",
nargs="?",
default="all",
choices=["ru", "en", "zh", "es", "ar", "fr", "de", "all"],
help=""
+ "Language code. "
+ "If omitted, all locales are processed. "
+ "Only for update & compile operations.",
)
args = parser.parse_args()
if args.operation == "init" and args.language == "all":
print("Error: You need to specify new language.") # noqa: T201
return
cmd = list()
cmd.append("pybabel")
cmd.append(args.operation)
if args.operation == "extract":
cmd.append(".")
cmd.append("-o")
cmd.append(str(LOCALES_POT))
run_cmd([cmd])
return
cmd.append("-D")
cmd.append(LOCALES_DOMAIN)
cmd.append("-d")
cmd.append(str(LOCALES_DIR))
if args.operation in ("update", "init"):
cmd.append("-i")
cmd.append(str(LOCALES_POT))
if args.operation == "update":
cmd.append("-w")
cmd.append(str(LOCALES_WIDTH))
if args.language == "all":
langs = [
str(path_name.name)
for path_name in LOCALES_DIR.iterdir()
if path_name.is_dir()
]
else:
langs = [args.language]
cmds = [cmd + ["-l"] + [lang] for lang in langs]
run_cmd(cmds)
if __name__ == "__main__":
main()