simplify get_message

This commit is contained in:
Emmanuel Garette 2020-03-14 22:23:52 +01:00
parent db8bdf4a6d
commit efb8f22872
2 changed files with 66 additions and 84 deletions

View File

@ -1,4 +1,3 @@
from collections import OrderedDict
from os.path import join, basename, dirname from os.path import join, basename, dirname
from glob import glob from glob import glob
@ -9,8 +8,11 @@ from tiramisu import StrOption, IntOption, BoolOption, ChoiceOption, OptionDescr
from yaml import load, SafeLoader from yaml import load, SafeLoader
from os import listdir from os import listdir
from os.path import isfile from os.path import isfile
from ..config import get_config
from ..utils import _
from .config import get_config
from .utils import _
MESSAGE_ROOT_PATH = get_config()['global']['message_root_path'] MESSAGE_ROOT_PATH = get_config()['global']['message_root_path']
CUSTOMTYPES = {} CUSTOMTYPES = {}
@ -42,14 +44,16 @@ class MessageDefinition:
A MessageDefinition is a representation of a message in the Zephir application messaging context A MessageDefinition is a representation of a message in the Zephir application messaging context
""" """
__slots__ = ('version', __slots__ = ('version',
'uri', 'message',
'description', 'description',
'parameters', 'parameters',
'default_roles', 'default_roles',
'errors', 'errors',
'pattern', 'pattern',
'related', 'related',
'response') 'response',
'options',
)
def __init__(self, def __init__(self,
raw_def, raw_def,
@ -57,17 +61,18 @@ class MessageDefinition:
message): message):
# default value for non mandatory key # default value for non mandatory key
self.version = version self.version = version
self.parameters = OrderedDict() self.parameters = {}
self.errors = [] self.errors = []
self.related = [] self.related = []
self.default_roles = [] self.default_roles = []
self.response = None self.response = None
self.uri = message self.message = message
self.options = None
# loads yaml information into object # loads yaml information into object
for key, value in raw_def.items(): for key, value in raw_def.items():
if key == 'uri': if key == 'message':
raise Exception('uri in not allowed in message') raise Exception('message in not allowed in message')
if isinstance(value, str): if isinstance(value, str):
value = value.strip() value = value.strip()
if key == 'pattern': if key == 'pattern':
@ -83,8 +88,10 @@ class MessageDefinition:
elif key == 'response': elif key == 'response':
value = ResponseDefinition(value, value = ResponseDefinition(value,
self.version) self.version)
elif key == 'errors': elif key == 'description':
value = _parse_error_definition(value) value = value.strip().rstrip()
if value.endswith('.'):
value = value[:-1]
setattr(self, key, value) setattr(self, key, value)
# check mandatory keys # check mandatory keys
for key in self.__slots__: for key in self.__slots__:
@ -130,6 +137,9 @@ class ParameterDefinition:
else: else:
self._valid_type(value) self._valid_type(value)
#self._valid_type(value) #self._valid_type(value)
elif key == 'description':
if value.endswith('.'):
value = value[:-1]
setattr(self, key, value) setattr(self, key, value)
# check mandatory keys # check mandatory keys
for key in self.__slots__: for key in self.__slots__:
@ -182,6 +192,9 @@ class ResponseDefinition:
value = CUSTOMTYPES[version][value].type value = CUSTOMTYPES[version][value].type
else: else:
self._valid_type(value) self._valid_type(value)
elif key == 'description':
if value.endswith('.'):
value = value[:-1]
setattr(self, key, value) setattr(self, key, value)
# check mandatory keys # check mandatory keys
for key in self.__slots__: for key in self.__slots__:
@ -197,29 +210,9 @@ class ResponseDefinition:
raise Exception(_('unknown parameter type: {}').format(typ)) raise Exception(_('unknown parameter type: {}').format(typ))
class ErrorDefinition:
"""
An ErrorDefinition is a representation of an error in the Zephir application messaging context
"""
__slots__ = ('uri',)
def __init__(self, raw_err):
extra_keys = set(raw_err) - set(self.__slots__)
if extra_keys:
raise Exception(_('extra keys for errors: {}').format(extra_keys))
self.uri = raw_err['uri']
def _parse_error_definition(raw_defs):
new_value = []
for raw_err in raw_defs:
new_value.append(ErrorDefinition(raw_err))
return new_value
def _parse_parameters(raw_defs, def _parse_parameters(raw_defs,
version): version):
parameters = OrderedDict() parameters = {}
for name, raw_def in raw_defs.items(): for name, raw_def in raw_defs.items():
parameters[name] = ParameterDefinition(name, parameters[name] = ParameterDefinition(name,
version, version,
@ -228,7 +221,8 @@ def _parse_parameters(raw_defs,
def get_message(uri: str, def get_message(uri: str,
current_module_names: str): current_module_names: str,
) -> MessageDefinition:
try: try:
version, message = uri.split('.', 1) version, message = uri.split('.', 1)
path = get_message_file_path(version, path = get_message_file_path(version,
@ -299,6 +293,9 @@ class CustomParam:
value = self._convert_type(value, raw_def) value = self._convert_type(value, raw_def)
elif key == 'items': elif key == 'items':
continue continue
elif key == 'description':
if value.endswith('.'):
value = value[:-1]
setattr(self, key, value) setattr(self, key, value)
# check mandatory keys # check mandatory keys
@ -331,7 +328,7 @@ class CustomParam:
def _parse_custom_params(raw_defs, required): def _parse_custom_params(raw_defs, required):
parameters = OrderedDict() parameters = {}
for name, raw_def in raw_defs.items(): for name, raw_def in raw_defs.items():
parameters[name] = CustomParam(name, raw_def, required) parameters[name] = CustomParam(name, raw_def, required)
return parameters return parameters
@ -357,6 +354,9 @@ class CustomType:
value = self._convert_type(value, raw_def) value = self._convert_type(value, raw_def)
elif key == 'properties': elif key == 'properties':
value = _parse_custom_params(value, raw_def.get('required', {})) value = _parse_custom_params(value, raw_def.get('required', {}))
elif key == 'description':
if value.endswith('.'):
value = value[:-1]
setattr(self, key, value) setattr(self, key, value)
# check mandatory keys # check mandatory keys
@ -435,12 +435,13 @@ def _get_option(name,
props = [] props = []
if not hasattr(arg, 'default'): if not hasattr(arg, 'default'):
props.append('mandatory') props.append('mandatory')
props.append(Calculation(calc_value, if select_option:
Params(ParamValue('disabled'), props.append(Calculation(calc_value,
kwargs={'condition': ParamOption(select_option, todict=True), Params(ParamValue('disabled'),
'expected': ParamValue(optiondescription), kwargs={'condition': ParamOption(select_option, todict=True),
'reverse_condition': ParamValue(True)}), 'expected': ParamValue(optiondescription),
calc_value_property_help)) 'reverse_condition': ParamValue(True)}),
calc_value_property_help))
description = arg.description.strip().rstrip() description = arg.description.strip().rstrip()
kwargs = {'name': name, kwargs = {'name': name,
@ -472,7 +473,6 @@ def _get_option(name,
def get_options(message_def, def get_options(message_def,
file_path, file_path,
needs,
select_option, select_option,
optiondescription, optiondescription,
load_shortarg): load_shortarg):
@ -496,7 +496,7 @@ def _parse_responses(message_def,
"""build option with returns """build option with returns
""" """
if message_def.response.parameters is None: if message_def.response.parameters is None:
raise Exception('uri "{}" did not returned any valid parameters.'.format(message_def.uri)) raise Exception('message "{}" did not returned any valid parameters.'.format(message_def.message))
options = [] options = []
names = [] names = []
@ -518,41 +518,21 @@ def _parse_responses(message_def,
# FIXME # FIXME
'File': StrOption}.get(type_) 'File': StrOption}.get(type_)
if not option: if not option:
raise Exception(f'unknown param type {obj.type} in responses of message {message_def.uri}') raise Exception(f'unknown param type {obj.type} in responses of message {message_def.message}')
if hasattr(obj, 'default'): if hasattr(obj, 'default'):
kwargs['default'] = obj.default kwargs['default'] = obj.default
else: else:
kwargs['properties'] = ('mandatory',) kwargs['properties'] = ('mandatory',)
options.append(option(**kwargs)) options.append(option(**kwargs))
od = OptionDescription(message_def.uri, od = OptionDescription(message_def.message,
message_def.response.description, message_def.response.description,
options) options)
od.impl_set_information('multi', message_def.response.multi) od.impl_set_information('multi', message_def.response.multi)
return od return od
def _getoptions_from_yml(message_def, def _get_root_option(select_option,
optiondescriptions, optiondescriptions):
file_path,
needs,
select_option,
load_shortarg):
if message_def.pattern == 'event' and message_def.response:
raise Exception('event with response?: {}'.format(file_path))
if message_def.pattern == 'rpc' and not message_def.response:
print('rpc without response?: {}'.format(file_path))
options = get_options(message_def,
file_path,
needs,
select_option,
message_def.uri,
load_shortarg)
name = message_def.uri
description = message_def.description.strip().rstrip()
optiondescriptions[name] = (description, options)
def _get_root_option(select_option, optiondescriptions):
"""get root option """get root option
""" """
def _get_od(curr_ods): def _get_od(curr_ods):
@ -600,7 +580,6 @@ def get_messages(current_module_names,
global CUSTOMTYPES global CUSTOMTYPES
optiondescriptions = {} optiondescriptions = {}
optiondescriptions_info = {} optiondescriptions_info = {}
needs = {}
messages = list(list_messages(uris, messages = list(list_messages(uris,
current_module_names, current_module_names,
current_version)) current_version))
@ -618,25 +597,29 @@ def get_messages(current_module_names,
load_customtypes(listdir(join(MESSAGE_ROOT_PATH, version))) load_customtypes(listdir(join(MESSAGE_ROOT_PATH, version)))
else: else:
load_customtypes(current_module_names) load_customtypes(current_module_names)
for message_name in messages: for uri in messages:
message_def = get_message(message_name, message_def = get_message(uri,
current_module_names) current_module_names,
optiondescriptions_info[message_def.uri] = {'pattern': message_def.pattern, )
'default_roles': message_def.default_roles, optiondescriptions_info[message_def.message] = {'pattern': message_def.pattern,
'version': message_name.split('.')[0]} 'default_roles': message_def.default_roles,
'version': message_def.version}
if message_def.pattern == 'rpc': if message_def.pattern == 'rpc':
optiondescriptions_info[message_def.uri]['response'] = _parse_responses(message_def, if not message_def.response:
message_name) raise Exception(f'rpc without response is not allowed {uri}')
optiondescriptions_info[message_def.message]['response'] = _parse_responses(message_def,
uri)
elif message_def.response: elif message_def.response:
raise Exception(f'response not allowed for {message_def.uri}') raise Exception(f'response is not allowed for {uri}')
_getoptions_from_yml(message_def, message_def.options = get_options(message_def,
optiondescriptions, uri,
message_name, select_option,
needs, message_def.message,
select_option, load_shortarg)
load_shortarg) optiondescriptions[message_def.message] = (message_def.description, message_def.options)
root = _get_root_option(select_option, optiondescriptions) root = _get_root_option(select_option,
optiondescriptions)
if current_module_names is None: if current_module_names is None:
CUSTOMTYPES = {} CUSTOMTYPES = {}
return optiondescriptions_info, root return optiondescriptions_info, root

View File

@ -1 +0,0 @@
from .message import get_messages