| 1 |
#!/usr/bin/env python |
| 2 |
# -*- coding: UTF-8 -*- |
| 3 |
# USAGE: convert_i18n_yaml.py [--data=i18n.yml] behave/i18n.py |
| 4 |
""" |
| 5 |
Generates I18N python module based on YAML description (i18n.yml). |
| 6 |
|
| 7 |
REQUIRES: |
| 8 |
* argparse |
| 9 |
* six |
| 10 |
* PyYAML |
| 11 |
""" |
| 12 |
|
| 13 |
from __future__ import absolute_import, print_function |
| 14 |
import argparse |
| 15 |
import os.path |
| 16 |
import six |
| 17 |
import sys |
| 18 |
import pprint |
| 19 |
import yaml |
| 20 |
|
| 21 |
HERE = os.path.dirname(__file__) |
| 22 |
NAME = os.path.basename(__file__) |
| 23 |
__version__ = "1.0" |
| 24 |
|
| 25 |
def yaml_normalize(data): |
| 26 |
for part in data: |
| 27 |
keywords = data[part] |
| 28 |
for k in keywords: |
| 29 |
v = keywords[k] |
| 30 |
# bloody YAML parser returns a mixture of unicode and str |
| 31 |
if not isinstance(v, six.text_type): |
| 32 |
v = v.decode("UTF-8") |
| 33 |
keywords[k] = v.split("|") |
| 34 |
return data |
| 35 |
|
| 36 |
def main(args=None): |
| 37 |
if args is None: |
| 38 |
args = sys.argv[1:] |
| 39 |
parser = argparse.ArgumentParser(prog=NAME, |
| 40 |
description="Generate python module i18n from YAML based data") |
| 41 |
parser.add_argument("-d", "--data", dest="yaml_file", |
| 42 |
default=os.path.join(HERE, "i18n.yml"), |
| 43 |
help="Path to i18n.yml file (YAML file).") |
| 44 |
parser.add_argument("output_file", default="stdout", |
| 45 |
help="Filename of Python I18N module (as output).") |
| 46 |
parser.add_argument("--version", action="version", version=__version__) |
| 47 |
|
| 48 |
options = parser.parse_args(args) |
| 49 |
if not os.path.isfile(options.yaml_file): |
| 50 |
parser.error("YAML file not found: %s" % options.yaml_file) |
| 51 |
|
| 52 |
# -- STEP 1: Load YAML data. |
| 53 |
languages = yaml.load(open(options.yaml_file)) |
| 54 |
languages = yaml_normalize(languages) |
| 55 |
|
| 56 |
# -- STEP 2: Generate python module with i18n data. |
| 57 |
contents = u"""# -*- coding: UTF-8 -*- |
| 58 |
# -- FILE GENERATED BY: convert_i18n_yaml.py with i18n.yml |
| 59 |
# pylint: disable=line-too-long |
| 60 |
|
| 61 |
languages = \\ |
| 62 |
""" |
| 63 |
if options.output_file in ("-", "stdout"): |
| 64 |
i18n_py = sys.stdout |
| 65 |
should_close = False |
| 66 |
else: |
| 67 |
i18n_py = open(options.output_file, "w") |
| 68 |
should_close = True |
| 69 |
i18n_py.write(contents.encode("UTF-8")) |
| 70 |
i18n_py.write(pprint.pformat(languages).encode("UTF-8")) |
| 71 |
i18n_py.write(u"\n") |
| 72 |
if should_close: |
| 73 |
i18n_py.close() |
| 74 |
return 0 |
| 75 |
|
| 76 |
if __name__ == "__main__": |
| 77 |
sys.exit(main()) |