tiramisu-cmdline-parser/tiramisu_cmdline_parser/api.py

322 lines
14 KiB
Python
Raw Normal View History

2018-11-29 22:52:20 +01:00
# Copyright (C) 2018 Team tiramisu (see AUTHORS for all contributors)
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
2019-01-10 09:55:45 +01:00
from typing import Union, List, Optional
from argparse import ArgumentParser, Namespace, SUPPRESS, _HelpAction, HelpFormatter
2019-04-02 21:02:08 +02:00
from copy import copy
2019-04-09 07:28:11 +02:00
from gettext import gettext as _
2019-04-02 21:02:08 +02:00
2019-01-10 09:55:45 +01:00
try:
from tiramisu import Config
from tiramisu.error import PropertiesOptionError
except ModuleNotFoundError:
2019-01-10 09:55:45 +01:00
Config = None
from tiramisu_json_api.error import PropertiesOptionError
2019-01-10 09:55:45 +01:00
try:
from tiramisu_json_api import Config as ConfigJson
if Config is None:
Config = ConfigJson
except ModuleNotFoundError:
2019-01-10 09:55:45 +01:00
ConfigJson = Config
2018-11-29 22:10:08 +01:00
class TiramisuNamespace(Namespace):
def _populate(self):
2019-01-10 09:55:45 +01:00
#self._config.property.read_only()
2018-11-29 22:10:08 +01:00
for tiramisu_key, tiramisu_value in self._config.value.dict().items():
option = self._config.option(tiramisu_key)
2019-01-10 09:55:45 +01:00
if not option.option.issymlinkoption():
2018-11-29 22:10:08 +01:00
if tiramisu_value == [] and option.option.ismulti() and option.owner.isdefault():
tiramisu_value = None
super().__setattr__(tiramisu_key, tiramisu_value)
2019-01-10 09:55:45 +01:00
#self._config.property.read_write()
2018-11-29 22:10:08 +01:00
def __init__(self, config):
self._config = config
super().__init__()
def __setattr__(self, key, value):
if key == '_config':
super().__setattr__(key, value)
return
2019-01-10 09:55:45 +01:00
# self._config.property.read_write()
2018-11-29 22:10:08 +01:00
option = self._config.option(key)
if option.option.ismulti() and value is not None and not isinstance(value, list):
value = [value]
option.value.set(value)
def __getattribute__(self, key):
if key == '__dict__' and hasattr(self, '_config'):
self._populate()
return super().__getattribute__(key)
class TiramisuHelpFormatter(HelpFormatter):
def _get_default_metavar_for_optional(self,
action):
ret = super()._get_default_metavar_for_optional(action)
if '.' in ret:
ret = ret.split('.', 1)[1]
return ret
class _TiramisuHelpAction(_HelpAction):
needs = False
def __call__(self, *args, **kwargs):
_TiramisuHelpAction.needs = True
def display(self, parser):
_HelpAction.__call__(self, parser, None, None)
class TiramisuCmdlineParser(ArgumentParser):
2019-01-10 09:55:45 +01:00
def __init__(self,
2019-01-16 09:28:29 +01:00
config: Union[Config, ConfigJson],
2019-01-10 09:55:45 +01:00
*args,
fullpath: bool=True,
2019-01-16 09:28:29 +01:00
_forhelp: bool=False,
2019-01-10 09:55:45 +01:00
**kwargs):
self.fullpath = fullpath
2019-01-16 09:28:29 +01:00
self.config = config
kwargs['formatter_class'] = TiramisuHelpFormatter
2018-11-29 22:10:08 +01:00
super().__init__(*args, **kwargs)
self.register('action', 'help', _TiramisuHelpAction)
2019-01-16 09:28:29 +01:00
self._config_to_argparser(_forhelp,
self.config.option)
def _pop_action_class(self, kwargs, default=None):
ret = super()._pop_action_class(kwargs, default)
if kwargs.get('action') != 'help' and kwargs.get('dest') != 'help':
return ret
return _TiramisuHelpAction
2018-11-29 22:10:08 +01:00
2019-01-10 09:55:45 +01:00
def _match_arguments_partial(self,
actions,
arg_string_pattern):
2018-11-29 22:10:08 +01:00
# used only when check first proposal for first value
# we have to remove all actions with propertieserror
# so only first settable option will be returned
actions_pop = []
for idx, action in enumerate(actions):
2019-01-10 09:55:45 +01:00
if self.config.option(action.dest).property.get(only_raises=True):
2018-11-29 22:10:08 +01:00
actions_pop.append(idx)
else:
break
for idx in actions_pop:
actions.pop(0)
return super()._match_arguments_partial(actions, arg_string_pattern)
def _parse_known_args(self, args=None, namespace=None):
namespace_, args_ = super()._parse_known_args(args, namespace)
if args != args_ and args_ and args_[0].startswith(self.prefix_chars):
# option that was disabled are no more disable
# so create a new parser
2019-01-16 09:28:29 +01:00
new_parser = TiramisuCmdlineParser(self.config,
self.prog,
fullpath=self.fullpath)
namespace_, args_ = new_parser._parse_known_args(args_, namespace)
else:
if self._registries['action']['help'].needs:
# display help only when all variables assignemnt are done
self._registries['action']['help'].needs = False
helper = self._registries['action']['help'](None)
helper.display(self)
return namespace_, args_
2018-11-29 22:10:08 +01:00
def add_argument(self, *args, **kwargs):
if args == ('-h', '--help'):
super().add_argument(*args, **kwargs)
else:
2019-04-09 07:28:11 +02:00
raise NotImplementedError(_('do not use add_argument'))
2018-11-29 22:10:08 +01:00
2019-01-16 09:28:29 +01:00
def add_arguments(self, *args, **kwargs):
2019-04-09 07:28:11 +02:00
raise NotImplementedError(_('do not use add_argument'))
2019-01-16 09:28:29 +01:00
2018-12-01 08:28:35 +01:00
def add_subparsers(self, *args, **kwargs):
2019-04-09 07:28:11 +02:00
raise NotImplementedError(_('do not use add_subparsers'))
2018-12-01 08:28:35 +01:00
2019-04-02 21:02:08 +02:00
def _gen_argument(self, name, longargument, no_prefix=False):
shortarg = len(name) == 1 and not longargument
if no_prefix:
if shortarg:
prefix = 'n'
else:
prefix = 'no-'
if '.' in name:
sname = name.rsplit('.', 1)
name = sname[0] + '.' + prefix + sname[1]
else:
name = prefix + name
if shortarg:
2019-01-16 17:44:49 +01:00
return self.prefix_chars + name
return self.prefix_chars * 2 + name
2018-12-01 08:28:35 +01:00
def _config_to_argparser(self,
2019-01-10 09:55:45 +01:00
_forhelp: bool,
config,
prefix: Optional[str]=None,
group=None) -> None:
if group is None:
group = super()
2018-11-29 22:10:08 +01:00
actions = {}
2019-01-10 09:55:45 +01:00
for obj in config.list(type='all'):
2018-11-29 22:10:08 +01:00
option = obj.option
2019-01-10 09:55:45 +01:00
if option.isoptiondescription():
if _forhelp:
group = self.add_argument_group(option.doc())
if prefix:
prefix_ = prefix + '.' + option.name()
else:
prefix_ = option.path()
self._config_to_argparser(_forhelp, obj, prefix_, group)
continue
if 'frozen' in option.properties():
continue
2018-11-29 22:10:08 +01:00
name = option.name()
if name.startswith(self.prefix_chars):
2019-04-09 07:28:11 +02:00
raise ValueError(_('name cannot startswith "{}"').format(self.prefix_chars))
2019-02-27 07:32:32 +01:00
if self.fullpath and prefix:
name = prefix + '.' + name
2018-11-29 22:10:08 +01:00
properties = obj.property.get()
2019-01-28 17:05:50 +01:00
kwargs = {'help': option.doc().replace('%', '%%')}
2019-02-27 07:32:32 +01:00
if option.issymlinkoption():
2019-04-02 19:01:17 +02:00
symlink_name = option.name(follow_symlink=True)
if symlink_name in actions:
2019-04-02 21:02:08 +02:00
actions[symlink_name][0][0].insert(0, self._gen_argument(option.name(), 'longargument' in properties))
if len(actions[symlink_name]) == 2:
actions[symlink_name][1][0].insert(0, self._gen_argument(option.name(), False, True))
2019-02-27 07:32:32 +01:00
continue
2019-04-02 21:02:08 +02:00
if _forhelp and not obj.owner.isdefault() and obj.value.get() is not None:
2019-04-02 19:01:17 +02:00
if 'positional' not in properties:
2019-04-02 21:02:08 +02:00
self.prog += ' {}'.format(self._gen_argument(name, 'longargument' in properties))
2019-04-02 19:01:17 +02:00
if option.type() != 'boolean':
self.prog += ' {}'.format(obj.value.get())
2018-11-29 22:10:08 +01:00
else:
2019-04-02 08:49:36 +02:00
if 'positional' in properties:
2019-04-02 21:02:08 +02:00
if option.type() == 'boolean':
2019-04-09 07:28:11 +02:00
raise ValueError(_('boolean option must not be positional'))
2019-04-09 07:18:05 +02:00
# if not 'mandatory' in properties:
# raise ValueError('"positional" argument must be "mandatory" too')
2019-04-02 21:02:08 +02:00
args = [option.path()]
2019-04-02 08:49:36 +02:00
if _forhelp:
kwargs['default'] = obj.value.default()
else:
kwargs['default'] = obj.value.get()
kwargs['nargs'] = '?'
2019-02-27 07:32:32 +01:00
else:
2019-04-02 08:49:36 +02:00
kwargs['dest'] = option.path()
kwargs['default'] = SUPPRESS
2018-12-01 08:28:35 +01:00
if _forhelp and 'mandatory' in properties:
2019-04-02 08:49:36 +02:00
kwargs['required'] = True
2019-04-02 21:02:08 +02:00
if option.type() == 'boolean':
if 'storefalse' in properties:
2019-04-02 21:02:08 +02:00
action = 'store_false'
no_action = 'store_true'
else:
action = 'store_true'
no_action = 'store_false'
2019-04-02 21:02:08 +02:00
kwargs['action'] = action
args = [self._gen_argument(name, 'longargument' in properties)]
#
nkwargs = copy(kwargs)
nkwargs['action'] = no_action
del nkwargs['help']
nargs = [self._gen_argument(name, 'longargument' in properties, True)]
actions[option.name()] = [(args, kwargs), (nargs, nkwargs)]
continue
args = [self._gen_argument(name, 'longargument' in properties)]
if _forhelp:
value = obj.value.default()
else:
value = obj.value.get()
if value not in [None, []]:
#kwargs['default'] = kwargs['const'] = option.default()
#kwargs['action'] = 'store_const'
kwargs['nargs'] = '?'
if option.ismulti():
if _forhelp and 'mandatory' in properties:
kwargs['nargs'] = '+'
2019-04-02 08:49:36 +02:00
else:
2019-04-02 21:02:08 +02:00
kwargs['nargs'] = '*'
if option.type() == 'string':
pass
elif option.type() == 'integer':
kwargs['type'] = int
elif option.type() == 'choice':
kwargs['choices'] = obj.value.list()
else:
pass
#raise NotImplementedError('not supported yet')
actions[option.name()] = [(args, kwargs)]
for values in actions.values():
for args, kwargs in values:
group.add_argument(*args, **kwargs)
2018-11-29 22:10:08 +01:00
2019-01-17 09:40:07 +01:00
def parse_args(self,
*args,
valid_mandatory=True,
**kwargs):
2018-11-29 22:10:08 +01:00
kwargs['namespace'] = TiramisuNamespace(self.config)
try:
2018-12-01 09:53:31 +01:00
namespaces = super().parse_args(*args, **kwargs)
2018-12-01 08:28:35 +01:00
del namespaces.__dict__['_config']
2018-11-29 22:10:08 +01:00
except PropertiesOptionError as err:
2018-12-01 09:53:31 +01:00
name = err._option_bag.option.impl_getname()
2019-01-10 09:55:45 +01:00
properties = self.config.option(name).property.get()
if self.fullpath and 'positional' not in properties:
2018-12-01 09:53:31 +01:00
if len(name) == 1 and 'longargument' not in properties:
name = self.prefix_chars + name
else:
name = self.prefix_chars * 2 + name
2018-12-01 08:28:35 +01:00
if err.proptype == ['mandatory']:
self.error('the following arguments are required: {}'.format(name))
2018-11-29 22:10:08 +01:00
else:
2018-12-01 09:53:31 +01:00
self.error('unrecognized arguments: {}'.format(name))
2019-01-17 09:40:07 +01:00
if valid_mandatory:
for key in self.config.value.mandatory():
2019-01-28 17:05:50 +01:00
properties = self.config.option(key).property.get()
if 'positional' not in properties:
if self.fullpath or '.' not in key:
name = key
else:
name = key.rsplit('.', 1)[1]
2019-04-02 21:02:08 +02:00
args = self._gen_argument(name, 'longargument' in self.config.option(key).property.get())
2019-01-17 09:40:07 +01:00
else:
2019-01-28 17:05:50 +01:00
args = key
if not self.fullpath and '.' in args:
args = args.rsplit('.', 1)[1]
2019-01-17 09:40:07 +01:00
self.error('the following arguments are required: {}'.format(args))
2018-11-29 22:10:08 +01:00
return namespaces
2019-01-10 09:55:45 +01:00
def format_usage(self,
*args,
**kwargs):
2019-01-16 09:28:29 +01:00
help_formatter = TiramisuCmdlineParser(self.config,
self.prog,
fullpath=self.fullpath,
_forhelp=True)
return super(TiramisuCmdlineParser, help_formatter).format_usage(*args, **kwargs)
2018-12-01 08:28:35 +01:00
2019-04-02 08:49:36 +02:00
def format_help(self):
2019-01-16 09:28:29 +01:00
help_formatter = TiramisuCmdlineParser(self.config,
self.prog,
fullpath=self.fullpath,
_forhelp=True)
2019-04-02 08:49:36 +02:00
return super(TiramisuCmdlineParser, help_formatter).format_help()
2018-12-01 08:28:35 +01:00
2018-11-29 22:10:08 +01:00
def get_config(self):
return self.config