File: _convert.py

package info (click to toggle)
sphinx-togglebutton 0.4.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 444 kB
  • sloc: javascript: 198; python: 143; makefile: 18
file content (65 lines) | stat: -rw-r--r-- 1,851 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import json
import os
import subprocess
from pathlib import Path

MESSAGE_CATALOG_NAME = "togglebutton"


def convert_json(folder=None):
    folder = folder or Path(__file__).parent

    # remove exising
    for path in (folder / "locales").glob(f"**/{MESSAGE_CATALOG_NAME}.po"):
        path.unlink()

    # compile po
    for path in (folder / "jsons").glob("*.json"):
        data = json.loads(path.read_text("utf8"))
        assert data[0]["symbol"] == "en"
        english = data[0]["text"]
        for item in data[1:]:
            language = item["symbol"]
            out_path = (
                folder
                / "locales"
                / language
                / "LC_MESSAGES"
                / f"{MESSAGE_CATALOG_NAME}.po"
            )
            if not out_path.parent.exists():
                out_path.parent.mkdir(parents=True)
            if not out_path.exists():
                header = f"""
msgid ""
msgstr ""
"Project-Id-Version: Sphinx-ToggleButton\\n"
"MIME-Version: 1.0\\n"
"Content-Type: text/plain; charset=UTF-8\\n"
"Content-Transfer-Encoding: 8bit\\n"
"Language: {language}\\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\\n"
"""
                out_path.write_text(header)

            with out_path.open("a", encoding="utf8") as f:
                f.write("\n")
                f.write(f'msgid "{english}"\n')
                text = item["text"].replace('"', '\\"')
                f.write(f'msgstr "{text}"\n')

    # compile mo
    for path in (folder / "locales").glob(f"**/{MESSAGE_CATALOG_NAME}.po"):
        print(path)
        subprocess.check_call(
            [
                "msgfmt",
                os.path.abspath(path),
                "-o",
                os.path.abspath(path.parent / f"{MESSAGE_CATALOG_NAME}.mo"),
            ]
        )


if __name__ == "__main__":
    convert_json()