13 Commits

8 changed files with 632 additions and 50 deletions

207
tests/test_choice.py Normal file
View File

@ -0,0 +1,207 @@
from io import StringIO
from contextlib import redirect_stdout, redirect_stderr
import pytest
from tiramisu_cmdline_parser import TiramisuCmdlineParser
from tiramisu import ChoiceOption, OptionDescription, Config
try:
from tiramisu_api import Config as JsonConfig
params = ['tiramisu', 'tiramisu-json']
except:
params = ['tiramisu']
def get_config(json):
positional = ChoiceOption('positional',
'choice the sub argument',
('str', 'list', 'int', 'none'),
properties=('positional', 'mandatory'))
positional_int = ChoiceOption('positional_int',
'choice the sub argument',
(1, 2, 3),
properties=('positional', 'mandatory'))
str_ = ChoiceOption('str',
'choice the sub argument',
('str1', 'str2', 'str3'))
int_ = ChoiceOption('int',
'choice the sub argument',
(1, 2, 3))
int_multi = ChoiceOption('int_multi',
'choice the sub argument',
(1, 2, 3),
multi=True)
od = OptionDescription('od',
'od',
[positional, positional_int, str_, int_, int_multi])
config = Config(od)
config.property.read_write()
if json == 'tiramisu':
return config
jconfig = JsonConfig(config.option.dict())
return jconfig
@pytest.fixture(params=params)
def json(request):
return request.param
def test_choice_positional(json):
output1 = '''usage: prog.py "str" "1" [-h] [--str {str1,str2,str3}] [--int {1,2,3}]
[--int_multi [{1,2,3} [{1,2,3} ...]]]
{str,list,int,none} {1,2,3}
prog.py: error: argument positional: invalid choice: 'error' (choose from 'str', 'list', 'int', 'none')
'''
output2 = '''usage: prog.py "str" "1" [-h] [--str {str1,str2,str3}] [--int {1,2,3}]
[--int_multi [{1,2,3} [{1,2,3} ...]]]
{str,list,int,none} {1,2,3}
prog.py: error: argument positional_int: invalid choice: '4' (choose from '1', '2', '3')
'''
config = get_config(json)
parser = TiramisuCmdlineParser(config, 'prog.py')
parser.parse_args(['str', '1'])
assert config.value.dict() == {'positional': 'str',
'positional_int': 1,
'str': None,
'int': None,
'int_multi': []}
f = StringIO()
with redirect_stderr(f):
try:
parser.parse_args(['error', '1'])
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(['str', '4'])
except SystemExit as err:
assert str(err) == "2"
else:
raise Exception('must raises')
assert f.getvalue() == output2
def test_choice_str(json):
output = """usage: prog.py "str" "1" --str "str3" [-h] [--str {str1,str2,str3}]
[--int {1,2,3}]
[--int_multi [{1,2,3} [{1,2,3} ...]]]
{str,list,int,none} {1,2,3}
prog.py: error: argument --str: invalid choice: 'error' (choose from 'str1', 'str2', 'str3')
"""
config = get_config(json)
parser = TiramisuCmdlineParser(config, 'prog.py')
parser.parse_args(['str', '1', '--str', 'str1'])
assert config.value.dict() == {'positional': 'str',
'positional_int': 1,
'str': 'str1',
'int': None,
'int_multi': []}
parser.parse_args(['str', '1', '--str', 'str2'])
assert config.value.dict() == {'positional': 'str',
'positional_int': 1,
'str': 'str2',
'int': None,
'int_multi': []}
parser.parse_args(['str', '1', '--str', 'str3'])
assert config.value.dict() == {'positional': 'str',
'positional_int': 1,
'str': 'str3',
'int': None,
'int_multi': []}
f = StringIO()
with redirect_stderr(f):
try:
parser.parse_args(['str', '1', '--str', 'error'])
except SystemExit as err:
assert str(err) == "2"
else:
raise Exception('must raises')
assert f.getvalue() == output
assert config.value.dict() == {'positional': 'str',
'positional_int': 1,
'str': 'str3',
'int': None,
'int_multi': []}
def test_choice_int(json):
output = """usage: prog.py "str" "1" --int "1" [-h] [--str {str1,str2,str3}]
[--int {1,2,3}]
[--int_multi [{1,2,3} [{1,2,3} ...]]]
{str,list,int,none} {1,2,3}
prog.py: error: argument --int: invalid choice: '4' (choose from '1', '2', '3')
"""
config = get_config(json)
parser = TiramisuCmdlineParser(config, 'prog.py')
parser.parse_args(['str', '1', '--int', '1'])
assert config.value.dict() == {'positional': 'str',
'positional_int': 1,
'str': None,
'int': 1,
'int_multi': []}
f = StringIO()
with redirect_stderr(f):
try:
parser.parse_args(['str', '1', '--int', '4'])
except SystemExit as err:
assert str(err) == "2"
else:
raise Exception('must raises')
assert f.getvalue() == output
assert config.value.dict() == {'positional': 'str',
'positional_int': 1,
'str': None,
'int': 1,
'int_multi': []}
def test_choice_int_multi(json):
output = """usage: prog.py "str" "1" --int_multi "1" "2" [-h] [--str {str1,str2,str3}]
[--int {1,2,3}]
[--int_multi [{1,2,3} [{1,2,3} ...]]]
{str,list,int,none} {1,2,3}
prog.py: error: argument --int_multi: invalid choice: '4' (choose from '1', '2', '3')
"""
config = get_config(json)
parser = TiramisuCmdlineParser(config, 'prog.py')
parser.parse_args(['str', '1', '--int_multi', '1', '2'])
assert config.value.dict() == {'positional': 'str',
'positional_int': 1,
'str': None,
'int': None,
'int_multi': [1, 2]}
f = StringIO()
with redirect_stderr(f):
try:
parser.parse_args(['str', '1', '--int_multi', '4'])
except SystemExit as err:
assert str(err) == "2"
else:
raise Exception('must raises')
assert f.getvalue() == output
assert config.value.dict() == {'positional': 'str',
'positional_int': 1,
'str': None,
'int': None,
'int_multi': [1, 2]}
f = StringIO()
with redirect_stderr(f):
try:
parser.parse_args(['str', '1', '--int_multi', '1', '4'])
except SystemExit as err:
assert str(err) == "2"
else:
raise Exception('must raises')
assert f.getvalue() == output
assert config.value.dict() == {'positional': 'str',
'positional_int': 1,
'str': None,
'int': None,
'int_multi': [1, 2]}

