tiramisu 4

This commit is contained in:
egarette@silique.fr 2023-06-22 12:39:58 +02:00
parent cf410f9577
commit e3ced2d356
3 changed files with 58 additions and 50 deletions

View file

@ -30,7 +30,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from shutil import copy from shutil import copy
import logging import logging
from typing import Dict, Any from typing import Dict, Any, Union
from subprocess import call from subprocess import call
from os import listdir, makedirs, getcwd, chdir, unlink, rmdir, chmod from os import listdir, makedirs, getcwd, chdir, unlink, rmdir, chmod
from os.path import dirname, join, isfile, isdir, abspath from os.path import dirname, join, isfile, isdir, abspath
@ -227,12 +227,12 @@ class RougailBaseTemplate:
"""Engine to process Creole cheetah template """Engine to process Creole cheetah template
""" """
def __init__(self, # pylint: disable=R0913 def __init__(self, # pylint: disable=R0913
config: Config, root: Union[Config, TiramisuOption],
rougailconfig: RougailConfig=None, rougailconfig: RougailConfig=None,
) -> None: ) -> None:
if rougailconfig is None: if rougailconfig is None:
rougailconfig = RougailConfig rougailconfig = RougailConfig
self.config = config self.root = root
self.destinations_dir = abspath(rougailconfig['destinations_dir']) self.destinations_dir = abspath(rougailconfig['destinations_dir'])
self.tmp_dir = abspath(rougailconfig['tmp_dir']) self.tmp_dir = abspath(rougailconfig['tmp_dir'])
self.templates_dir = [] self.templates_dir = []
@ -360,12 +360,12 @@ class RougailBaseTemplate:
return destfilenames return destfilenames
def load_variables(self, with_flatten=True): def load_variables(self, with_flatten=True):
if isinstance(self.config, Config): if isinstance(self.root, Config):
list_options = self.config.option.list(type='all') list_options = self.root.option.list(type='all')
else: else:
list_options = self.config.list(type='all') list_options = self.root.list(type='all')
for option in list_options: for option in list_options:
namespace = option.option.name() namespace = option.name()
if with_flatten and namespace == self.rougailconfig['variable_namespace']: if with_flatten and namespace == self.rougailconfig['variable_namespace']:
is_variable_namespace = True is_variable_namespace = True
else: else:
@ -386,11 +386,11 @@ class RougailBaseTemplate:
if not self.rougail_variables_dict: if not self.rougail_variables_dict:
self.load_variables() self.load_variables()
self.prepare_templates() self.prepare_templates()
for service_obj in self.config.option('services').list('all'): for service_obj in self.root.option('services').list('all'):
service_name = service_obj.option.description() service_name = service_obj.description()
service_desactived = service_obj.option('activate').value.get() is False service_desactived = service_obj.option('activate').value.get() is False
for fills in service_obj.list('optiondescription'): for fills in service_obj.list('optiondescription'):
type_ = fills.option.name() type_ = fills.name()
for fill_obj in fills.list('all'): for fill_obj in fills.list('all'):
fill = {path.split('.')[-1]: value for path, value in fill_obj.value.dict().items()} fill = {path.split('.')[-1]: value for path, value in fill_obj.value.dict().items()}
self.get_default(type_, fill, fill_obj) self.get_default(type_, fill, fill_obj)
@ -440,8 +440,8 @@ class RougailBaseTemplate:
self.prepare_templates() self.prepare_templates()
files_to_delete = [] files_to_delete = []
for included in (True, False): for included in (True, False):
for service_obj in self.config.option('services').list('all'): for service_obj in self.root.option('services').list('all'):
service_name = service_obj.option.description() service_name = service_obj.description()
if service_obj.option('activate').value.get() is False: if service_obj.option('activate').value.get() is False:
if included is False and not service_obj.information.get('undisable', False): if included is False and not service_obj.information.get('undisable', False):
self.desactive_service(service_name) self.desactive_service(service_name)
@ -461,7 +461,7 @@ class RougailBaseTemplate:
engine is None, engine is None,
) )
for fills in service_obj.list('optiondescription'): for fills in service_obj.list('optiondescription'):
type_ = fills.option.name() type_ = fills.name()
for fill_obj in fills.list('all'): for fill_obj in fills.list('all'):
fill = {path.split('.')[-1]: value for path, value in fill_obj.value.dict().items()} fill = {path.split('.')[-1]: value for path, value in fill_obj.value.dict().items()}
self.get_default(type_, fill, fill_obj) self.get_default(type_, fill, fill_obj)
@ -538,7 +538,7 @@ class RougailBaseTemplate:
else: else:
default_value = undefined default_value = undefined
value = obj.information.get(key, default_value) value = obj.information.get(key, default_value)
if key not in ['target', 'undisable'] or value != default_value: if key != 'target' or value != default_value:
dico[key] = obj.information.get(key, default_value) dico[key] = obj.information.get(key, default_value)
def desactive_service(self, def desactive_service(self,
@ -621,33 +621,33 @@ class RougailBaseTemplate:
"""Load all variables and set it in RougailExtra objects """Load all variables and set it in RougailExtra objects
""" """
variables = {} variables = {}
if isinstance(self.config, TiramisuOption): if isinstance(self.root, TiramisuOption):
len_root_path = len(self.config.option.path()) + 1 len_root_path = len(self.root.path()) + 1
for option in optiondescription.list('all'): for option in optiondescription.list('all'):
if option.option.isoptiondescription(): if option.isoptiondescription():
if option.option.isleadership(): if option.isleadership():
for idx, suboption in enumerate(option.list('all')): for idx, suboption in enumerate(option.list('all')):
if idx == 0: if idx == 0:
leader_name = suboption.option.name() leader_name = suboption.name()
leader = RougailLeader(leader_name, suboption.value.get()) leader = RougailLeader(leader_name, suboption.value.get())
leadership_name = option.option.name() leadership_name = option.name()
if is_variable_namespace: if is_variable_namespace:
self.rougail_variables_dict[suboption.option.name()] = leader self.rougail_variables_dict[suboption.name()] = leader
else: else:
if isinstance(self.config, TiramisuOption): if isinstance(self.root, TiramisuOption):
path = (suboption.option.path())[len_root_path:] path = (suboption.path())[len_root_path:]
else: else:
path = suboption.option.path() path = suboption.path()
leader._add_follower(self.config, leader._add_follower(self.root,
suboption.option.name(), suboption.name(),
path, path,
) )
variables[leadership_name] = RougailExtra(option.option.name(), {leader_name: leader}, option.option.path()) variables[leadership_name] = RougailExtra(option.name(), {leader_name: leader}, option.path())
else: else:
if is_service_namespace == 'root': if is_service_namespace == 'root':
new_is_service_namespace = 'service_name' new_is_service_namespace = 'service_name'
elif is_service_namespace == 'service_name': elif is_service_namespace == 'service_name':
new_is_service_namespace = option.option.name() new_is_service_namespace = option.name()
elif is_service_namespace in INFORMATIONS: elif is_service_namespace in INFORMATIONS:
# remove 's' # remove 's'
new_is_service_namespace = is_service_namespace[:-1] new_is_service_namespace = is_service_namespace[:-1]
@ -657,9 +657,9 @@ class RougailBaseTemplate:
is_variable_namespace, is_variable_namespace,
new_is_service_namespace, new_is_service_namespace,
) )
variables[option.option.name()] = subfamilies variables[option.name()] = subfamilies
else: else:
name = option.option.name() name = option.name()
value = option.value.get() value = option.value.get()
if is_variable_namespace: if is_variable_namespace:
self.rougail_variables_dict[name] = value self.rougail_variables_dict[name] = value
@ -673,4 +673,4 @@ class RougailBaseTemplate:
variables, variables,
optiondescription, optiondescription,
) )
return RougailExtra(optiondescription.option.name(), variables, optiondescription.option.path()) return RougailExtra(optiondescription.name(), variables, optiondescription.path())

