~coder_kalyan/svdg

159fac30fa6d900c53d7beabd0afa32ce83dd976 — Kalyan Sriram 3 years ago 0d3cb62 master
generate: add generation capabilities
4 files changed, 71 insertions(+), 3 deletions(-)

A iter.py
M requirements.txt
M svdg/__main__.py
A svdg/generate.py
A iter.py => iter.py +6 -0
@@ 0,0 1,6 @@
#
# Copyright (C) 2021 Kalyan Sriram <kalyan@coderkalyan.com>
# This software is distributed under the terms of the MIT License.
#



M requirements.txt => requirements.txt +1 -1
@@ 1,3 1,3 @@
jinja2
cmsis-svd
click
git+https://git.sr.ht/~coder_kalyan/svd-py#svd

M svdg/__main__.py => svdg/__main__.py +11 -2
@@ 3,12 3,21 @@
# This software is distributed under the terms of the MIT License.
#

import os

import click

from .version import __version__
from .generate import generate


@click.command()
def main():
    click.echo("Hi")
@click.version_option(__version__)
@click.argument("definition")
@click.option('-t', "--template", required=True)
@click.option('-o', "--output", required=False, default=os.getcwd())
def main(definition, template, output):
    generate(definition_file=definition, template_dir=template, output_dir=output)


if __name__ == "__main__":

A svdg/generate.py => svdg/generate.py +53 -0
@@ 0,0 1,53 @@
#
# Copyright (C) 2021 Kalyan Sriram <kalyan@coderkalyan.com>
# This software is distributed under the terms of the MIT License.
#

import os
import importlib

import jinja2
import svd


def generate(definition_file, template_dir, output_dir):
    with open(definition_file, "r") as f:
        definition = f.read()

    device = svd.Parser.convert(definition)

    context_file = os.path.join(template_dir, "__context__.py")
    if os.path.exists(context_file):
        spec = importlib.util.spec_from_file_location("module.name", context_file)
        module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(module)

        env = module.get_env()
    else:
        env = jinja2.Environment()

    for root, dirs, files in os.walk(template_dir):
        base = root.lstrip(template_dir).lstrip(os.sep)
        for d in dirs:
            try:
                os.mkdir(os.path.join(output_dir, base, d))
            except FileExistsError:
                pass

        for file in files:
            if root == template_dir and file == "__context__.py":
                continue
            if file in ["__pycache__"]:
                continue
            if os.path.splitext(file)[1] in [".pyc"]:
                continue

            with open(os.path.join(root, file), "r") as f:
                content = f.read()

            template = env.from_string(content)
            generated = template.render(device=device)

            outfile = os.path.join(output_dir, base, file)
            with open(outfile, "w") as f:
                f.write(generated)