View File

@ -7,7 +7,11 @@ from argparse import RawDescriptionHelpFormatter
from tiramisu_cmdline_parser import TiramisuCmdlineParser
from tiramisu import IntOption, StrOption, BoolOption, ChoiceOption, \
SymLinkOption, OptionDescription, Config
from tiramisu_api import Config as JsonConfig
try:
from tiramisu_api import Config as JsonConfig
params = ['tiramisu', 'tiramisu-json']
except:
params = ['tiramisu']
@ -31,7 +35,7 @@ def get_config(json):
return jconfig
@pytest.fixture(params=['tiramisu', 'tiramisu-json'])
@pytest.fixture(params=params)
def json(request):
return request.param

View File

@ -6,7 +6,11 @@ import pytest
from tiramisu_cmdline_parser import TiramisuCmdlineParser
from tiramisu import IntOption, StrOption, BoolOption, ChoiceOption, \
SymLinkOption, OptionDescription, Leadership, Config, submulti
from tiramisu_api import Config as JsonConfig
try:
from tiramisu_api import Config as JsonConfig
params = ['tiramisu', 'tiramisu-json']
except:
params = ['tiramisu']
def get_config(json, with_mandatory=False):
@ -31,7 +35,7 @@ def get_config(json, with_mandatory=False):
return jconfig
@pytest.fixture(params=['tiramisu', 'tiramisu-api'])
@pytest.fixture(params=params)
def json(request):
return request.param
@ -186,6 +190,34 @@ def test_leadership_modif_follower_bool_false(json):
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):
output = {'leader.leader': ['192.168.0.1'],
'leader.follower': [None],
@ -209,7 +241,7 @@ def test_leadership_modif_follower_choice_unknown(json):
[--leader.follower_boolean INDEX]
[--leader.no-follower_boolean INDEX]
[--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)
parser = TiramisuCmdlineParser(config, 'prog.py')
@ -331,6 +363,53 @@ prog.py: error: the following arguments are required: --leader.follower_submulti
assert config.value.dict() == output
def test_leadership_modif_mandatory_remove(json):
output = {'leader.leader': ['192.168.1.1'],
'leader.follower': [None],
'leader.follower_mandatory': ['255.255.255.128'],
'leader.follower_boolean': [None],
'leader.follower_choice': [None],
'leader.follower_integer': [None],
'leader.follower_submulti': [['255.255.255.128']]}
output2 = """usage: prog.py --leader.leader "192.168.1.1" [-h] [--leader.pop-leader INDEX]
[--leader.follower INDEX [FOLLOWER]]
--leader.follower_submulti INDEX
[FOLLOWER_SUBMULTI ...]
[--leader.follower_integer INDEX [FOLLOWER_INTEGER]]
[--leader.follower_boolean INDEX]
[--leader.no-follower_boolean INDEX]
[--leader.follower_choice INDEX [{opt1,opt2}]]
--leader.follower_mandatory INDEX
FOLLOWER_MANDATORY
prog.py: error: the following arguments are required: --leader.follower_submulti"""
config = get_config(json, with_mandatory=True)
parser = TiramisuCmdlineParser(config, 'prog.py', display_modified_value=False)
f = StringIO()
with redirect_stderr(f):
try:
parser.parse_args(['--leader.leader', '192.168.1.1'])
except SystemExit as err:
assert str(err) == "2"
else:
raise Exception('must raises')
assert f.getvalue() == output2 + ', --leader.follower_mandatory\n'
f = StringIO()
with redirect_stderr(f):
try:
parser.parse_args(['--leader.leader', '192.168.1.1',
'--leader.follower_mandatory', '0', '255.255.255.128'])
except SystemExit as err:
assert str(err) == "2"
else:
raise Exception('must raises')
assert f.getvalue() == output2 + '\n'
parser.parse_args(['--leader.leader', '192.168.1.1',
'--leader.follower_submulti', '0', '255.255.255.128',
'--leader.follower_mandatory', '0', '255.255.255.128'])
assert config.value.dict() == output
def test_leadership_modif_mandatory_unvalidate(json):
output = {'leader.leader': ['192.168.1.1'],
'leader.follower': [None],

View File

@ -6,7 +6,11 @@ import pytest
from tiramisu_cmdline_parser import TiramisuCmdlineParser
from tiramisu import IntOption, StrOption, BoolOption, ChoiceOption, \
SymLinkOption, OptionDescription, Config
from tiramisu_api import Config as JsonConfig
try:
from tiramisu_api import Config as JsonConfig
params = ['tiramisu', 'tiramisu-json']
except:
params = ['tiramisu']
def get_config(json, has_tree=False, default_verbosity=False, add_long=False, add_store_false=False, empty_optiondescription=False):
@ -59,7 +63,7 @@ def get_config(json, has_tree=False, default_verbosity=False, add_long=False, ad
return jconfig
@pytest.fixture(params=['tiramisu', 'tiramisu-json'])
@pytest.fixture(params=params)
def json(request):
return request.param

View File

@ -6,7 +6,11 @@ import pytest
from tiramisu_cmdline_parser import TiramisuCmdlineParser
from tiramisu import IntOption, StrOption, BoolOption, ChoiceOption, \
SymLinkOption, OptionDescription, Config
from tiramisu_api import Config as JsonConfig
try:
from tiramisu_api import Config as JsonConfig
params = ['tiramisu', 'tiramisu-json']
except:
params = ['tiramisu']
def get_config(json, has_tree=False, default_verbosity=False, add_long=False, add_store_false=False):
@ -67,7 +71,7 @@ def get_config(json, has_tree=False, default_verbosity=False, add_long=False, ad
return jconfig
@pytest.fixture(params=['tiramisu', 'tiramisu-json'])
@pytest.fixture(params=params)
def json(request):
return request.param
@ -154,6 +158,27 @@ optional arguments:
assert f.getvalue() == output
def test_readme_help_modif_positional_remove(json):
output = """usage: prog.py "str" [-h] [-v] [-nv] --str STR
optional arguments:
-h, --help show this help message and exit
-v, --verbosity increase output verbosity
-nv, --no-verbosity
--str STR string option
"""
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', display_modified_value=False)
f = StringIO()
with redirect_stdout(f):
try:
parser.parse_args(['str', '--help'])
except SystemExit as err:
assert str(err) == "0"
else:
raise Exception('must raises')
assert f.getvalue() == output
def test_readme_help_modif(json):
output = """usage: prog.py "str" --str "toto" [-h] [-v] [-nv] --str STR
{str,list,int,none}
@ -179,7 +204,27 @@ optional arguments:
assert f.getvalue() == output
def test_readme_help_modif_short1(json):
def test_readme_help_modif_remove(json):
output = """usage: prog.py "str" --str "toto" [-h] [-v] [-nv]
optional arguments:
-h, --help show this help message and exit
-v, --verbosity increase output verbosity
-nv, --no-verbosity
"""
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', display_modified_value=False)
f = StringIO()
with redirect_stdout(f):
try:
parser.parse_args(['str', '--str', 'toto', '--help'])
except SystemExit as err:
assert str(err) == "0"
else:
raise Exception('must raises')
assert f.getvalue() == output
def test_readme_help_modif_short(json):
output = """usage: prog.py "str" -v [-h] [-v] [-nv] --str STR {str,list,int,none}
positional arguments:
@ -203,7 +248,28 @@ optional arguments:
assert f.getvalue() == output
def test_readme_help_modif_short_no(json):
def test_readme_help_modif_short_remove(json):
# FIXME -v -nv ?? pas de description
output = """usage: prog.py "str" -v [-h] [-nv] --str STR
optional arguments:
-h, --help show this help message and exit
-nv, --no-verbosity increase output verbosity
--str STR string option
"""
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', display_modified_value=False)
f = StringIO()
with redirect_stdout(f):
try:
parser.parse_args(['str', '-v', '--help'])
except SystemExit as err:
assert str(err) == "0"
else:
raise Exception('must raises')
assert f.getvalue() == output
def test_readme_help_modif_short_no1(json):
output = """usage: prog.py "str" -v [-h] [-v] [-nv] --str STR {str,list,int,none}
positional arguments:
@ -227,6 +293,26 @@ optional arguments:
assert f.getvalue() == output
def test_readme_help_modif_short_no_remove(json):
output = """usage: prog.py "str" -v [-h] [-v] --str STR
optional arguments:
-h, --help show this help message and exit
-v, --verbosity increase output verbosity
--str STR string option
"""
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', display_modified_value=False)
f = StringIO()
with redirect_stdout(f):
try:
parser.parse_args(['str', '-nv', '--help'])
except SystemExit as err:
assert str(err) == "0"
else:
raise Exception('must raises')
assert f.getvalue() == output
def test_readme_positional_mandatory(json):
output = """usage: prog.py [-h] [-v] [-nv] {str,list,int,none}
prog.py: error: the following arguments are required: cmd
@ -291,6 +377,22 @@ prog.py: error: the following arguments are required: --str
assert f.getvalue() == output
def test_readme_mandatory_remove(json):
output = """usage: prog.py "str" [-h] [-v] [-nv] --str STR
prog.py: error: the following arguments are required: --str
"""
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', display_modified_value=False)
f = StringIO()
with redirect_stderr(f):
try:
parser.parse_args(['str'])
except SystemExit as err:
assert str(err) == "2"
else:
raise Exception('must raises')
assert f.getvalue() == output
def test_readme_mandatory_tree(json):
output = """usage: prog.py "str" [-h] [-v] [-nv] --root.str STR {str,list,int,none}
prog.py: error: the following arguments are required: --root.str
@ -307,6 +409,22 @@ prog.py: error: the following arguments are required: --root.str
assert f.getvalue() == output
def test_readme_mandatory_tree_remove(json):
output = """usage: prog.py "str" [-h] [-v] [-nv] --root.str STR
prog.py: error: the following arguments are required: --root.str
"""
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', display_modified_value=False)
f = StringIO()
with redirect_stderr(f):
try:
parser.parse_args(['str'])
except SystemExit as err:
assert str(err) == "2"
else:
raise Exception('must raises')
assert f.getvalue() == output
def test_readme_mandatory_tree_flatten(json):
output = """usage: prog.py "str" [-h] [-v] [-nv] --str STR {str,list,int,none}
prog.py: error: the following arguments are required: --str
@ -323,6 +441,22 @@ prog.py: error: the following arguments are required: --str
assert f.getvalue() == output
def test_readme_mandatory_tree_flatten_remove(json):
output = """usage: prog.py "str" [-h] [-v] [-nv] --str STR
prog.py: error: the following arguments are required: --str
"""
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', fullpath=False, display_modified_value=False)
f = StringIO()
with redirect_stderr(f):
try:
parser.parse_args(['str'])
except SystemExit as err:
assert str(err) == "2"
else:
raise Exception('must raises')
assert f.getvalue() == output
def test_readme_cross(json):
output = """usage: prog.py "none" [-h] [-v] [-nv] {str,list,int,none}
prog.py: error: unrecognized arguments: --int
@ -331,7 +465,23 @@ prog.py: error: unrecognized arguments: --int
f = StringIO()
with redirect_stderr(f):
try:
parser.parse_args(['none', '--int'])
parser.parse_args(['none', '--int', '1'])
except SystemExit as err:
assert str(err) == "2"
else:
raise Exception('must raises')
assert f.getvalue() == output
def test_readme_cross_remove(json):
output = """usage: prog.py "none" [-h] [-v] [-nv]
prog.py: error: unrecognized arguments: --int
"""
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', display_modified_value=False)
f = StringIO()
with redirect_stderr(f):
try:
parser.parse_args(['none', '--int', '1'])
except SystemExit as err:
assert str(err) == "2"
else:
@ -341,13 +491,29 @@ prog.py: error: unrecognized arguments: --int
def test_readme_cross_tree(json):
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')
f = StringIO()
with redirect_stderr(f):
try:
parser.parse_args(['none', '--int'])
parser.parse_args(['none', '--root.int', '1'])
except SystemExit as err:
assert str(err) == "2"
else:
raise Exception('must raises')
assert f.getvalue() == output
def test_readme_cross_tree_remove(json):
output = """usage: prog.py "none" [-h] [-v] [-nv]
prog.py: error: unrecognized arguments: --root.int
"""
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', display_modified_value=False)
f = StringIO()
with redirect_stderr(f):
try:
parser.parse_args(['none', '--root.int', '1'])
except SystemExit as err:
assert str(err) == "2"
else:
@ -363,7 +529,23 @@ prog.py: error: unrecognized arguments: --int
f = StringIO()
with redirect_stderr(f):
try:
parser.parse_args(['none', '--int'])
parser.parse_args(['none', '--int', '1'])
except SystemExit as err:
assert str(err) == "2"
else:
raise Exception('must raises')
assert f.getvalue() == output
def test_readme_cross_tree_flatten_remove(json):
output = """usage: prog.py "none" [-h] [-v] [-nv]
prog.py: error: unrecognized arguments: --int
"""
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', fullpath=False, display_modified_value=False)
f = StringIO()
with redirect_stderr(f):
try:
parser.parse_args(['none', '--int', '1'])
except SystemExit as err:
assert str(err) == "2"
else:
@ -681,3 +863,32 @@ def test_readme_longargument(json):
parser = TiramisuCmdlineParser(config, 'prog.py')
parser.parse_args(['list', '--list', 'a', '--v'])
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

View File

@ -6,10 +6,14 @@ from contextlib import redirect_stderr
from tiramisu_cmdline_parser import TiramisuCmdlineParser
from tiramisu import IntOption, StrOption, BoolOption, ChoiceOption, \
SymLinkOption, OptionDescription, Config
from tiramisu_api import Config as JsonConfig
try:
from tiramisu_api import Config as JsonConfig
params = ['tiramisu', 'tiramisu-json']
except:
params = ['tiramisu']
@pytest.fixture(params=['tiramisu', 'tiramisu-json'])
@pytest.fixture(params=params)
def json(request):
return request.param

View File

@ -1,4 +1,9 @@
from .api import TiramisuCmdlineParser
try:
from .api import TiramisuCmdlineParser
except ImportError as err:
import warnings
warnings.warn("cannot not import TiramisuCmdlineParser {err}", ImportWarning)
TiramisuCmdlineParser = None
__version__ = "0.1"
__version__ = "0.5"
__all__ = ('TiramisuCmdlineParser',)

View File

@ -20,19 +20,34 @@ from gettext import gettext as _
try:
from tiramisu import Config
from tiramisu.error import PropertiesOptionError, RequirementError, LeadershipError
except ModuleNotFoundError:
except ImportError:
Config = None
from tiramisu_api.error import PropertiesOptionError
RequirementError = PropertiesOptionError
LeadershipError = ValueError
try:
from tiramisu__api import Config as ConfigJson
from tiramisu_api import Config as ConfigJson
if Config is None:
Config = ConfigJson
except ModuleNotFoundError:
except ImportError:
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 and choices[0] == '':
del choices[0]
if display:
choices = '{{{}}}'.format(','.join(choices))
if 'mandatory' not in properties:
choices = '[{}]'.format(choices)
return choices
class TiramisuNamespace(Namespace):
def __init__(self,
config: Config,
@ -41,6 +56,7 @@ class TiramisuNamespace(Namespace):
super().__setattr__('_root', root)
super().__setattr__('list_force_no', {})
super().__setattr__('list_force_del', {})
super().__setattr__('arguments', {})
self._populate()
super().__init__()
@ -74,6 +90,22 @@ class TiramisuNamespace(Namespace):
else:
_setattr = self._setattr
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:
if key in self.list_force_del:
option.value.pop(value)
@ -81,7 +113,16 @@ class TiramisuNamespace(Namespace):
_setattr(option, true_key, key, value)
except ValueError as err:
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:
raise err
@ -94,7 +135,10 @@ class TiramisuNamespace(Namespace):
value is not None and \
not isinstance(value, list):
value = [value]
option.value.set(value)
try:
option.value.set(value)
except PropertiesOptionError:
raise AttributeError('unrecognized arguments: {}'.format(self.arguments[key]))
def _setattr_follower(self,
option: 'Option',
@ -147,13 +191,15 @@ class _BuildKwargs:
cmdlineparser: 'TiramisuCmdlineParser',
properties: List[str],
force_no: bool,
force_del: bool) -> None:
force_del: bool,
display_modified_value: bool,
not_display: bool) -> None:
self.kwargs = {}
self.cmdlineparser = cmdlineparser
self.properties = properties
self.force_no = force_no
self.force_del = force_del
if not self.force_no and not self.force_del:
if (not self.force_no or (not_display and not display_modified_value)) and not self.force_del:
description = option.doc()
if not description:
description = description.replace('%', '%%')
@ -162,15 +208,20 @@ class _BuildKwargs:
is_short_name = self.cmdlineparser._is_short_name(name, 'longargument' in self.properties)
if self.force_no:
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:
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:
ga_name = name
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:
self.cmdlineparser.namespace.arguments[option.path()] = option.path()
self.args = [option.path()]
def __setitem__(self,
@ -187,7 +238,9 @@ class _BuildKwargs:
name = self.gen_argument_name(option.name(), is_short_name)
else:
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):
if self.force_no:
@ -223,21 +276,29 @@ class TiramisuCmdlineParser(ArgumentParser):
root: str=None,
fullpath: bool=True,
remove_empty_od: bool=False,
display_modified_value: bool=True,
formatter_class=HelpFormatter,
unrestraint: bool=False,
_forhelp: bool=False,
**kwargs):
self.fullpath = fullpath
self.config = config
self.root = root
self.remove_empty_od = remove_empty_od
self.unrestraint = unrestraint
self.display_modified_value = display_modified_value
if TiramisuHelpFormatter not in formatter_class.__mro__:
formatter_class = type('TiramisuHelpFormatter', (TiramisuHelpFormatter, formatter_class), {})
formatter_class.remove_empty_od = self.remove_empty_od
kwargs['formatter_class'] = formatter_class
if self.root is None:
subconfig = self.config.option
if not _forhelp and self.unrestraint:
subconfig = self.config.unrestraint
else:
subconfig = self.config.option(self.root)
subconfig = self.config
if self.root is None:
subconfig = subconfig.option
else:
subconfig = subconfig.option(self.root)
self.namespace = TiramisuNamespace(self.config, self.root)
super().__init__(*args, **kwargs)
self.register('action', 'help', _TiramisuHelpAction)
@ -278,7 +339,7 @@ class TiramisuCmdlineParser(ArgumentParser):
def _parse_known_args(self, args=None, namespace=None):
try:
namespace_, args_ = super()._parse_known_args(args, namespace)
except (ValueError, LeadershipError) as err:
except (ValueError, LeadershipError, AttributeError) as err:
self.error(err)
if args != args_ and args_ and args_[0].startswith(self.prefix_chars):
# option that was disabled are no more disable
@ -287,9 +348,11 @@ class TiramisuCmdlineParser(ArgumentParser):
self.prog,
root=self.root,
remove_empty_od=self.remove_empty_od,
display_modified_value=self.display_modified_value,
formatter_class=self.formatter_class,
epilog=self.epilog,
description=self.description,
unrestraint=self.unrestraint,
fullpath=self.fullpath)
namespace_, args_ = new_parser._parse_known_args(args_, new_parser.namespace)
else:
@ -323,9 +386,9 @@ class TiramisuCmdlineParser(ArgumentParser):
if type != 'boolean':
if isinstance(value, list):
for val in value:
self.prog += f' "{val}"'
self.prog += ' "{}"'.format(val)
else:
self.prog += f' "{value}"'
self.prog += ' "{}"'.format(value)
def _config_list(self,
config: Config,
@ -391,8 +454,11 @@ class TiramisuCmdlineParser(ArgumentParser):
leadership_len = len(value)
elif option.isfollower():
value = []
for index in range(leadership_len):
value.append(self.config.option(obj.option.path(), index).value.get())
try:
for index in range(leadership_len):
value.append(self.config.option(obj.option.path(), index).value.get())
except:
value = None
else:
value = obj.value.get()
if self.fullpath and prefix:
@ -401,12 +467,15 @@ class TiramisuCmdlineParser(ArgumentParser):
properties = obj.option.properties()
else:
properties = obj.property.get()
kwargs = _BuildKwargs(name, option, self, properties, force_no, force_del)
if not option.isfollower() and _forhelp and not obj.owner.isdefault() and value is not None and not force_no:
not_display = not option.isfollower() and not obj.owner.isdefault() and value is not None
kwargs = _BuildKwargs(name, option, self, properties, force_no, force_del, self.display_modified_value, not_display)
if _forhelp and not_display and ((value is not False and not force_no) or (value is False and force_no)):
options_is_not_default[option.name()] = {'properties': properties,
'type': option.type(),
'name': name,
'value': value}
if not self.display_modified_value:
continue
if 'positional' in properties:
if option.type() == 'boolean':
raise ValueError(_('boolean option must not be positional'))
@ -456,15 +525,10 @@ class TiramisuCmdlineParser(ArgumentParser):
else:
kwargs['nargs'] = 2
if _forhelp and 'mandatory' not in properties:
metavar = f'[{metavar}]'
metavar = '[{}]'.format(metavar)
if option.type() == 'choice':
choice_list = obj.value.list()
if choice_list[0] == '':
del choice_list[0]
choices = '{{{}}}'.format(','.join(choice_list))
if 'mandatory' not in properties:
choices = f'[{choices}]'
kwargs['metavar'] = ('INDEX', choices)
# do not manage choice with argparse there is problem with integer problem
kwargs['metavar'] = ('INDEX', get_choice_list(obj, properties, True))
else:
kwargs['metavar'] = ('INDEX', metavar)
if force_del:
@ -479,10 +543,12 @@ class TiramisuCmdlineParser(ArgumentParser):
kwargs['metavar'] = 'INDEX'
kwargs['nargs'] = 1
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)
elif option.type() == 'float':
kwargs['type'] = float
else:
pass
#raise NotImplementedError('not supported yet')
actions.setdefault(option.name(), []).append(kwargs)
for option_is_not_default in options_is_not_default.values():
self._option_is_not_default(**option_is_not_default)
@ -548,6 +614,7 @@ class TiramisuCmdlineParser(ArgumentParser):
root=self.root,
fullpath=self.fullpath,
remove_empty_od=self.remove_empty_od,
display_modified_value=self.display_modified_value,
formatter_class=self.formatter_class,
epilog=self.epilog,
description=self.description,
@ -560,6 +627,7 @@ class TiramisuCmdlineParser(ArgumentParser):
root=self.root,
fullpath=self.fullpath,
remove_empty_od=self.remove_empty_od,
display_modified_value=self.display_modified_value,
formatter_class=self.formatter_class,
epilog=self.epilog,
description=self.description,