Compare commits

..

12 commits

11 changed files with 677 additions and 318 deletions

22
CHANGELOG.md Normal file
View file

@ -0,0 +1,22 @@
## 0.6.1rc0 (2024-11-06)
### Fix
- update tiramisu dependency
## 0.6.0 (2024-11-01)
### Fix
- black
## 0.6.0rc0 (2024-10-31)
### Feat
- pyproject.toml
- portage to tiramisu 5.0
### Fix
- only first value

41
pyproject.toml Normal file
View file

@ -0,0 +1,41 @@
[build-system]
build-backend = "flit_core.buildapi"
requires = ["flit_core >=3.8.0,<4"]
[project]
name = "tiramisu_cmdline_parser"
version = "0.6.1"
authors = [{name = "Emmanuel Garette", email = "gnunux@gnunux.info"}]
readme = "README.md"
description = "command-line parser using Tiramisu"
requires-python = ">=3.8"
license = {file = "LICENSE"}
classifiers = [
"License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)",
"Programming Language :: Python",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3",
"Operating System :: OS Independent",
"Natural Language :: English",
"Natural Language :: French",
]
dependencies = [
"tiramisu >= 5.0,<6",
]
[project.urls]
Home = "https://forge.cloud.silique.fr/stove/tiramisu-cmdline-parser"
[tool.commitizen]
name = "cz_conventional_commits"
tag_format = "$version"
version_scheme = "pep440"
version_provider = "pep621"
#update_changelog_on_bump = true
changelog_merge_prerelease = true

View file

@ -1,34 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import os
from tiramisu_cmdline_parser import __version__
PACKAGE_NAME = os.environ.get('PACKAGE_DST', 'tiramisu_cmdline_parser')
setup(
version=__version__,
author="Tiramisu's team",
author_email='gnunux@gnunux.info',
name=PACKAGE_NAME,
description="command-line parser using Tiramisu.",
url='https://framagit.org/tiramisu/tiramisu-cmdline-parser',
license='GNU Library or Lesser General Public License (LGPL)',
install_requires=["tiramisu>=5.0"],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)",
"Operating System :: OS Independent",
"Natural Language :: English",
"Natural Language :: French",
],
long_description="""\
tiramisu-cmdline-parser
---------------------------------
Python3 parser for command-line options and arguments using Tiramisu engine.
""",
include_package_data=True,
packages=find_packages(include=['tiramisu_cmdline_parser'])
)

View file

@ -26,7 +26,7 @@ def get_config(json):
properties=('positional', 'mandatory')) properties=('positional', 'mandatory'))
str_ = ChoiceOption('str', str_ = ChoiceOption('str',
'choice the sub argument', 'choice the sub argument',
('str1', 'str2', 'str3')) ('str1', 'str2', 'str3', None))
int_ = ChoiceOption('int', int_ = ChoiceOption('int',
'choice the sub argument', 'choice the sub argument',
(1, 2, 3)) (1, 2, 3))

107
tests/test_default.py Normal file
View file

@ -0,0 +1,107 @@
from io import StringIO
from contextlib import redirect_stdout, redirect_stderr
import pytest
from tiramisu_cmdline_parser import TiramisuCmdlineParser
from tiramisu import IntOption, StrOption, BoolOption, ChoiceOption, \
OptionDescription, Config
try:
from tiramisu_api import Config as JsonConfig
#params = ['tiramisu', 'tiramisu-json']
params = ['tiramisu']
except:
params = ['tiramisu']
from .utils import TestHelpFormatter, to_dict
def get_config(json, has_tree=False, default_verbosity=False, add_long=False, add_store_false=False):
choiceoption = ChoiceOption('cmd',
'choice the sub argument',
('str', 'list', 'int', 'none'),
properties=('mandatory',))
booloption = BoolOption('verbosity',
'increase output verbosity',
default=default_verbosity,
)
str_ = StrOption('str',
'string option',
default='default'
)
list_ = StrOption('list',
'list string option',
multi=True,
default=['default'],
)
int_ = IntOption('int',
'int option',
default=10,
)
root = OptionDescription('root',
'root',
[choiceoption,
booloption,
str_,
list_,
int_
])
if has_tree:
root = OptionDescription('root',
'root',
[root])
config = Config(root)
config.property.read_write()
if add_store_false:
config.option('verbosity').property.add('storefalse')
if add_long:
config.option('verbosity').property.add('longargument')
if json == 'tiramisu':
return config
jconfig = JsonConfig(config.option.dict())
return jconfig
@pytest.fixture(params=params)
def json(request):
return request.param
def test_readme_help(json):
output = """usage: prog.py [-h] --cmd {str,list,int,none} [--verbosity] [--no-verbosity] [--str [STR]] [--list [LIST ...]] [--int [INT]]
options:
-h, --help show this help message and exit
--cmd {str,list,int,none}
choice the sub argument
--verbosity increase output verbosity (default: False)
--no-verbosity
--str [STR] string option (default: default)
--list [LIST ...] list string option (default: default)
--int [INT] int option (default: 10)
"""
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', formatter_class=TestHelpFormatter)
f = StringIO()
with redirect_stdout(f):
parser.print_help()
assert f.getvalue() == output
def test_readme_help2(json):
output = """usage: prog.py [-h] --cmd {str,list,int,none} [--verbosity] [--no-verbosity] [--str [STR]] [--list [LIST ...]] [--int [INT]]
options:
-h, --help show this help message and exit
--cmd {str,list,int,none}
choice the sub argument
--verbosity increase output verbosity (default: True)
--no-verbosity
--str [STR] string option (default: default)
--list [LIST ...] list string option (default: default)
--int [INT] int option (default: 10)
"""
parser = TiramisuCmdlineParser(get_config(json, default_verbosity=True), 'prog.py', formatter_class=TestHelpFormatter)
f = StringIO()
with redirect_stdout(f):
parser.print_help()
assert f.getvalue() == output

View file

