rougail/src/rougail/template.py

444 lines
16 KiB
Python
Raw Normal View History

2021-01-30 08:15:26 +01:00
"""Template langage for Rougail
Created by:
EOLE (http://eole.orion.education.fr)
Copyright (C) 2005-2018
Forked by:
Cadoles (http://www.cadoles.com)
Copyright (C) 2019-2021
distribued with GPL-2 or later license
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
2019-12-02 10:31:55 +01:00
"""
from shutil import copy
import logging
2019-12-22 14:46:16 +01:00
from typing import Dict, Any
2019-12-02 10:31:55 +01:00
from subprocess import call
from os import listdir, makedirs, getcwd, chdir
from os.path import dirname, join, isfile, abspath, normpath, relpath
2020-02-16 21:27:42 +01:00
2019-12-02 10:31:55 +01:00
from Cheetah.Template import Template as ChtTemplate
from Cheetah.NameMapper import NotFound as CheetahNotFound
2020-08-07 17:17:42 +02:00
try:
from tiramisu3 import Config
2020-12-26 15:15:51 +01:00
from tiramisu3.error import PropertiesOptionError # pragma: no cover
2020-12-26 17:06:56 +01:00
except ModuleNotFoundError: # pragma: no cover
2020-08-08 11:03:06 +02:00
from tiramisu import Config
from tiramisu.error import PropertiesOptionError
2019-12-02 10:31:55 +01:00
2020-08-12 08:23:38 +02:00
from .config import Config
2020-07-08 16:32:10 +02:00
from .error import FileNotFound, TemplateError
2019-12-02 10:31:55 +01:00
from .i18n import _
2021-01-19 19:05:07 +01:00
from .utils import normalize_family, load_modules
2019-12-02 10:31:55 +01:00
log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())
2020-07-08 16:32:10 +02:00
2019-12-02 10:31:55 +01:00
@classmethod
def cl_compile(kls, *args, **kwargs):
2021-01-18 17:46:21 +01:00
"""Rewrite compile methode to force some settings
"""
2019-12-02 10:31:55 +01:00
kwargs['compilerSettings'] = {'directiveStartToken' : '%',
2019-12-20 11:02:26 +01:00
'cheetahVarStartToken' : '%%',
'EOLSlurpToken' : '%',
'PSPStartToken' : 'µ' * 10,
'PSPEndToken' : 'µ' * 10,
'commentStartToken' : 'µ' * 10,
'commentEndToken' : 'µ' * 10,
'multiLineCommentStartToken' : 'µ' * 10,
'multiLineCommentEndToken' : 'µ' * 10}
2021-01-19 19:28:29 +01:00
return kls.old_compile(*args, **kwargs) # pylint: disable=E1101
2019-12-02 10:31:55 +01:00
ChtTemplate.old_compile = ChtTemplate.compile
ChtTemplate.compile = cl_compile
2021-01-19 19:28:29 +01:00
class CheetahTemplate(ChtTemplate): # pylint: disable=W0223
2021-01-18 17:46:21 +01:00
"""Construct a cheetah templating object
2019-12-02 10:31:55 +01:00
"""
def __init__(self,
filename: str,
context,
eosfunc: Dict,
2021-01-18 17:46:21 +01:00
extra_context: Dict,
):
2019-12-02 10:31:55 +01:00
"""Initialize Creole CheetahTemplate
"""
2019-12-22 14:46:16 +01:00
ChtTemplate.__init__(self,
file=filename,
searchList=[context, eosfunc, extra_context])
2019-12-02 10:31:55 +01:00
2020-12-26 15:15:51 +01:00
# FORK of Cheetah function, do not replace '\\' by '/'
def serverSidePath(self,
path=None,
2020-11-18 22:18:16 +01:00
normpath=normpath,
abspath=abspath
2021-01-18 17:46:21 +01:00
): # pylint: disable=W0621
2020-11-18 22:18:16 +01:00
# strange...
if path is None and isinstance(self, str):
path = self
2021-01-18 17:46:21 +01:00
if path: # pylint: disable=R1705
2020-11-18 22:18:16 +01:00
return normpath(abspath(path))
2020-12-26 15:15:51 +01:00
# original code return normpath(abspath(path.replace("\\", '/')))
elif hasattr(self, '_filePath') and self._filePath: # pragma: no cover
2020-11-18 22:18:16 +01:00
return normpath(abspath(self._filePath))
2020-12-26 15:15:51 +01:00
else: # pragma: no cover
2020-11-18 22:18:16 +01:00
return None
2021-01-02 21:22:59 +01:00
class CreoleLeaderIndex:
2021-01-18 17:46:21 +01:00
"""This object is create when access to a specified Index of the variable
"""
2020-12-26 15:15:51 +01:00
def __init__(self,
value,
follower,
index,
) -> None:
2019-12-02 10:31:55 +01:00
self._value = value
2020-12-26 15:15:51 +01:00
self._follower = follower
2019-12-02 10:31:55 +01:00
self._index = index
def __getattr__(self, name):
2020-12-26 15:15:51 +01:00
if name not in self._follower:
raise AttributeError()
value = self._follower[name]
if isinstance(value, PropertiesOptionError):
raise AttributeError()
return value
2019-12-02 10:31:55 +01:00
2021-01-02 21:22:59 +01:00
def __str__(self):
return str(self._value)
2020-12-26 15:15:51 +01:00
def __lt__(self, value):
return self._value.__lt__(value)
2019-12-02 10:31:55 +01:00
2020-12-26 15:15:51 +01:00
def __le__(self, value):
return self._value.__le__(value)
2019-12-02 10:31:55 +01:00
def __eq__(self, value):
2020-12-26 15:15:51 +01:00
return self._value.__eq__(value)
2019-12-02 10:31:55 +01:00
def __ne__(self, value):
2020-12-26 15:15:51 +01:00
return self._value.__ne__(value)
2019-12-02 10:31:55 +01:00
def __gt__(self, value):
2020-12-26 15:15:51 +01:00
return self._value.__gt__(value)
2019-12-02 10:31:55 +01:00
def __ge__(self, value):
return self._value >= value
2020-12-26 15:15:51 +01:00
def __add__(self, value):
return self._value.__add__(value)
def __radd__(self, value):
return value + self._value
2021-01-02 21:22:59 +01:00
class CreoleLeader:
2021-01-18 17:46:21 +01:00
"""Implement access to leader and follower variable
For examples: %%leader, %%leader[0].follower1
"""
2020-12-26 15:15:51 +01:00
def __init__(self,
value,
) -> None:
self._value = value
self._follower = {}
def __getitem__(self, index):
"""Get a leader.follower at requested index.
2019-12-02 10:31:55 +01:00
"""
2020-12-26 15:15:51 +01:00
followers = {key: values[index] for key, values in self._follower.items()}
return CreoleLeaderIndex(self._value[index],
followers,
index,
)
def __iter__(self):
"""Iterate over leader.follower.
2019-12-02 10:31:55 +01:00
2020-12-26 15:15:51 +01:00
Return synchronised value of leader.follower.
"""
for index in range(len(self._value)):
yield self.__getitem__(index)
2019-12-02 10:31:55 +01:00
2020-12-26 15:15:51 +01:00
def __len__(self):
return len(self._value)
2019-12-02 10:31:55 +01:00
2020-12-26 15:15:51 +01:00
def __contains__(self, value):
return self._value.__contains__(value)
2019-12-02 10:31:55 +01:00
2020-12-26 15:15:51 +01:00
async def add_follower(self,
config,
name: str,
path: str,
):
2021-01-18 17:46:21 +01:00
"""Add a new follower
"""
2020-12-26 15:15:51 +01:00
self._follower[name] = []
for index in range(len(self._value)):
try:
value = await config.option(path, index).value.get()
except PropertiesOptionError as err:
value = err
self._follower[name].append(value)
2019-12-02 10:31:55 +01:00
2019-12-22 15:35:50 +01:00
class CreoleExtra:
2021-01-18 17:46:21 +01:00
"""Object that implement access to extra variable
For example %%extra1.family.variable
"""
2019-12-22 15:35:50 +01:00
def __init__(self,
suboption: Dict) -> None:
self.suboption = suboption
def __getattr__(self,
2021-01-02 21:22:59 +01:00
key: str,
) -> Any:
2019-12-22 15:35:50 +01:00
return self.suboption[key]
def __iter__(self):
return iter(self.suboption.values())
2019-12-22 15:35:50 +01:00
2019-12-02 10:31:55 +01:00
class CreoleTemplateEngine:
"""Engine to process Creole cheetah template
"""
2021-01-19 19:28:29 +01:00
def __init__(self, # pylint: disable=R0913
2019-12-02 10:31:55 +01:00
config: Config,
2019-12-02 14:23:02 +01:00
eosfunc_file: str,
distrib_dir: str,
tmp_dir: str,
dest_dir: str,
) -> None:
2019-12-02 10:31:55 +01:00
self.config = config
2019-12-02 14:23:02 +01:00
self.dest_dir = dest_dir
self.tmp_dir = tmp_dir
self.distrib_dir = distrib_dir
2019-12-02 10:31:55 +01:00
eos = {}
2020-02-16 21:27:42 +01:00
if eosfunc_file is not None:
2021-01-19 19:05:07 +01:00
eosfunc = load_modules(eosfunc_file)
2020-02-16 21:27:42 +01:00
for func in dir(eosfunc):
2020-12-26 17:06:56 +01:00
if not func.startswith('_'):
eos[func] = getattr(eosfunc, func)
2019-12-02 10:31:55 +01:00
self.eosfunc = eos
2020-07-06 20:58:11 +02:00
self.rougail_variables_dict = {}
2020-01-13 19:44:24 +01:00
2019-12-02 10:31:55 +01:00
def patch_template(self,
filename: str,
tmp_dir: str,
patch_dir: str,
) -> None:
2019-12-02 10:31:55 +01:00
"""Apply patch to a template
"""
patch_cmd = ['patch', '-d', tmp_dir, '-N', '-p1']
2019-12-02 10:31:55 +01:00
patch_no_debug = ['-s', '-r', '-', '--backup-if-mismatch']
patch_file = join(patch_dir, f'{filename}.patch')
if isfile(patch_file):
log.info(_("Patching template '{filename}' with '{patch_file}'"))
rel_patch_file = relpath(patch_file, tmp_dir)
ret = call(patch_cmd + patch_no_debug + ['-i', rel_patch_file])
2020-12-26 15:15:51 +01:00
if ret: # pragma: no cover
patch_cmd_err = ' '.join(patch_cmd + ['-i', rel_patch_file])
2021-01-18 17:46:21 +01:00
msg = _(f"Error applying patch: '{rel_patch_file}'\n"
f"To reproduce and fix this error {patch_cmd_err}")
log.error(_(msg))
copy(join(self.distrib_dir, filename), tmp_dir)
2019-12-02 10:31:55 +01:00
def prepare_template(self,
filename: str,
tmp_dir: str,
patch_dir: str,
) -> None:
2019-12-02 10:31:55 +01:00
"""Prepare template source file
"""
log.info(_("Copy template: '{filename}' -> '{tmp_dir}'"))
copy(filename, tmp_dir)
self.patch_template(filename, tmp_dir, patch_dir)
2019-12-02 10:31:55 +01:00
def process(self,
source: str,
true_destfilename: str,
2019-12-02 14:23:02 +01:00
destfilename: str,
variable: Any,
):
2019-12-02 10:31:55 +01:00
"""Process a cheetah template
"""
# full path of the destination file
log.info(_(f"Cheetah processing: '{destfilename}'"))
try:
2021-01-18 17:46:21 +01:00
extra_context = {'normalize_family': normalize_family,
'rougail_filename': true_destfilename
}
if variable:
extra_context['rougail_variable'] = variable
cheetah_template = CheetahTemplate(source,
2020-07-06 20:58:11 +02:00
self.rougail_variables_dict,
2019-12-02 10:31:55 +01:00
self.eosfunc,
2021-01-18 17:46:21 +01:00
extra_context,
2020-07-06 20:58:11 +02:00
)
2019-12-02 10:31:55 +01:00
data = str(cheetah_template)
2020-12-26 15:15:51 +01:00
except CheetahNotFound as err: # pragma: no cover
2019-12-02 10:31:55 +01:00
varname = err.args[0][13:-1]
2021-01-18 17:46:21 +01:00
msg = f"Error: unknown variable used in template {source} to {destfilename}: {varname}"
2021-01-19 19:28:29 +01:00
raise TemplateError(_(msg)) from err
2020-12-26 15:15:51 +01:00
except Exception as err: # pragma: no cover
2021-01-18 17:46:21 +01:00
msg = _(f"Error while instantiating template {source} to {destfilename}: {err}")
2021-01-19 19:28:29 +01:00
raise TemplateError(msg) from err
2019-12-02 10:31:55 +01:00
with open(destfilename, 'w') as file_h:
file_h.write(data)
def instance_file(self,
filevar: Dict,
tmp_dir: str,
dest_dir: str,
) -> None:
2020-02-16 21:27:42 +01:00
"""Run templatisation on one file
2019-12-02 10:31:55 +01:00
"""
log.info(_("Instantiating file '{filename}'"))
2019-12-22 14:46:16 +01:00
if 'variable' in filevar:
variable = filevar['variable']
else:
variable = None
filenames = filevar['name']
if not isinstance(filenames, list):
filenames = [filenames]
if variable:
variable = [variable]
2019-12-22 14:46:16 +01:00
for idx, filename in enumerate(filenames):
destfilename = join(dest_dir, filename[1:])
2019-12-22 11:04:39 +01:00
makedirs(dirname(destfilename), exist_ok=True)
2019-12-22 14:46:16 +01:00
if variable:
var = variable[idx]
else:
var = None
source = join(tmp_dir, filevar['source'])
2021-02-12 18:08:28 +01:00
if filevar['templating'] == 'creole':
self.process(source,
filename,
destfilename,
2020-12-26 17:06:56 +01:00
var,
)
else:
copy(source, destfilename)
2019-12-02 10:31:55 +01:00
2020-02-16 21:27:42 +01:00
async def instance_files(self) -> None:
"""Run templatisation on all files
2019-12-02 10:31:55 +01:00
"""
ori_dir = getcwd()
tmp_dir = relpath(self.tmp_dir, self.distrib_dir)
dest_dir = relpath(self.dest_dir, self.distrib_dir)
patch_dir = relpath(Config['patch_dir'], self.distrib_dir)
chdir(self.distrib_dir)
2020-01-13 19:44:24 +01:00
for option in await self.config.option.list(type='all'):
namespace = await option.option.name()
2020-08-12 08:23:38 +02:00
if namespace == Config['variable_namespace']:
2021-01-18 17:46:21 +01:00
await self.load_variables_namespace(option)
2020-01-13 19:44:24 +01:00
else:
2021-01-18 17:46:21 +01:00
self.rougail_variables_dict[namespace] = await self.load_variables_extra(option)
for template in listdir('.'):
self.prepare_template(template, tmp_dir, patch_dir)
2020-02-14 17:59:39 +01:00
for service_obj in await self.config.option('services').list('all'):
for fills in await service_obj.list('all'):
if await fills.option.name() in ['files', 'overrides']:
2020-01-13 19:44:24 +01:00
for fill_obj in await fills.list('all'):
fill = await fill_obj.value.dict()
2019-12-02 10:31:55 +01:00
filename = fill['source']
2020-12-26 15:15:51 +01:00
if not isfile(filename): # pragma: no cover
raise FileNotFound(_(f"File {filename} does not exist."))
2021-01-30 12:28:36 +01:00
if fill['activate']:
2019-12-02 14:23:02 +01:00
self.instance_file(fill,
tmp_dir,
dest_dir,
)
2019-12-02 10:31:55 +01:00
else:
log.debug(_("Instantiation of file '{filename}' disabled"))
chdir(ori_dir)
2019-12-02 10:31:55 +01:00
2021-01-18 17:46:21 +01:00
async def load_variables_namespace (self,
optiondescription,
):
"""load variables from the "variable namespace
"""
for option in await optiondescription.list('all'):
if await option.option.isoptiondescription():
if await option.option.isleadership():
for idx, suboption in enumerate(await option.list('all')):
if idx == 0:
leader = CreoleLeader(await suboption.value.get())
self.rougail_variables_dict[await suboption.option.name()] = leader
else:
await leader.add_follower(self.config,
await suboption.option.name(),
await suboption.option.path(),
)
else:
await self.load_variables_namespace(option)
else:
self.rougail_variables_dict[await option.option.name()] = await option.value.get()
async def load_variables_extra(self,
optiondescription,
) -> CreoleExtra:
"""Load all variables and set it in CreoleExtra objects
"""
families = {}
for family in await optiondescription.list('all'):
variables = {}
for variable in await family.list('all'):
if await variable.option.isoptiondescription():
if await variable.option.isleadership():
for idx, suboption in enumerate(await variable.list('all')):
if idx == 0:
leader = CreoleLeader(await suboption.value.get())
leader_name = await suboption.option.name()
else:
await leader.add_follower(self.config,
await suboption.option.name(),
await suboption.option.path(),
)
variables[leader_name] = leader
else:
subfamilies = await self.load_variables_extra(variable)
variables[await variable.option.name()] = subfamilies
else:
variables[await variable.option.name()] = await variable.value.get()
families[await family.option.name()] = CreoleExtra(variables)
return CreoleExtra(families)
2019-12-02 10:31:55 +01:00
2020-01-13 19:44:24 +01:00
async def generate(config: Config,
eosfunc_file: str,
distrib_dir: str,
tmp_dir: str,
dest_dir: str,
2020-04-29 14:06:29 +02:00
) -> None:
2021-01-18 17:46:21 +01:00
"""Generate all files
"""
2019-12-02 10:31:55 +01:00
engine = CreoleTemplateEngine(config,
2019-12-02 14:23:02 +01:00
eosfunc_file,
distrib_dir,
tmp_dir,
dest_dir,
2020-04-29 14:06:29 +02:00
)
2020-02-16 21:27:42 +01:00
await engine.instance_files()