File: cpp_generator.py

package info (click to toggle)
libkgapi 25.08.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,408 kB
  • sloc: cpp: 37,386; ansic: 977; python: 671; xml: 58; makefile: 16; sh: 1
file content (44 lines) | stat: -rw-r--r-- 1,388 bytes parent folder | download | duplicates (3)
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
# SPDX-FileCopyrightText: 2021 Daniel Vrátil <dvratil@kde.org>
#
# SPDX-License-Identifier: LGPL-2.1-only
# SPDX-License-Identifier: LGPL-3.0-only
# SPDX-License-Identifier: LicenseRef-KDE-Accepted-LGPL

import os
import pathlib
from datetime import datetime
from jinja2 import Environment, FileSystemLoader, select_autoescape

from schema_types import Object


class Generator:
    """
    Generates C++ code for given schema.
    """

    def __init__(self, api, outdir):
        self._env = Environment(
            loader=FileSystemLoader(
                f"{pathlib.Path(__file__).parent.resolve()}/templates/"
            ),
            autoescape=select_autoescape(),
        )
        self._api = api
        self._outdir = outdir
        os.makedirs(outdir, exist_ok=True)

        self._api["date"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S %z")

    def generate_schema(self, schema: Object):
        template_base = "object"
        if schema.name in self._api["kgapiobjects"]:
            template_base = "kgapiobject"

        filename = schema.name.lower()
        for ext in ["h", "cpp"]:
            with open(
                os.path.join(self._outdir, f"{filename}.{ext}"), "w"
            ) as output_file:
                template = self._env.get_template(f"{template_base}.{ext}")
                output_file.write(template.render(api=self._api, schema=schema))