@ -5,7 +5,7 @@ import pytest
from tiramisu_cmdline_parser import TiramisuCmdlineParser from tiramisu_cmdline_parser import TiramisuCmdlineParser
from tiramisu import IntOption, StrOption, BoolOption, ChoiceOption, \ from tiramisu import IntOption, StrOption, BoolOption, ChoiceOption, \
OptionDescription, Leadership, Config, submulti OptionDescription, Leadership, SymLinkOption, Config, submulti
try: try:
from tiramisu_api import Config as JsonConfig from tiramisu_api import Config as JsonConfig
# params = ['tiramisu', 'tiramisu-json'] # params = ['tiramisu', 'tiramisu-json']
@ -16,8 +16,14 @@ except:
from .utils import TestHelpFormatter, to_dict from .utils import TestHelpFormatter, to_dict
def get_config(json, with_mandatory=False): def get_config(json, with_mandatory=False, with_symlink=False, with_default_value=True):
leader = StrOption('leader', "Leader var", ['192.168.0.1'], multi=True) if with_default_value:
default = ['192.168.0.1']
else:
default = []
leader = StrOption('leader', "Leader var", default, multi=True)
if with_symlink:
link_leader = SymLinkOption('l', leader)
follower = StrOption('follower', "Follower", multi=True) follower = StrOption('follower', "Follower", multi=True)
if with_mandatory: if with_mandatory:
properties = ('mandatory',) properties = ('mandatory',)
@ -25,9 +31,14 @@ def get_config(json, with_mandatory=False):
properties = None properties = None
follower_submulti = StrOption('follower_submulti', "Follower submulti", multi=submulti, properties=properties) follower_submulti = StrOption('follower_submulti', "Follower submulti", multi=submulti, properties=properties)
follower_integer = IntOption('follower_integer', "Follower integer", multi=True) follower_integer = IntOption('follower_integer', "Follower integer", multi=True)
if with_symlink:
link_follower = SymLinkOption('i', follower_integer)
follower_boolean = BoolOption('follower_boolean', "Follower boolean", multi=True) follower_boolean = BoolOption('follower_boolean', "Follower boolean", multi=True)
follower_choice = ChoiceOption('follower_choice', "Follower choice", ('opt1', 'opt2'), multi=True) follower_choice = ChoiceOption('follower_choice', "Follower choice", ('opt1', 'opt2'), multi=True)
opt_list = [leader, follower, follower_submulti, follower_integer, follower_boolean, follower_choice] opt_list = [leader, follower, follower_submulti, follower_integer, follower_boolean, follower_choice]
if with_symlink:
opt_list.append(link_leader)
opt_list.append(link_follower)
if with_mandatory: if with_mandatory:
opt_list.append(StrOption('follower_mandatory', "Follower mandatory", multi=True, properties=('mandatory',))) opt_list.append(StrOption('follower_mandatory', "Follower mandatory", multi=True, properties=('mandatory',)))
leadership = Leadership('leader', 'leader', opt_list) leadership = Leadership('leader', 'leader', opt_list)
@ -74,6 +85,81 @@ leader:
assert f.getvalue() == output assert f.getvalue() == output
def test_leadership_help_no_pop(json):
output = """usage: prog.py [-h] [--leader.leader [LEADER ...]] [--leader.follower INDEX [FOLLOWER]] --leader.follower_submulti INDEX [FOLLOWER_SUBMULTI ...] [--leader.follower_integer INDEX [FOLLOWER_INTEGER]] [--leader.follower_boolean INDEX] [--leader.follower_choice INDEX [{opt1,opt2}]] --leader.follower_mandatory INDEX FOLLOWER_MANDATORY
options:
-h, --help show this help message and exit
leader:
--leader.leader [LEADER ...]
Leader var
--leader.follower INDEX [FOLLOWER]
Follower
--leader.follower_submulti INDEX [FOLLOWER_SUBMULTI ...]
Follower submulti
--leader.follower_integer INDEX [FOLLOWER_INTEGER]
Follower integer
--leader.follower_boolean INDEX
Follower boolean
--leader.follower_choice INDEX [{opt1,opt2}]
Follower choice
--leader.follower_mandatory INDEX FOLLOWER_MANDATORY
Follower mandatory
"""
parser = TiramisuCmdlineParser(get_config(json, with_mandatory=True), 'prog.py', add_extra_options=False, formatter_class=TestHelpFormatter)
f = StringIO()
with redirect_stdout(f):
parser.print_help()
assert f.getvalue() == output
def test_leadership_help_short_no_default(json):
output = """usage: prog.py [-h] [-l [LEADER ...]]
options:
-h, --help show this help message and exit
leader:
-l [LEADER ...], --leader.leader [LEADER ...]
Leader var
"""
parser = TiramisuCmdlineParser(get_config(json, with_mandatory=True, with_symlink=True, with_default_value=False), 'prog.py', add_extra_options=False, formatter_class=TestHelpFormatter)
f = StringIO()
with redirect_stdout(f):
parser.print_help()
assert f.getvalue() == output
def test_leadership_help_short(json):
output = """usage: prog.py [-h] [-l [LEADER ...]] [--leader.follower INDEX [FOLLOWER]] --leader.follower_submulti INDEX [FOLLOWER_SUBMULTI ...] [-i INDEX [FOLLOWER_INTEGER]] [--leader.follower_boolean INDEX] [--leader.follower_choice INDEX [{opt1,opt2}]] --leader.follower_mandatory INDEX FOLLOWER_MANDATORY
options:
-h, --help show this help message and exit
leader:
-l [LEADER ...], --leader.leader [LEADER ...]
Leader var
--leader.follower INDEX [FOLLOWER]
Follower
--leader.follower_submulti INDEX [FOLLOWER_SUBMULTI ...]
Follower submulti
-i INDEX [FOLLOWER_INTEGER], --leader.follower_integer INDEX [FOLLOWER_INTEGER]
Follower integer
--leader.follower_boolean INDEX
Follower boolean
--leader.follower_choice INDEX [{opt1,opt2}]
Follower choice
--leader.follower_mandatory INDEX FOLLOWER_MANDATORY
Follower mandatory
"""
parser = TiramisuCmdlineParser(get_config(json, with_mandatory=True, with_symlink=True), 'prog.py', add_extra_options=False, formatter_class=TestHelpFormatter)
f = StringIO()
with redirect_stdout(f):
parser.print_help()
assert f.getvalue() == output
def test_leadership_modif_leader(json): def test_leadership_modif_leader(json):
output = {'leader.leader': ['192.168.1.1'], output = {'leader.leader': ['192.168.1.1'],
'leader.follower': [None], 'leader.follower': [None],

View file

@ -84,7 +84,7 @@ od1.od0:
{str,list,int,none} choice the sub argument {str,list,int,none} choice the sub argument
-v, --od1.od0.verbosity -v, --od1.od0.verbosity
increase output verbosity increase output verbosity (default: False)
-nv, --od1.od0.no-verbosity -nv, --od1.od0.no-verbosity
od2: od2:
@ -115,7 +115,7 @@ od1.od0:
{str,list,int,none} choice the sub argument {str,list,int,none} choice the sub argument
-v, --od1.od0.verbosity -v, --od1.od0.verbosity
increase output verbosity increase output verbosity (default: False)
-nv, --od1.od0.no-verbosity -nv, --od1.od0.no-verbosity
od2: od2:
@ -146,7 +146,7 @@ od1.od0:
{str,list,int,none} choice the sub argument {str,list,int,none} choice the sub argument
-v, --od1.od0.verbosity -v, --od1.od0.verbosity
increase output verbosity increase output verbosity (default: False)
-nv, --od1.od0.no-verbosity -nv, --od1.od0.no-verbosity
od2: od2:

View file

@ -96,7 +96,7 @@ positional arguments:
options: options:
-h, --help show this help message and exit -h, --help show this help message and exit
-v, --verbosity increase output verbosity -v, --verbosity increase output verbosity (default: False)
-nv, --no-verbosity -nv, --no-verbosity
""" """
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', formatter_class=TestHelpFormatter) parser = TiramisuCmdlineParser(get_config(json), 'prog.py', formatter_class=TestHelpFormatter)
@ -114,7 +114,7 @@ options:
root: root:
{str,list,int,none} choice the sub argument {str,list,int,none} choice the sub argument
-v, --root.verbosity increase output verbosity -v, --root.verbosity increase output verbosity (default: False)
-nv, --root.no-verbosity -nv, --root.no-verbosity
""" """
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', formatter_class=TestHelpFormatter) parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', formatter_class=TestHelpFormatter)
@ -132,7 +132,7 @@ options:
root: root:
{str,list,int,none} choice the sub argument {str,list,int,none} choice the sub argument
-v, --verbosity increase output verbosity -v, --verbosity increase output verbosity (default: False)
-nv, --no-verbosity -nv, --no-verbosity
""" """
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', fullpath=False, formatter_class=TestHelpFormatter) parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', fullpath=False, formatter_class=TestHelpFormatter)
@ -150,7 +150,7 @@ positional arguments:
options: options:
-h, --help show this help message and exit -h, --help show this help message and exit
-v, --verbosity increase output verbosity -v, --verbosity increase output verbosity (default: False)
-nv, --no-verbosity -nv, --no-verbosity
--str STR string option --str STR string option
""" """
@ -171,7 +171,7 @@ def test_readme_help_modif_positional_remove(json):
options: options:
-h, --help show this help message and exit -h, --help show this help message and exit
-v, --verbosity increase output verbosity -v, --verbosity increase output verbosity (default: False)
-nv, --no-verbosity -nv, --no-verbosity
--str STR string option --str STR string option
""" """
@ -195,7 +195,7 @@ positional arguments:
options: options:
-h, --help show this help message and exit -h, --help show this help message and exit
-v, --verbosity increase output verbosity -v, --verbosity increase output verbosity (default: False)
-nv, --no-verbosity -nv, --no-verbosity
--str STR string option --str STR string option
""" """
@ -216,7 +216,7 @@ def test_readme_help_modif_remove(json):
options: options:
-h, --help show this help message and exit -h, --help show this help message and exit
-v, --verbosity increase output verbosity -v, --verbosity increase output verbosity (default: False)
-nv, --no-verbosity -nv, --no-verbosity
""" """
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', display_modified_value=False, formatter_class=TestHelpFormatter) parser = TiramisuCmdlineParser(get_config(json), 'prog.py', display_modified_value=False, formatter_class=TestHelpFormatter)
@ -239,7 +239,7 @@ positional arguments:
options: options:
-h, --help show this help message and exit -h, --help show this help message and exit
-v, --verbosity increase output verbosity -v, --verbosity increase output verbosity (default: False)
-nv, --no-verbosity -nv, --no-verbosity
--str STR string option --str STR string option
""" """
@ -261,7 +261,7 @@ def test_readme_help_modif_short_remove(json):
options: options:
-h, --help show this help message and exit -h, --help show this help message and exit
-nv, --no-verbosity increase output verbosity -nv, --no-verbosity increase output verbosity (default: False)
--str STR string option --str STR string option
""" """
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', display_modified_value=False, formatter_class=TestHelpFormatter) parser = TiramisuCmdlineParser(get_config(json), 'prog.py', display_modified_value=False, formatter_class=TestHelpFormatter)
@ -284,7 +284,7 @@ positional arguments:
options: options:
-h, --help show this help message and exit -h, --help show this help message and exit
-v, --verbosity increase output verbosity -v, --verbosity increase output verbosity (default: False)
-nv, --no-verbosity -nv, --no-verbosity
--str STR string option --str STR string option
""" """
@ -305,7 +305,7 @@ def test_readme_help_modif_short_no_remove(json):
options: options:
-h, --help show this help message and exit -h, --help show this help message and exit
-v, --verbosity increase output verbosity -v, --verbosity increase output verbosity (default: False)
--str STR string option --str STR string option
""" """
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', display_modified_value=False, formatter_class=TestHelpFormatter) parser = TiramisuCmdlineParser(get_config(json), 'prog.py', display_modified_value=False, formatter_class=TestHelpFormatter)

