Reintroduce jinja2

This commit is contained in:
Joe Rickerby
2020-05-02 09:59:55 +01:00
parent 4f75eaabcd
commit c38bc9064a
2 changed files with 47 additions and 15 deletions
+16 -5
View File
@@ -1,18 +1,29 @@
import os import os
import io import io
from typing import List, Tuple import jinja2
from typing import Union, Dict, Any
FilesDict = Dict[str, Union[str, jinja2.Template]]
class TemplateProject: class TemplateProject:
files: List[Tuple[str, str]] default_files: FilesDict = {}
files: FilesDict
context: Dict[str, Any]
def __init__(self, files): def __init__(self, *, extra_files: FilesDict):
self.files = files self.files = self.default_files.copy()
self.files.update(extra_files)
self.context = {}
def generate(self, path): def generate(self, path):
for filename, content in self.files: for filename, content in self.files.items():
file_path = os.path.join(path, filename) file_path = os.path.join(path, filename)
os.makedirs(os.path.dirname(file_path), exist_ok=True) os.makedirs(os.path.dirname(file_path), exist_ok=True)
with io.open(file_path, 'w', encoding='utf8') as f: with io.open(file_path, 'w', encoding='utf8') as f:
if isinstance(content, jinja2.Template):
content = content.render(self.context)
f.write(content) f.write(content)
+31 -10
View File
@@ -1,26 +1,30 @@
import textwrap import textwrap
import jinja2
from .base import TemplateProject
def indent(str, level):
return str
def CTemplateProject(TemplateProject): class CTemplateProject(TemplateProject):
files = { default_files = {
'spam.c': textwrap.dedent(fr''' 'spam.c': jinja2.Template(textwrap.dedent(r'''
#include <Python.h> #include <Python.h>
{spam_c_top_level_add} {{ spam_c_top_level_add }}
static PyObject * static PyObject *
spam_system(PyObject *self, PyObject *args) spam_system(PyObject *self, PyObject *args)
{{ {
const char *command; const char *command;
int sts; int sts;
if (!PyArg_ParseTuple(args, "s", &command)) if (!PyArg_ParseTuple(args, "s", &command))
return NULL; return NULL;
sts = system(command); sts = system(command);
{indent(spam_c_function_add, 4)}
{{ spam_c_function_add | indent(4) }}
return PyLong_FromLong(sts); return PyLong_FromLong(sts);
}} }
/* Module initialization */ /* Module initialization */
@@ -56,5 +60,22 @@ def CTemplateProject(TemplateProject):
MOD_RETURN(m) MOD_RETURN(m)
} }
''') ''')),
'setup.py': jinja2.Template(textwrap.dedent(r'''
from setuptools import setup, Extension
{{ setup_py_add }}
setup(
name="spam",
ext_modules=[Extension("spam", sources=["spam.c"])],
version="0.1.0",
{{ setup_py_setup_args_add | indent(4) }}
)
'''))
} }
def __init__(self, spam_c_top_level_add, spam_c_function_add, setup_py_add,
setup_py_setup_args_add, extra_files):
super().__init__(extra_files)
self.context = {}