Compare commits
4 Commits
release/0.
...
release/0.
Author | SHA1 | Date | |
---|---|---|---|
ed54090710 | |||
46866f1e38 | |||
e6a9a37607 | |||
74215a6f80 |
@ -186,6 +186,34 @@ def test_leadership_modif_follower_bool_false(json):
|
|||||||
assert config.value.dict() == output
|
assert config.value.dict() == output
|
||||||
|
|
||||||
|
|
||||||
|
def test_leadership_modif_follower_bool_true_fullname(json):
|
||||||
|
output = {'leader.leader': ['192.168.0.1'],
|
||||||
|
'leader.follower': [None],
|
||||||
|
'leader.follower_boolean': [True],
|
||||||
|
'leader.follower_choice': [None],
|
||||||
|
'leader.follower_integer': [None],
|
||||||
|
'leader.follower_submulti': [[]]}
|
||||||
|
|
||||||
|
config = get_config(json)
|
||||||
|
parser = TiramisuCmdlineParser(config, 'prog.py', fullpath=False)
|
||||||
|
parser.parse_args(['--follower_boolean', '0'])
|
||||||
|
assert config.value.dict() == output
|
||||||
|
|
||||||
|
|
||||||
|
def test_leadership_modif_follower_bool_false_fullname(json):
|
||||||
|
output = {'leader.leader': ['192.168.0.1'],
|
||||||
|
'leader.follower': [None],
|
||||||
|
'leader.follower_boolean': [False],
|
||||||
|
'leader.follower_choice': [None],
|
||||||
|
'leader.follower_integer': [None],
|
||||||
|
'leader.follower_submulti': [[]]}
|
||||||
|
|
||||||
|
config = get_config(json)
|
||||||
|
parser = TiramisuCmdlineParser(config, 'prog.py', fullpath=False)
|
||||||
|
parser.parse_args(['--no-follower_boolean', '0'])
|
||||||
|
assert config.value.dict() == output
|
||||||
|
|
||||||
|
|
||||||
def test_leadership_modif_follower_choice(json):
|
def test_leadership_modif_follower_choice(json):
|
||||||
output = {'leader.leader': ['192.168.0.1'],
|
output = {'leader.leader': ['192.168.0.1'],
|
||||||
'leader.follower': [None],
|
'leader.follower': [None],
|
||||||
@ -209,7 +237,7 @@ def test_leadership_modif_follower_choice_unknown(json):
|
|||||||
[--leader.follower_boolean INDEX]
|
[--leader.follower_boolean INDEX]
|
||||||
[--leader.no-follower_boolean INDEX]
|
[--leader.no-follower_boolean INDEX]
|
||||||
[--leader.follower_choice INDEX [{opt1,opt2}]]
|
[--leader.follower_choice INDEX [{opt1,opt2}]]
|
||||||
prog.py: error: invalid choice: 'opt_unknown' (choose from 'opt1', 'opt2')
|
prog.py: error: argument --leader.follower_choice: invalid choice: 'opt_unknown' (choose from 'opt1', 'opt2')
|
||||||
"""
|
"""
|
||||||
config = get_config(json)
|
config = get_config(json)
|
||||||
parser = TiramisuCmdlineParser(config, 'prog.py')
|
parser = TiramisuCmdlineParser(config, 'prog.py')
|
||||||
|
@ -487,13 +487,13 @@ prog.py: error: unrecognized arguments: --int
|
|||||||
|
|
||||||
def test_readme_cross_tree(json):
|
def test_readme_cross_tree(json):
|
||||||
output = """usage: prog.py "none" [-h] [-v] [-nv] {str,list,int,none}
|
output = """usage: prog.py "none" [-h] [-v] [-nv] {str,list,int,none}
|
||||||
prog.py: error: unrecognized arguments: --int
|
prog.py: error: unrecognized arguments: --root.int
|
||||||
"""
|
"""
|
||||||
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py')
|
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py')
|
||||||
f = StringIO()
|
f = StringIO()
|
||||||
with redirect_stderr(f):
|
with redirect_stderr(f):
|
||||||
try:
|
try:
|
||||||
parser.parse_args(['none', '--int'])
|
parser.parse_args(['none', '--root.int'])
|
||||||
except SystemExit as err:
|
except SystemExit as err:
|
||||||
assert str(err) == "2"
|
assert str(err) == "2"
|
||||||
else:
|
else:
|
||||||
@ -503,13 +503,13 @@ prog.py: error: unrecognized arguments: --int
|
|||||||
|
|
||||||
def test_readme_cross_tree_remove(json):
|
def test_readme_cross_tree_remove(json):
|
||||||
output = """usage: prog.py "none" [-h] [-v] [-nv]
|
output = """usage: prog.py "none" [-h] [-v] [-nv]
|
||||||
prog.py: error: unrecognized arguments: --int
|
prog.py: error: unrecognized arguments: --root.int
|
||||||
"""
|
"""
|
||||||
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', display_modified_value=False)
|
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', display_modified_value=False)
|
||||||
f = StringIO()
|
f = StringIO()
|
||||||
with redirect_stderr(f):
|
with redirect_stderr(f):
|
||||||
try:
|
try:
|
||||||
parser.parse_args(['none', '--int'])
|
parser.parse_args(['none', '--root.int'])
|
||||||
except SystemExit as err:
|
except SystemExit as err:
|
||||||
assert str(err) == "2"
|
assert str(err) == "2"
|
||||||
else:
|
else:
|
||||||
@ -859,3 +859,32 @@ def test_readme_longargument(json):
|
|||||||
parser = TiramisuCmdlineParser(config, 'prog.py')
|
parser = TiramisuCmdlineParser(config, 'prog.py')
|
||||||
parser.parse_args(['list', '--list', 'a', '--v'])
|
parser.parse_args(['list', '--list', 'a', '--v'])
|
||||||
assert config.value.dict() == output
|
assert config.value.dict() == output
|
||||||
|
|
||||||
|
|
||||||
|
def test_readme_unknown_key(json):
|
||||||
|
output1 = """usage: prog.py [-h] [-v] [-nv] {str,list,int,none}
|
||||||
|
prog.py: error: unrecognized arguments: --unknown
|
||||||
|
"""
|
||||||
|
output2 = """usage: prog.py [-h] [-v] [-nv] {str,list,int,none}
|
||||||
|
prog.py: error: unrecognized arguments: --root.unknown
|
||||||
|
"""
|
||||||
|
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', fullpath=False)
|
||||||
|
f = StringIO()
|
||||||
|
with redirect_stderr(f):
|
||||||
|
try:
|
||||||
|
parser.parse_args(['--unknown'])
|
||||||
|
except SystemExit as err:
|
||||||
|
assert str(err) == "2"
|
||||||
|
else:
|
||||||
|
raise Exception('must raises')
|
||||||
|
assert f.getvalue() == output1
|
||||||
|
|
||||||
|
f = StringIO()
|
||||||
|
with redirect_stderr(f):
|
||||||
|
try:
|
||||||
|
parser.parse_args(['--root.unknown'])
|
||||||
|
except SystemExit as err:
|
||||||
|
assert str(err) == "2"
|
||||||
|
else:
|
||||||
|
raise Exception('must raises')
|
||||||
|
assert f.getvalue() == output2
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
from .api import TiramisuCmdlineParser
|
from .api import TiramisuCmdlineParser
|
||||||
|
|
||||||
__version__ = "0.2"
|
__version__ = "0.3"
|
||||||
__all__ = ('TiramisuCmdlineParser',)
|
__all__ = ('TiramisuCmdlineParser',)
|
||||||
|
@ -20,7 +20,7 @@ from gettext import gettext as _
|
|||||||
try:
|
try:
|
||||||
from tiramisu import Config
|
from tiramisu import Config
|
||||||
from tiramisu.error import PropertiesOptionError, RequirementError, LeadershipError
|
from tiramisu.error import PropertiesOptionError, RequirementError, LeadershipError
|
||||||
except ModuleNotFoundError:
|
except ImportError:
|
||||||
Config = None
|
Config = None
|
||||||
from tiramisu_api.error import PropertiesOptionError
|
from tiramisu_api.error import PropertiesOptionError
|
||||||
RequirementError = PropertiesOptionError
|
RequirementError = PropertiesOptionError
|
||||||
@ -29,10 +29,25 @@ try:
|
|||||||
from tiramisu__api import Config as ConfigJson
|
from tiramisu__api import Config as ConfigJson
|
||||||
if Config is None:
|
if Config is None:
|
||||||
Config = ConfigJson
|
Config = ConfigJson
|
||||||
except ModuleNotFoundError:
|
except ImportError:
|
||||||
ConfigJson = Config
|
ConfigJson = Config
|
||||||
|
|
||||||
|
|
||||||
|
def get_choice_list(obj, properties, display):
|
||||||
|
def convert(choice):
|
||||||
|
if isinstance(choice, int):
|
||||||
|
return str(choice)
|
||||||
|
return choice
|
||||||
|
choices = [convert(choice) for choice in obj.value.list()]
|
||||||
|
if choices[0] == '':
|
||||||
|
del choices[0]
|
||||||
|
if display:
|
||||||
|
choices = '{{{}}}'.format(','.join(choices))
|
||||||
|
if 'mandatory' not in properties:
|
||||||
|
choices = '[{}]'.format(choices)
|
||||||
|
return choices
|
||||||
|
|
||||||
|
|
||||||
class TiramisuNamespace(Namespace):
|
class TiramisuNamespace(Namespace):
|
||||||
def __init__(self,
|
def __init__(self,
|
||||||
config: Config,
|
config: Config,
|
||||||
@ -41,6 +56,7 @@ class TiramisuNamespace(Namespace):
|
|||||||
super().__setattr__('_root', root)
|
super().__setattr__('_root', root)
|
||||||
super().__setattr__('list_force_no', {})
|
super().__setattr__('list_force_no', {})
|
||||||
super().__setattr__('list_force_del', {})
|
super().__setattr__('list_force_del', {})
|
||||||
|
super().__setattr__('arguments', {})
|
||||||
self._populate()
|
self._populate()
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
@ -74,6 +90,22 @@ class TiramisuNamespace(Namespace):
|
|||||||
else:
|
else:
|
||||||
_setattr = self._setattr
|
_setattr = self._setattr
|
||||||
true_value = value
|
true_value = value
|
||||||
|
if option.option.type() == 'choice':
|
||||||
|
# HACK if integer in choice
|
||||||
|
values = option.value.list()
|
||||||
|
if isinstance(value, list):
|
||||||
|
int_value = []
|
||||||
|
for val in value:
|
||||||
|
if isinstance(val, str) and val.isdigit():
|
||||||
|
int_val = int(val)
|
||||||
|
if int_val in values:
|
||||||
|
val = int_val
|
||||||
|
int_value.append(val)
|
||||||
|
value = int_value
|
||||||
|
elif value not in values and isinstance(value, str) and value.isdigit():
|
||||||
|
int_value = int(value)
|
||||||
|
if int_value in values:
|
||||||
|
value = int_value
|
||||||
try:
|
try:
|
||||||
if key in self.list_force_del:
|
if key in self.list_force_del:
|
||||||
option.value.pop(value)
|
option.value.pop(value)
|
||||||
@ -81,7 +113,16 @@ class TiramisuNamespace(Namespace):
|
|||||||
_setattr(option, true_key, key, value)
|
_setattr(option, true_key, key, value)
|
||||||
except ValueError as err:
|
except ValueError as err:
|
||||||
if option.option.type() == 'choice':
|
if option.option.type() == 'choice':
|
||||||
raise ValueError("invalid choice: '{}' (choose from {})".format(true_value, ', '.join([f"'{val}'" for val in option.value.list()])))
|
values = option.value.list()
|
||||||
|
if isinstance(true_value, list):
|
||||||
|
for val in value:
|
||||||
|
if val not in values:
|
||||||
|
display_value = val
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
display_value = true_value
|
||||||
|
choices = get_choice_list(option, option.property.get(), False)
|
||||||
|
raise ValueError("argument {}: invalid choice: '{}' (choose from {})".format(self.arguments[key], display_value, ', '.join([f"'{val}'" for val in choices])))
|
||||||
else:
|
else:
|
||||||
raise err
|
raise err
|
||||||
|
|
||||||
@ -164,15 +205,20 @@ class _BuildKwargs:
|
|||||||
is_short_name = self.cmdlineparser._is_short_name(name, 'longargument' in self.properties)
|
is_short_name = self.cmdlineparser._is_short_name(name, 'longargument' in self.properties)
|
||||||
if self.force_no:
|
if self.force_no:
|
||||||
ga_name = self.gen_argument_name(name, is_short_name)
|
ga_name = self.gen_argument_name(name, is_short_name)
|
||||||
self.cmdlineparser.namespace.list_force_no[ga_name] = option.path()
|
ga_path = self.gen_argument_name(option.path(), is_short_name)
|
||||||
|
self.cmdlineparser.namespace.list_force_no[ga_path] = option.path()
|
||||||
elif self.force_del:
|
elif self.force_del:
|
||||||
ga_name = self.gen_argument_name(name, is_short_name)
|
ga_name = self.gen_argument_name(name, is_short_name)
|
||||||
self.cmdlineparser.namespace.list_force_del[ga_name] = option.path()
|
ga_path = self.gen_argument_name(option.path(), is_short_name)
|
||||||
|
self.cmdlineparser.namespace.list_force_del[ga_path] = option.path()
|
||||||
else:
|
else:
|
||||||
ga_name = name
|
ga_name = name
|
||||||
self.kwargs['dest'] = self.gen_argument_name(option.path(), False)
|
self.kwargs['dest'] = self.gen_argument_name(option.path(), False)
|
||||||
self.args = [self.cmdlineparser._gen_argument(ga_name, is_short_name)]
|
argument = self.cmdlineparser._gen_argument(ga_name, is_short_name)
|
||||||
|
self.cmdlineparser.namespace.arguments[option.path()] = argument
|
||||||
|
self.args = [argument]
|
||||||
else:
|
else:
|
||||||
|
self.cmdlineparser.namespace.arguments[option.path()] = option.path()
|
||||||
self.args = [option.path()]
|
self.args = [option.path()]
|
||||||
|
|
||||||
def __setitem__(self,
|
def __setitem__(self,
|
||||||
@ -189,7 +235,9 @@ class _BuildKwargs:
|
|||||||
name = self.gen_argument_name(option.name(), is_short_name)
|
name = self.gen_argument_name(option.name(), is_short_name)
|
||||||
else:
|
else:
|
||||||
name = option.name()
|
name = option.name()
|
||||||
self.args.insert(0, self.cmdlineparser._gen_argument(name, is_short_name))
|
argument = self.cmdlineparser._gen_argument(name, is_short_name)
|
||||||
|
self.cmdlineparser.namespace.arguments[option.path()] = argument
|
||||||
|
self.args.insert(0, argument)
|
||||||
|
|
||||||
def gen_argument_name(self, name, is_short_name):
|
def gen_argument_name(self, name, is_short_name):
|
||||||
if self.force_no:
|
if self.force_no:
|
||||||
@ -328,9 +376,9 @@ class TiramisuCmdlineParser(ArgumentParser):
|
|||||||
if type != 'boolean':
|
if type != 'boolean':
|
||||||
if isinstance(value, list):
|
if isinstance(value, list):
|
||||||
for val in value:
|
for val in value:
|
||||||
self.prog += f' "{val}"'
|
self.prog += ' "{}"'.format(val)
|
||||||
else:
|
else:
|
||||||
self.prog += f' "{value}"'
|
self.prog += ' "{}"'.format(value)
|
||||||
|
|
||||||
def _config_list(self,
|
def _config_list(self,
|
||||||
config: Config,
|
config: Config,
|
||||||
@ -464,15 +512,10 @@ class TiramisuCmdlineParser(ArgumentParser):
|
|||||||
else:
|
else:
|
||||||
kwargs['nargs'] = 2
|
kwargs['nargs'] = 2
|
||||||
if _forhelp and 'mandatory' not in properties:
|
if _forhelp and 'mandatory' not in properties:
|
||||||
metavar = f'[{metavar}]'
|
metavar = '[{}]'.format(metavar)
|
||||||
if option.type() == 'choice':
|
if option.type() == 'choice':
|
||||||
choice_list = obj.value.list()
|
# do not manage choice with argparse there is problem with integer problem
|
||||||
if choice_list[0] == '':
|
kwargs['metavar'] = ('INDEX', get_choice_list(obj, properties, True))
|
||||||
del choice_list[0]
|
|
||||||
choices = '{{{}}}'.format(','.join(choice_list))
|
|
||||||
if 'mandatory' not in properties:
|
|
||||||
choices = f'[{choices}]'
|
|
||||||
kwargs['metavar'] = ('INDEX', choices)
|
|
||||||
else:
|
else:
|
||||||
kwargs['metavar'] = ('INDEX', metavar)
|
kwargs['metavar'] = ('INDEX', metavar)
|
||||||
if force_del:
|
if force_del:
|
||||||
@ -487,10 +530,10 @@ class TiramisuCmdlineParser(ArgumentParser):
|
|||||||
kwargs['metavar'] = 'INDEX'
|
kwargs['metavar'] = 'INDEX'
|
||||||
kwargs['nargs'] = 1
|
kwargs['nargs'] = 1
|
||||||
elif option.type() == 'choice' and not option.isfollower():
|
elif option.type() == 'choice' and not option.isfollower():
|
||||||
kwargs['choices'] = obj.value.list()
|
# do not manage choice with argparse there is problem with integer problem
|
||||||
|
kwargs['choices'] = get_choice_list(obj, properties, False)
|
||||||
else:
|
else:
|
||||||
pass
|
pass
|
||||||
#raise NotImplementedError('not supported yet')
|
|
||||||
actions.setdefault(option.name(), []).append(kwargs)
|
actions.setdefault(option.name(), []).append(kwargs)
|
||||||
for option_is_not_default in options_is_not_default.values():
|
for option_is_not_default in options_is_not_default.values():
|
||||||
self._option_is_not_default(**option_is_not_default)
|
self._option_is_not_default(**option_is_not_default)
|
||||||
|
Reference in New Issue
Block a user