1# Copyright 2016-2016 the openage authors. See copying.md for legal info.
2
3"""
4Generates libopenage/coord/coord_{xy, xyz, ne_se, ne_se_up}.{h, cpp}
5"""
6
7from jinja2 import Template
8
9
10def generate_coord_basetypes(projectdir):
11    """
12    Generates the test/demo method symbol lookup file from tests_cpp.
13
14    projectdir is a util.fslike.path.Path.
15    """
16    # this list contains all required member lists.
17    member_lists = [
18        ["x", "y"],
19        ["x", "y", "z"],
20        ["ne", "se"],
21        ["ne", "se", "up"]
22    ]
23
24    # this list maps template file name to output file name.
25    # the output filename is a jinja2 template itself.
26    template_files_spec = [
27        ("libopenage/coord/coord.h.template",
28         "libopenage/coord/coord_{{ ''.join(members) }}.gen.h"),
29        ("libopenage/coord/coord.cpp.template",
30         "libopenage/coord/coord_{{ ''.join(members) }}.gen.cpp")
31    ]
32
33    templates = []
34    for template_filename, output_filename in template_files_spec:
35        with projectdir.joinpath(template_filename).open() as template_file:
36            templates.append((
37                Template(template_file.read()),
38                Template(output_filename)
39            ))
40
41    for member_list in member_lists:
42        def format_members(formatstring, join_with=", "):
43            """
44            For being called by the template engine.
45
46            >>> format_members("{0} = {0}")
47            "x = x, y = y"
48            """
49            return join_with.join(formatstring.format(m) for m in member_list)
50
51        template_dict = dict(
52            members=member_list,
53            formatted_members=format_members,
54            camelcase="".join(member.title() for member in member_list),
55        )
56
57        for template, output_filename_template in templates:
58            output_filename = output_filename_template.render(template_dict)
59            with projectdir.joinpath(output_filename).open("w") as output_file:
60                output = template.render(template_dict)
61                output_file.write(output)
62                if not output.endswith('\n'):
63                    output_file.write('\n')
64