View file

@ -1,4 +1,4 @@
from argparse import HelpFormatter from argparse import ArgumentDefaultsHelpFormatter
from tiramisu_cmdline_parser.api import TiramisuHelpFormatter from tiramisu_cmdline_parser.api import TiramisuHelpFormatter
@ -27,7 +27,7 @@ def to_dict(dico):
return ret return ret
class TestHelpFormatter(TiramisuHelpFormatter, HelpFormatter): class TestHelpFormatter(TiramisuHelpFormatter, ArgumentDefaultsHelpFormatter):
def __init__(self, def __init__(self,
*args, *args,
**kwargs, **kwargs,

View file

@ -1,9 +1,26 @@
# Copyright (C) 2018-2019 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/>.
from typing import Union, List, Dict, Tuple, Optional, Any
try: try:
from .api import TiramisuCmdlineParser from .api import TiramisuCmdlineParser
except ImportError as err: except ImportError as err:
import warnings import warnings
warnings.warn("cannot not import TiramisuCmdlineParser {err}", ImportWarning) warnings.warn("cannot not import TiramisuCmdlineParser {err}", ImportWarning)
TiramisuCmdlineParser = None TiramisuCmdlineParser = None
__version__ = "0.5" __version__ = "0.5"
__all__ = ('TiramisuCmdlineParser',) __all__ = ("TiramisuCmdlineParser",)

View file

@ -13,19 +13,28 @@
# You should have received a copy of the GNU Lesser General Public License # 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/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from typing import Union, List, Dict, Tuple, Optional, Any from typing import Union, List, Dict, Tuple, Optional, Any
from argparse import ArgumentParser, Namespace, SUPPRESS, _HelpAction, HelpFormatter from argparse import (
ArgumentParser,
Namespace,
SUPPRESS,
_HelpAction,
HelpFormatter,
ArgumentDefaultsHelpFormatter,
)
from copy import copy from copy import copy
from gettext import gettext as _ from gettext import gettext as _
#try: # try:
from tiramisu import Config from tiramisu import Config
from tiramisu.error import PropertiesOptionError, LeadershipError from tiramisu.error import PropertiesOptionError, LeadershipError, ConfigError
#except ImportError:
# except ImportError:
# Config = None # Config = None
# from tiramisu_api.error import PropertiesOptionError # from tiramisu_api.error import PropertiesOptionError
# LeadershipError = ValueError # LeadershipError = ValueError
try: 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 ImportError: except ImportError:
@ -37,25 +46,26 @@ def get_choice_list(config, properties, display):
if isinstance(choice, int): if isinstance(choice, int):
return str(choice) return str(choice)
return choice return choice
choices = [convert(choice) for choice in config.value.list()]
if choices and choices[0] == '': choices = [
del choices[0] convert(choice)
for choice in config.value.list()
if choice != "" and choice is not None
]
if display: if display:
choices = '{{{}}}'.format(','.join(choices)) choices = "{{{}}}".format(",".join(choices))
if 'mandatory' not in properties: if "mandatory" not in properties:
choices = '[{}]'.format(choices) choices = "[{}]".format(choices)
return choices return choices
class TiramisuNamespace(Namespace): class TiramisuNamespace(Namespace):
def __init__(self, def __init__(self, config: Config, root: Optional[str]) -> None:
config: Config, super().__setattr__("_config", config)
root: Optional[str]) -> None: super().__setattr__("_root", root)
super().__setattr__('_config', config) super().__setattr__("list_force_no", {})
super().__setattr__('_root', root) super().__setattr__("list_force_del", {})
super().__setattr__('list_force_no', {}) super().__setattr__("arguments", {})
super().__setattr__('list_force_del', {})
super().__setattr__('arguments', {})
self._populate() self._populate()
super().__init__() super().__init__()
@ -75,10 +85,11 @@ class TiramisuNamespace(Namespace):
value = None value = None
super().__setattr__(option.path(), value) super().__setattr__(option.path(), value)
def __setattr__(self, def __setattr__(
key: str, self,
value: Any, key: str,
) -> None: value: Any,
) -> None:
if key in self.list_force_no: if key in self.list_force_no:
true_key = self.list_force_no[key] true_key = self.list_force_no[key]
elif key in self.list_force_del: elif key in self.list_force_del:
@ -89,14 +100,14 @@ class TiramisuNamespace(Namespace):
if option.isfollower(): if option.isfollower():
_setattr = self._setattr_follower _setattr = self._setattr_follower
if not value[0].isdecimal(): if not value[0].isdecimal():
raise ValueError('index must be a number, not {}'.format(value[0])) raise ValueError("index must be a number, not {}".format(value[0]))
index = int(value[0]) index = int(value[0])
option = self._config.option(true_key, index) option = self._config.option(true_key, index)
true_value = ','.join(value[1:]) true_value = ",".join(value[1:])
else: else:
_setattr = self._setattr _setattr = self._setattr
true_value = value true_value = value
if option.type() == 'choice': if option.type() == "choice":
# HACK if integer in choice # HACK if integer in choice
values = option.value.list() values = option.value.list()
if isinstance(value, list): if isinstance(value, list):
@ -118,9 +129,9 @@ class TiramisuNamespace(Namespace):
else: else:
_setattr(option, true_key, key, value) _setattr(option, true_key, key, value)
except ValueError as err: except ValueError as err:
if option.type() == 'choice': if option.type() == "choice":
values = option.value.list() values = option.value.list()
display_value = '' display_value = ""
if isinstance(true_value, list): if isinstance(true_value, list):
for val in value: for val in value:
if val not in values: if val not in values:
@ -129,31 +140,31 @@ class TiramisuNamespace(Namespace):
else: else:
display_value = true_value display_value = true_value
choices = get_choice_list(option, option.property.get(), False) 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]))) 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
def _setattr(self, def _setattr(self, option: "Option", true_key: str, key: str, value: Any) -> None:
option: 'Option', if option.ismulti() and value is not None and not isinstance(value, list):
true_key: str,
key: str,
value: Any) -> None:
if option.ismulti() and \
value is not None and \
not isinstance(value, list):
value = [value] value = [value]
try: try:
option.value.set(value) option.value.set(value)
except PropertiesOptionError: except PropertiesOptionError:
raise AttributeError('unrecognized arguments: {}'.format(self.arguments[key])) raise AttributeError(
"unrecognized arguments: {}".format(self.arguments[key])
)
def _setattr_follower(self, def _setattr_follower(
option: 'Option', self, option: "Option", true_key: str, key: str, value: Any
true_key: str, ) -> None:
key: str,
value: Any) -> None:
index = int(value[0]) index = int(value[0])
if option.type() == 'boolean': if option.type() == "boolean":
value = key not in self.list_force_no value = key not in self.list_force_no
elif option.issubmulti(): elif option.issubmulti():
value = value[1:] value = value[1:]
@ -163,25 +174,27 @@ class TiramisuNamespace(Namespace):
class TiramisuHelpFormatter: class TiramisuHelpFormatter:
def _get_default_metavar_for_optional(self, def _get_default_metavar_for_optional(self, action):
action):
ret = super()._get_default_metavar_for_optional(action) ret = super()._get_default_metavar_for_optional(action)
if '.' in ret: if "." in ret:
ret = ret.rsplit('.', 1)[1] ret = ret.rsplit(".", 1)[1]
return ret return ret
class _Section(HelpFormatter._Section): class _Section(HelpFormatter._Section):
def format_help(self): def format_help(self):
# Remove empty OD # Remove empty OD
if self.formatter.remove_empty_od and \ if (
len(self.items) == 1 and \ self.formatter.remove_empty_od
self.items[0][0].__name__ == '_format_text': and len(self.items) == 1
return '' and self.items[0][0].__name__ == "_format_text"
):
return ""
return super().format_help() return super().format_help()
class _TiramisuHelpAction(_HelpAction): class _TiramisuHelpAction(_HelpAction):
needs = False needs = False
def __call__(self, *args, **kwargs): def __call__(self, *args, **kwargs):
_TiramisuHelpAction.needs = True _TiramisuHelpAction.needs = True
@ -190,27 +203,38 @@ class _TiramisuHelpAction(_HelpAction):
class _BuildKwargs: class _BuildKwargs:
def __init__(self, def __init__(
name: str, self,
option: 'Option', name: str,
cmdlineparser: 'TiramisuCmdlineParser', option: "Option",
properties: List[str], cmdlineparser: "TiramisuCmdlineParser",
force_no: bool, properties: List[str],
force_del: bool, force_no: bool,
display_modified_value: bool, force_del: bool,
not_display: bool) -> None: add_extra_options: bool,
display_modified_value: bool,
not_display: bool,
) -> None:
self.kwargs = {} self.kwargs = {}
self.cmdlineparser = cmdlineparser self.cmdlineparser = cmdlineparser
self.properties = properties self.properties = properties
self.force_no = force_no self.force_no = force_no
self.force_del = force_del self.force_del = force_del
if (not self.force_no or (not_display and not display_modified_value)) and not self.force_del: if (
description = option.description() (not self.force_no or not add_extra_options)
if not description: or (not_display and not display_modified_value)
description = description.replace('%', '%%') ) and not self.force_del:
self.kwargs['help'] = description if self.force_no:
if 'positional' not in self.properties: description = option.information.get("negative_description", None)
is_short_name = self.cmdlineparser._is_short_name(name, 'longargument' in self.properties) else:
description = None
if description is None:
description = option.description()
self.kwargs["help"] = description
if "positional" not 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)
ga_path = self.gen_argument_name(option.path(), is_short_name) ga_path = self.gen_argument_name(option.path(), is_short_name)
@ -221,7 +245,7 @@ class _BuildKwargs:
self.cmdlineparser.namespace.list_force_del[ga_path] = option.path() 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)
argument = 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.cmdlineparser.namespace.arguments[option.path()] = argument
self.args = [argument] self.args = [argument]
@ -229,14 +253,13 @@ class _BuildKwargs:
self.cmdlineparser.namespace.arguments[option.path()] = option.path() self.cmdlineparser.namespace.arguments[option.path()] = option.path()
self.args = [option.path()] self.args = [option.path()]
def __setitem__(self, def __setitem__(self, key: str, value: Any) -> None:
key: str,
value: Any) -> None:
self.kwargs[key] = value self.kwargs[key] = value
def add_argument(self, def add_argument(self, option: "Option"):
option: 'Option'): is_short_name = self.cmdlineparser._is_short_name(
is_short_name = self.cmdlineparser._is_short_name(option.name(), 'longargument' in self.properties) option.name(), "longargument" in self.properties
)
if self.force_no: if self.force_no:
name = self.gen_argument_name(option.name(), is_short_name) name = self.gen_argument_name(option.name(), is_short_name)
elif self.force_del: elif self.force_del:
@ -250,22 +273,22 @@ class _BuildKwargs:
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:
if is_short_name: if is_short_name:
prefix = 'n' prefix = "n"
else: else:
prefix = 'no-' prefix = "no-"
if '.' in name: if "." in name:
sname = name.rsplit('.', 1) sname = name.rsplit(".", 1)
name = sname[0] + '.' + prefix + sname[1] name = sname[0] + "." + prefix + sname[1]
else: else:
name = prefix + name name = prefix + name
if self.force_del: if self.force_del:
if is_short_name: if is_short_name:
prefix = 'p' prefix = "p"
else: else:
prefix = 'pop-' prefix = "pop-"
if '.' in name: if "." in name:
sname = name.rsplit('.', 1) sname = name.rsplit(".", 1)
name = sname[0] + '.' + prefix + sname[1] name = sname[0] + "." + prefix + sname[1]
else: else:
name = prefix + name name = prefix + name
return name return name
@ -275,17 +298,21 @@ class _BuildKwargs:
class TiramisuCmdlineParser(ArgumentParser): class TiramisuCmdlineParser(ArgumentParser):
def __init__(self, def __init__(
config: Union[Config, ConfigJson], self,
*args, config: Union[Config, ConfigJson],
root: str=None, *args,
fullpath: bool=True, root: str = None,
remove_empty_od: bool=False, fullpath: bool = True,
display_modified_value: bool=True, remove_empty_od: bool = False,
formatter_class=HelpFormatter, display_modified_value: bool = True,
unrestraint: bool=False, formatter_class=ArgumentDefaultsHelpFormatter,
_forhelp: bool=False, unrestraint: bool = False,
**kwargs): add_extra_options: bool = True,
short_name_max_len: int = 1,
_forhelp: bool = False,
**kwargs,
):
if not _forhelp: if not _forhelp:
unrestraint = True unrestraint = True
self.fullpath = fullpath self.fullpath = fullpath
@ -293,11 +320,15 @@ class TiramisuCmdlineParser(ArgumentParser):
self.root = root self.root = root
self.remove_empty_od = remove_empty_od self.remove_empty_od = remove_empty_od
self.unrestraint = unrestraint self.unrestraint = unrestraint
self.add_extra_options = add_extra_options
self.display_modified_value = display_modified_value self.display_modified_value = display_modified_value
self.short_name_max_len = short_name_max_len
if TiramisuHelpFormatter not in formatter_class.__mro__: if TiramisuHelpFormatter not in formatter_class.__mro__:
formatter_class = type('TiramisuHelpFormatter', (TiramisuHelpFormatter, formatter_class), {}) formatter_class = type(
"TiramisuHelpFormatter", (TiramisuHelpFormatter, formatter_class), {}
)
formatter_class.remove_empty_od = self.remove_empty_od formatter_class.remove_empty_od = self.remove_empty_od
kwargs['formatter_class'] = formatter_class kwargs["formatter_class"] = formatter_class
if not _forhelp and self.unrestraint: if not _forhelp and self.unrestraint:
subconfig = self.config.unrestraint subconfig = self.config.unrestraint
else: else:
@ -308,20 +339,20 @@ class TiramisuCmdlineParser(ArgumentParser):
subconfig = subconfig.option(self.root) subconfig = subconfig.option(self.root)
self.namespace = TiramisuNamespace(self.config, self.root) self.namespace = TiramisuNamespace(self.config, self.root)
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.register('action', 'help', _TiramisuHelpAction) self.register("action", "help", _TiramisuHelpAction)
self._config_to_argparser(_forhelp, self._config_to_argparser(
subconfig, _forhelp,
self.root) subconfig,
self.root,
)
def _pop_action_class(self, kwargs, default=None): def _pop_action_class(self, kwargs, default=None):
ret = super()._pop_action_class(kwargs, default) ret = super()._pop_action_class(kwargs, default)
if kwargs.get('action') != 'help' and kwargs.get('dest') != 'help': if kwargs.get("action") != "help" and kwargs.get("dest") != "help":
return ret return ret
return _TiramisuHelpAction return _TiramisuHelpAction
def _match_arguments_partial(self, def _match_arguments_partial(self, actions, arg_string_pattern):
actions,
arg_string_pattern):
# used only when check first proposal for first value # used only when check first proposal for first value
# we have to remove all actions with propertieserror # we have to remove all actions with propertieserror
# so only first settable option will be returned # so only first settable option will be returned
@ -336,7 +367,7 @@ class TiramisuCmdlineParser(ArgumentParser):
return super()._match_arguments_partial(actions, arg_string_pattern) return super()._match_arguments_partial(actions, arg_string_pattern)
def _is_short_name(self, name, longargument): def _is_short_name(self, name, longargument):
return len(name) == 1 and not longargument return len(name) <= self.short_name_max_len and not longargument
def _gen_argument(self, name, is_short_name): def _gen_argument(self, name, is_short_name):
if is_short_name: if is_short_name:
@ -351,60 +382,61 @@ class TiramisuCmdlineParser(ArgumentParser):
if args != args_ and args_ and args_[0].startswith(self.prefix_chars): if args != args_ and args_ and args_[0].startswith(self.prefix_chars):
# option that was disabled are no more disable # option that was disabled are no more disable
# so create a new parser # so create a new parser
new_parser = TiramisuCmdlineParser(self.config, new_parser = TiramisuCmdlineParser(
self.prog, self.config,
root=self.root, self.prog,
remove_empty_od=self.remove_empty_od, root=self.root,
display_modified_value=self.display_modified_value, remove_empty_od=self.remove_empty_od,
formatter_class=self.formatter_class, display_modified_value=self.display_modified_value,
epilog=self.epilog, formatter_class=self.formatter_class,
description=self.description, epilog=self.epilog,
unrestraint=self.unrestraint, description=self.description,
fullpath=self.fullpath) unrestraint=self.unrestraint,
namespace_, args_ = new_parser._parse_known_args(args_, new_parser.namespace) add_extra_options=self.add_extra_options,
short_name_max_len=self.short_name_max_len,
fullpath=self.fullpath,
)
namespace_, args_ = new_parser._parse_known_args(
args_, new_parser.namespace
)
else: else:
if self._registries['action']['help'].needs: if self._registries["action"]["help"].needs:
# display help only when all variables assignemnt are done # display help only when all variables assignemnt are done
self._registries['action']['help'].needs = False self._registries["action"]["help"].needs = False
helper = self._registries['action']['help'](None) helper = self._registries["action"]["help"](None)
helper.display(self) helper.display(self)
return namespace_, args_ return namespace_, args_
def add_argument(self, *args, **kwargs): def add_argument(self, *args, **kwargs):
if args == ('-h', '--help'): if args == ("-h", "--help"):
super().add_argument(*args, **kwargs) super().add_argument(*args, **kwargs)
else: else:
raise NotImplementedError(_('do not use add_argument')) raise NotImplementedError(_("do not use add_argument"))
def add_arguments(self, *args, **kwargs): def add_arguments(self, *args, **kwargs):
raise NotImplementedError(_('do not use add_argument')) raise NotImplementedError(_("do not use add_argument"))
def add_subparsers(self, *args, **kwargs): def add_subparsers(self, *args, **kwargs):
raise NotImplementedError(_('do not use add_subparsers')) raise NotImplementedError(_("do not use add_subparsers"))
def _option_is_not_default(self, def _option_is_not_default(self, properties, type, name, value):
properties, if "positional" not in properties:
type, is_short_name = self._is_short_name(name, "longargument" in properties)
name, self.prog += " {}".format(self._gen_argument(name, is_short_name))
value): if type != "boolean":
if 'positional' not in properties:
is_short_name = self._is_short_name(name, 'longargument' in properties)
self.prog += ' {}'.format(self._gen_argument(name, is_short_name))
if type != 'boolean':
if isinstance(value, list): if isinstance(value, list):
for val in value: for val in value:
self.prog += ' "{}"'.format(val) self.prog += ' "{}"'.format(val)
else: else:
self.prog += ' "{}"'.format(value) self.prog += ' "{}"'.format(value)
def _config_list(self, def _config_list(
config: Config, self, config: Config, prefix: Optional[str], _forhelp: bool, group, level
prefix: Optional[str], ):
_forhelp: bool, obj = None
group, level):
for obj in config: for obj in config:
# do not display frozen option # do not display frozen option
if 'frozen' in obj.property.get(): if "frozen" in obj.property.get():
continue continue
if obj.isoptiondescription(): if obj.isoptiondescription():
if _forhelp: if _forhelp:
@ -415,11 +447,15 @@ class TiramisuCmdlineParser(ArgumentParser):
else: else:
newgroup = group newgroup = group
if prefix: if prefix:
prefix_ = prefix + '.' + obj.name() prefix_ = prefix + "." + obj.name()
else: else:
prefix_ = obj.path() prefix_ = obj.path()
self._config_to_argparser(_forhelp, obj, prefix_, newgroup, level + 1) self._config_to_argparser(_forhelp, obj, prefix_, newgroup, level + 1)
elif obj.type() == 'boolean' and not obj.issymlinkoption(): elif (
self.add_extra_options
and obj.type() == "boolean"
and not obj.issymlinkoption()
):
if not obj.isleader(): if not obj.isleader():
yield obj, False, None yield obj, False, None
yield obj, True, None yield obj, True, None
@ -427,217 +463,301 @@ class TiramisuCmdlineParser(ArgumentParser):
yield obj, False, False yield obj, False, False
yield obj, False, True yield obj, False, True
yield obj, True, None yield obj, True, None
elif obj.isleader(): elif self.add_extra_options and obj.isleader():
yield obj, None, False yield obj, None, False
yield obj, None, True yield obj, None, True
else: else:
yield obj, None, None if (
not obj.issymlinkoption()
and obj.type() == "boolean"
and obj.value.get() is True
):
negative_description = obj.information.get(
"negative_description", None
)
if _forhelp and not negative_description:
raise ValueError(
_(
f'the boolean "{obj.path()}" cannot have a default value to "True" with option add_extra_options if there is no negative_description'
)
)
yield obj, True, None
else:
yield obj, None, None
if obj is not None and not obj.isoptiondescription() and obj.isleader():
# no follower found, search if there is a symlink
for sobj in config.list(uncalculated=True):
try:
if sobj.issymlinkoption() and sobj.option().isleader():
yield sobj, None, None
except ConfigError:
pass
def _config_to_argparser(self, def _config_to_argparser(
_forhelp: bool, self, _forhelp: bool, config, prefix: Optional[str], group=None, level=0
config, ) -> None:
prefix: Optional[str],
group=None,
level=0) -> None:
if group is None: if group is None:
group = super() group = super()
actions = {} actions = {}
leadership_len = None leadership_len = None
options_is_not_default = {} options_is_not_default = {}
for option, force_no, force_del in self._config_list(config, prefix, _forhelp, group, level): for option, force_no, force_del in self._config_list(
config, prefix, _forhelp, group, level
):
name = option.name() name = option.name()
if name.startswith(self.prefix_chars): if name.startswith(self.prefix_chars):
raise ValueError(_('name cannot startswith "{}"').format(self.prefix_chars)) raise ValueError(
_('name cannot startswith "{}"').format(self.prefix_chars)
)
if option.issymlinkoption(): if option.issymlinkoption():
symlink_name = option.option().name() symlink_name = option.option().name()
if symlink_name in options_is_not_default: if symlink_name in options_is_not_default:
options_is_not_default[symlink_name]['name'] = name options_is_not_default[symlink_name]["name"] = name
if symlink_name in actions: if symlink_name in actions:
for action in actions[symlink_name]: for action in actions[symlink_name]:
action.add_argument(option) action.add_argument(option)
continue continue
if force_del: if force_del:
value = None value = None
# elif force_no:
# value = not option.value.get()
elif option.isleader(): elif option.isleader():
value = option.value.get() value = option.value.get()
leadership_len = len(value) leadership_len = len(value)
elif option.isfollower(): elif option.isfollower():
value = [] if _forhelp:
try: value = option.value.defaultmulti()
for index in range(leadership_len): else:
value.append(self.config.option(option.path(), index).value.get()) value = []
except: try:
value = None for index in range(leadership_len):
value.append(
self.config.option(option.path(), index).value.get()
)
except:
value = None
else: else:
value = option.value.get() value = option.value.get()
if self.fullpath and prefix: if self.fullpath and prefix:
name = prefix + '.' + name name = prefix + "." + name
properties = option.property.get() properties = option.property.get()
not_display = not option.isfollower() and not option.owner.isdefault() and value is not None not_display = (
kwargs = _BuildKwargs(name, option, self, properties, force_no, force_del, self.display_modified_value, not_display) not option.isfollower()
if _forhelp and not_display and ((value is not False and not force_no) or (value is False and force_no)): and not option.owner.isdefault()
options_is_not_default[option.name()] = {'properties': properties, and value is not None
'type': option.type(), )
'name': name, kwargs = _BuildKwargs(
'value': value} name,
option,
self,
properties,
force_no,
force_del,
self.add_extra_options,
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: if not self.display_modified_value:
continue continue
if 'positional' in properties: if force_no:
if option.type() == 'boolean': default = False
raise ValueError(_('boolean option must not be positional')) else:
if not 'mandatory' in properties: default = option.value.default()
if isinstance(default, list):
str_default_value = ",".join([str(v) for v in default])
else:
str_default_value = default
if "positional" in properties:
if option.type() == "boolean":
raise ValueError(_("boolean option must not be positional"))
if not "mandatory" in properties:
raise ValueError('"positional" argument must be "mandatory" too') raise ValueError('"positional" argument must be "mandatory" too')
if _forhelp: if _forhelp:
kwargs['default'] = option.value.default() kwargs["default"] = str_default_value
else: else:
kwargs['default'] = value kwargs["default"] = value
kwargs['nargs'] = '?' kwargs["nargs"] = "?"
else: else:
kwargs['default'] = SUPPRESS if _forhelp and not option.isleader():
if _forhelp and 'mandatory' in properties: if default not in [None, []]:
kwargs['required'] = True kwargs["default"] = str_default_value
if not force_del and option.type() == 'boolean':
if not option.isfollower():
if 'storefalse' in properties:
if force_no:
action = 'store_true'
else:
action = 'store_false'
elif force_no:
action = 'store_false'
else:
action = 'store_true'
kwargs['action'] = action
else: else:
kwargs['metavar'] = 'INDEX' kwargs["default"] = SUPPRESS
if option.type() != 'boolean' or force_del: else:
kwargs["default"] = SUPPRESS
if _forhelp and "mandatory" in properties:
kwargs["required"] = True
if not force_del and option.type() == "boolean":
if not option.isfollower():
if "storefalse" in properties:
if force_no:
action = "store_true"
else:
action = "store_false"
elif force_no:
action = "store_false"
else:
action = "store_true"
kwargs["action"] = action
else:
kwargs["metavar"] = "INDEX"
if option.type() != "boolean" or force_del:
if not force_del: if not force_del:
if _forhelp: if _forhelp:
value = option.value.default() value = option.value.default()
if value not in [None, []]: if value not in [None, []]:
#kwargs['default'] = kwargs['const'] = option.default() # kwargs['default'] = kwargs['const'] = option.default()
#kwargs['action'] = 'store_const' # kwargs['action'] = 'store_const'
kwargs['nargs'] = '?' kwargs["nargs"] = "?"
if not option.isfollower() and option.ismulti(): if not option.isfollower() and option.ismulti():
if _forhelp and 'mandatory' in properties: if _forhelp and "mandatory" in properties:
kwargs['nargs'] = '+' kwargs["nargs"] = "+"
else: else:
kwargs['nargs'] = '*' kwargs["nargs"] = "*"
if option.isfollower() and not option.type() == 'boolean': if option.isfollower() and not option.type() == "boolean":
metavar = option.name().upper() metavar = option.name().upper()
if option.issubmulti(): if option.issubmulti():
kwargs['nargs'] = '+' kwargs["nargs"] = "+"
else: else:
kwargs['nargs'] = 2 kwargs["nargs"] = 2
if _forhelp and 'mandatory' not in properties: if _forhelp and "mandatory" not in properties:
metavar = '[{}]'.format(metavar) metavar = "[{}]".format(metavar)
if option.type() == 'choice': if option.type() == "choice":
# do not manage choice with argparse there is problem with integer problem # do not manage choice with argparse there is problem with integer problem
kwargs['metavar'] = ('INDEX', get_choice_list(option, properties, True)) kwargs["metavar"] = (
"INDEX",
get_choice_list(option, properties, True),
)
else: else:
kwargs['metavar'] = ('INDEX', metavar) kwargs["metavar"] = ("INDEX", metavar)
if force_del: if force_del:
kwargs['metavar'] = 'INDEX' kwargs["metavar"] = "INDEX"
kwargs['type'] = int kwargs["type"] = int
elif option.type() == 'string': elif option.type() == "string":
pass pass
elif option.type() == 'integer' or option.type() == 'boolean': elif option.type() == "integer" or option.type() == "boolean":
# when boolean we are here only if follower # when boolean we are here only if follower
kwargs['type'] = int kwargs["type"] = int
if _forhelp and option.type() == 'boolean': if _forhelp and option.type() == "boolean":
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():
# do not manage choice with argparse there is problem with integer problem # do not manage choice with argparse there is problem with integer problem
kwargs['choices'] = get_choice_list(option, properties, False) kwargs["choices"] = get_choice_list(option, properties, False)
elif option.type() == 'float': elif option.type() == "float":
kwargs['type'] = float kwargs["type"] = float
else: else:
pass pass
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)
for values in actions.values(): for values in actions.values():
for value in values: # for value in values:
args, kwargs = value.get() value = values[0]
group.add_argument(*args, **kwargs) args, kwargs = value.get()
def _valid_mandatory(self): group.add_argument(*args, **kwargs)
pass
def parse_args(self, # def _valid_mandatory(self):
*args, # pass
valid_mandatory=True, #
**kwargs): def parse_args(self, *args, valid_mandatory=True, **kwargs):
kwargs['namespace'] = self.namespace kwargs["namespace"] = self.namespace
try: try:
namespaces = super().parse_args(*args, **kwargs) namespaces = super().parse_args(*args, **kwargs)
except PropertiesOptionError as err: except PropertiesOptionError as err:
name = err._option_bag.option.impl_getname() name = err._subconfig.path
properties = self.config.option(name).property.get() properties = self.config.option(name).property.get()
if self.fullpath and 'positional' not in properties: if self.fullpath and "positional" not in properties:
if len(name) == 1 and 'longargument' not in properties: if len(name) == 1 and "longargument" not in properties:
name = self.prefix_chars + name name = self.prefix_chars + name
else: else:
name = self.prefix_chars * 2 + name name = self.prefix_chars * 2 + name
if err.proptype == ['mandatory']: if err.proptype == ["mandatory"]:
self.error('the following arguments are required: {}'.format(name)) self.error("the following arguments are required: {}".format(name))
else: else:
self.error('unrecognized arguments: {}'.format(name)) self.error("unrecognized arguments: {}".format(name))
if valid_mandatory: if valid_mandatory:
errors = [] errors = []
for option in self.config.value.mandatory(): for option in self.config.value.mandatory():
properties = option.property.get() properties = option.property.get()
if not option.isfollower(): if not option.isfollower():
if 'positional' not in properties: if "positional" not in properties:
if self.fullpath: if self.fullpath:
name = option.path() name = option.path()
else: else:
name = option.name() name = option.name()
is_short_name = self._is_short_name(name, 'longargument' in option.property.get()) is_short_name = self._is_short_name(
name, "longargument" in option.property.get()
)
args = self._gen_argument(name, is_short_name) args = self._gen_argument(name, is_short_name)
else: else:
args = option.path() args = option.path()
else: else:
if 'positional' not in properties: if "positional" not in properties:
args = self._gen_argument(option.path(), False) args = self._gen_argument(option.path(), False)
else: else:
args = option.path() args = option.path()
if not self.fullpath and '.' in args: if not self.fullpath and "." in args:
args = args.rsplit('.', 1)[1] args = args.rsplit(".", 1)[1]
if 'positional' not in properties: if "positional" not in properties:
args = self._gen_argument(args, False) args = self._gen_argument(args, False)
errors.append(args) errors.append(args)
if errors: if errors:
self.error('the following arguments are required: {}'.format(', '.join(errors))) self.error(
"the following arguments are required: {}".format(", ".join(errors))
)
return namespaces return namespaces
def format_usage(self, def format_usage(self, *args, **kwargs):
*args, help_formatter = TiramisuCmdlineParser(
**kwargs): self.config,
help_formatter = TiramisuCmdlineParser(self.config, self.prog,
self.prog, root=self.root,
root=self.root, fullpath=self.fullpath,
fullpath=self.fullpath, remove_empty_od=self.remove_empty_od,
remove_empty_od=self.remove_empty_od, display_modified_value=self.display_modified_value,
display_modified_value=self.display_modified_value, formatter_class=self.formatter_class,
formatter_class=self.formatter_class, add_extra_options=self.add_extra_options,
epilog=self.epilog, short_name_max_len=self.short_name_max_len,
description=self.description, epilog=self.epilog,
_forhelp=True) description=self.description,
return super(TiramisuCmdlineParser, help_formatter).format_usage(*args, **kwargs) _forhelp=True,
)
return super(TiramisuCmdlineParser, help_formatter).format_usage(
*args, **kwargs
)
def format_help(self): def format_help(self):
help_formatter = TiramisuCmdlineParser(self.config, help_formatter = TiramisuCmdlineParser(
self.prog, self.config,
root=self.root, self.prog,
fullpath=self.fullpath, root=self.root,
remove_empty_od=self.remove_empty_od, fullpath=self.fullpath,
display_modified_value=self.display_modified_value, remove_empty_od=self.remove_empty_od,
formatter_class=self.formatter_class, display_modified_value=self.display_modified_value,
epilog=self.epilog, formatter_class=self.formatter_class,
description=self.description, add_extra_options=self.add_extra_options,
_forhelp=True) short_name_max_len=self.short_name_max_len,
epilog=self.epilog,
description=self.description,
_forhelp=True,
)
return super(TiramisuCmdlineParser, help_formatter).format_help() return super(TiramisuCmdlineParser, help_formatter).format_help()
def get_config(self): def get_config(self):