Skip to content

Documentation for tasks module

normalize.py

This module contains functions for normalizing i18n localization files.

__perform_normalize(locales, locale_path)

private method to perform normalization, should not be called directly

Source code in pyi18n/tasks/normalize.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def __perform_normalize(locales: set, locale_path: str) -> None:
    """ private method to perform normalization,
        should not be called directly"""

    for subclass in loaders.PyI18nBaseLoader.__subclasses__():
        if subclass.__name__ == "PyI18nXMLLoader" \
         and environ["PYI18N_TEST_ENV"]:
            continue

        loader: loaders.PyI18nBaseLoader = subclass(locale_path)
        content: dict = loader.load(locales)

        sorted_content: dict = __sort_nested(content)

        __save_normalized(locales, loader,
                          locale_path, sorted_content)

__save_normalized(locales, loader, locale_path, sorted_content)

private function to save the normalized content, should not be called directly.

Source code in pyi18n/tasks/normalize.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def __save_normalized(
                    locales: set,
                    loader: loaders.PyI18nBaseLoader,
                    locale_path: str,
                    sorted_content: dict
                    ) -> None:
    """ private function to save the normalized content,
        should not be called directly."""

    ext: str = loader.type().replace('yaml', 'yml')
    dumper: str = {
        "json": lambda x, y: json_dump(x, y, indent=4, sort_keys=True),
        "yml": yaml_dump,
        "xml": lambda x, _: xml_dump(x, pretty=True)
    }

    for locale in locales:
        file_path: str = f"{locale_path}{locale}.{ext}"
        with open(file_path, "w", encoding="utf-8") as _f:
            dumper[ext]({locale: sorted_content[locale]}, _f)

__sort_nested(dictionary)

private function to sort nested dictionaries

Source code in pyi18n/tasks/normalize.py
73
74
75
def __sort_nested(dictionary: dict) -> dict:
    """ private function to sort nested dictionaries """
    return {k: dict(sorted(v.items())) for k, v in dictionary.items()}

normalize_locales(locale_path='locales/')

Sorts the keys in alphabetically order, and overrides files

Source code in pyi18n/tasks/normalize.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def normalize_locales(locale_path: str = "locales/") -> dict:
    """ Sorts the keys in alphabetically order, and overrides files """

    locale_path: str = f"{getcwd()}/{locale_path}"
    if not exists(locale_path):
        print(f"[ERROR] {locale_path} does not exist")
        exit(1)

    locales: set = set([x.split('.')[0] for x in listdir(locale_path)])

    if not locales:
        print(f"[ERROR] {locale_path} is empty")
        exit(1)

    __perform_normalize(locales, locale_path)