View file

@ -51,7 +51,7 @@ class RougailSystemdTemplate(RougailBaseTemplate):
) -> None: ) -> None:
self.ip_per_service = None self.ip_per_service = None
super().__init__(config, rougailconfig) super().__init__(config, rougailconfig)
self.rougail_tmpl_template = f"""%def display(%%file, %%filename) self.rougail_tmpl_template = f"""%def display(%%file, %%filename, %%service_activate, %%file_activate)
""" """
tmp_local_dir = (f"%%filename.startswith('{local_dir}')" for local_dir in LOCAL_DIR) tmp_local_dir = (f"%%filename.startswith('{local_dir}')" for local_dir in LOCAL_DIR)
self.rougail_tmpl_template += '%if ' + ' or '.join(tmp_local_dir) self.rougail_tmpl_template += '%if ' + ' or '.join(tmp_local_dir)
@ -59,23 +59,25 @@ class RougailSystemdTemplate(RougailBaseTemplate):
%if {self.rougailconfig['systemd_tmpfile_delete_before_create']} %if {self.rougailconfig['systemd_tmpfile_delete_before_create']}
r %%filename r %%filename
%end if %end if
%if %%service_activate and %%file_activate
%set %%mode = %%str(%%file.mode) %set %%mode = %%str(%%file.mode)
%if %%len(%%mode) == 3 %if %%len(%%mode) == 3
%set %%mode = '0' + %%mode %set %%mode = '0' + %%mode
%end if %end if
C %%filename %%mode %%file.owner %%file.group - {self.rougailconfig['systemd_tmpfile_factory_dir']}%%filename C %%filename %%mode %%file.owner %%file.group - {self.rougailconfig['systemd_tmpfile_factory_dir']}%%filename
%end if
%end if %end if
%end def %end def
%for %%service in %%services %for %%service in %%services
%if %%service.activate is True and %%hasattr(%%service, 'files') %if %%hasattr(%%service, 'files')
%for %%file in %%service.files %for %%file in %%service.files
%if %%file.activate is True and %%file.included != 'content' %if %%hasattr(%%file, 'name') and %%file.included != 'content'
%if %%isinstance(%%file.name, list) %if %%isinstance(%%file.name, list)
%for %%filename in %%file.name %for %%filename in %%file.name
%%display(%%file, %%filename)%slurp %%display(%%file, %%filename, %%service.activate, %%file.activate)%slurp
%end for %end for
%else %else
%%display(%%file, %%file.name)%slurp %%display(%%file, %%file.name, %%service.activate, %%file.activate)%slurp
%end if %end if
%end if %end if
%end for %end for

