Peano
Loading...
Searching...
No Matches
Jinja2TemplatedHeaderFile.py
Go to the documentation of this file.
1# This file is part of the Peano project. For conditions of distribution and
2# use, please see the copyright notice at www.peano-framework.org
3import os
4import re
5import jinja2
6
7from copy import deepcopy
8
9from .Helper import write_file
10
11from .Overwrite import Overwrite
12
14 def __init__(self,headerfile_template,classname,namespace,subdirectory,dictionary,default_overwrite=True,apply_iteratively=False):
15 """
16 The template files should be fully qualified
17
18 classname is a string
19 namespace is a (possibly empty) list of strings
20 dictionary a series of mappings (cmp. Jinja2 convention)
21 """
22 self.headerfile_template = headerfile_template
23 self.classname = classname
24 self.namespace = namespace
25 self.subdirectory = subdirectory
26 self.default_overwrite = default_overwrite
27 self.apply_iteratively = apply_iteratively
28
29 self.d = deepcopy(dictionary)
30 self.d[ "CLASSNAME" ] = classname
31 self.d[ "NAMESPACE" ] = []
32 for i in namespace:
33 self.d["NAMESPACE"].append(i)
34 # Eliminate the prepending "::" that can lead to compatibility issues across the solvers
35 self.d["FULL_QUALIFIED_NAMESPACE"] = "::".join(namespace)
36
37 def __generate_file(self,overwrite,full_qualified_filename,template_file):
38 """
39 template_file: string
40 Usually, this is an absolute file name.
41 """
42 if template_file!=None and write_file(overwrite,self.default_overwrite,full_qualified_filename):
43 print( "write " + full_qualified_filename )
44
45 template_loader = jinja2.FileSystemLoader(searchpath=os.path.split(template_file)[0])
46 templateEnv = jinja2.Environment(loader=template_loader, undefined=jinja2.DebugUndefined)
47 template = templateEnv.get_template( os.path.split(template_file)[1] )
48
49 if self.apply_iteratively:
50 rendered_text = template.render(self.d)
51 while "{{" in rendered_text and len(rendered_text)!=old_size:
52 old_size = len(rendered_text)
53 template = jinja2.Template(rendered_text, undefined=jinja2.DebugUndefined)
54 rendered_text = template.render( self.d )
55
56 with open( full_qualified_filename, "w" ) as output:
57 output.write( template.render(self.d) )
58
59 def generate(self,overwrite,directory):
60 if not os.path.exists( directory + "/" + self.subdirectory ):
61 os.mkdir(directory + "/" + self.subdirectory)
62
63 header_filename = directory + "/" + self.subdirectory + "/" + self.classname + ".h"
64
65 self.__generate_file(overwrite,header_filename,self.headerfile_template)
__generate_file(self, overwrite, full_qualified_filename, template_file)
template_file: string Usually, this is an absolute file name.
__init__(self, headerfile_template, classname, namespace, subdirectory, dictionary, default_overwrite=True, apply_iteratively=False)
The template files should be fully qualified.