View file

@ -115,7 +115,9 @@ class TiramisuReflector:
self.populate_family(basefamily, self.populate_family(basefamily,
elt, elt,
) )
basefamily.populate_informations() # basefamily.populate_informations()
if not hasattr(basefamily.elt, 'information'):
basefamily.elt.information = self.objectspace.information(None)
basefamily.elt.information = self.objectspace.paths.get_providers_path() basefamily.elt.information = self.objectspace.paths.get_providers_path()
basefamily.elt.information.update(self.objectspace.paths.get_suppliers_path()) basefamily.elt.information.update(self.objectspace.paths.get_suppliers_path())
else: else:
@ -132,9 +134,13 @@ class TiramisuReflector:
self.populate_family(baseprefix, self.populate_family(baseprefix,
elt, elt,
) )
baseprefix.populate_informations() if not hasattr(baseprefix.elt, 'information'):
baseprefix.elt.information = self.objectspace.paths.get_providers_path(path_prefix) baseprefix.elt.information = self.objectspace.information(baseprefix.elt.xmlfiles)
baseprefix.elt.information.update(self.objectspace.paths.get_suppliers_path(path_prefix)) for key, value in self.objectspace.paths.get_providers_path(path_prefix).items():
setattr(baseprefix.elt.information, key, value)
for key, value in self.objectspace.paths.get_suppliers_path(path_prefix).items():
setattr(baseprefix.elt.information, key, value)
# baseprefix.populate_informations()
baseelt.name = normalize_family(self.cfg['base_option_name']) baseelt.name = normalize_family(self.cfg['base_option_name'])
baseelt.doc = self.cfg['base_option_name'] baseelt.doc = self.cfg['base_option_name']
baseelt.reflector_object.get([], baseelt.doc, 'base') # pylint: disable=E1101 baseelt.reflector_object.get([], baseelt.doc, 'base') # pylint: disable=E1101
@ -308,11 +314,8 @@ class Common:
): ):
"""Populate variable parameters """Populate variable parameters
""" """
if param.type in ['number', 'boolean', 'nil', 'string', 'port', 'choice', 'space']: if param.type in ['number', 'boolean', 'nil', 'port', 'choice', 'space']:
value = param.text return f'ParamValue({param.text})'
if param.type == 'string' and value is not None:
value = self.convert_str(value)
return f'ParamValue({value})'
if param.type in ['variable_name', 'variable']: if param.type in ['variable_name', 'variable']:
return self.build_option_param(param) return self.build_option_param(param)
if param.type == 'information': if param.type == 'information':
@ -320,14 +323,17 @@ class Common:
default = [] default = []
else: else:
default = None default = None
if hasattr(param, 'variable'):
if param.variable.path == self.elt.path:
return f'ParamSelfInformation("{param.text}", {default})'
return f'ParamInformation("{param.text}", {default}, option={param.variable.reflector_object.get(self.calls, self.elt.path, "param")})'
return f'ParamInformation("{param.text}", {default})' return f'ParamInformation("{param.text}", {default})'
if param.type == 'target_information':
return f'ParamSelfInformation("{param.text}", None)'
if param.type == 'suffix': if param.type == 'suffix':
return 'ParamSuffix()' return 'ParamSuffix()'
if param.type == 'index': if param.type == 'index':
return 'ParamIndex()' return 'ParamIndex()'
raise Exception(_(f'unknown type {param.type}')) # pragma: no cover value = self.convert_str(param.text)
return f'ParamValue({value})'
def build_option_param(self, def build_option_param(self,
param, param,