Compare commits

...

18 commits

Author SHA1 Message Date
fc5c3f3691 bump: version 0.7.0a3 → 0.7.0a4 2025-11-21 07:57:44 +01:00
f458c9eefc feat: add 'add_help' option un TiramisuCmdLineParser 2025-11-21 07:57:28 +01:00
9befbf0ade bump: version 0.7.0a2 → 0.7.0a3 2025-10-10 08:10:15 +02:00
c4ce6dfb3f fix: update test 2025-10-10 08:00:30 +02:00
44378162b2 feat: do not exit() with exit_on_error to False 2025-10-07 20:58:45 +02:00
1ca99df30e bump: version 0.7.0a1 → 0.7.0a2 2025-09-29 11:02:41 +02:00
9da6c6f421 fix: better support for boolean help 2025-09-29 09:17:37 +02:00
db2402b04a bump: version 0.7.0a0 → 0.7.0a1 2025-05-12 09:12:39 +02:00
bf40fe1a70 fix: black 2025-05-12 09:05:26 +02:00
03f84ef27e bump: version 0.6.2rc2 → 0.7.0a0 2025-04-30 09:12:36 +02:00
ce59a2544b fix: formatter.short_name_max_len for symlink 2025-04-29 22:55:43 +02:00
0e86a7ef43 feat: for boolean always add --xxx and --no-xxx 2025-04-29 08:49:20 +02:00
17ce3b77d5 bump: version 0.6.2rc1 → 0.6.2rc2 2025-04-09 21:18:06 +02:00
8d2536543b fix: version 2025-04-09 21:18:01 +02:00
d480d5bf5c bump: version 0.6.2rc0 → 0.6.2rc1 2025-03-19 10:02:50 +01:00
fb0d9c9d22 fix: better leader support 2025-03-19 10:02:29 +01:00
093819f051 bump: version 0.6.1 → 0.6.2rc0 2025-01-03 08:01:29 +01:00
b5347fb6cc fix: python 2.12 support 2025-01-03 08:01:14 +01:00
9 changed files with 353 additions and 95 deletions

View file

@ -1,3 +1,61 @@
## 0.7.0a4 (2025-11-21)
### Feat
- add 'add_help' option un TiramisuCmdLineParser
## 0.7.0a3 (2025-10-10)
### Feat
- do not exit() with exit_on_error to False
### Fix
- update test
## 0.7.0a2 (2025-09-29)
### Fix
- better support for boolean help
## 0.7.0a1 (2025-05-12)
### Fix
- black
## 0.7.0a0 (2025-04-30)
### Feat
- for boolean always add --xxx and --no-xxx
### Fix
- formatter.short_name_max_len for symlink
## 0.6.2rc2 (2025-04-09)
### Fix
- version
## 0.6.2rc1 (2025-03-19)
### Fix
- better leader support
## 0.6.2rc0 (2025-01-03)
### Fix
- python 2.12 support
## 0.6.1 (2024-11-06)
## 0.6.1rc0 (2024-11-06)
### Fix

View file

@ -4,7 +4,7 @@ requires = ["flit_core >=3.8.0,<4"]
[project]
name = "tiramisu_cmdline_parser"
version = "0.6.1"
version = "0.7.0a4"
authors = [{name = "Emmanuel Garette", email = "gnunux@gnunux.info"}]
readme = "README.md"
description = "command-line parser using Tiramisu"
@ -18,6 +18,8 @@ classifiers = [
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3.14",
"Programming Language :: Python :: 3",
"Operating System :: OS Independent",
"Natural Language :: English",
@ -37,5 +39,9 @@ name = "cz_conventional_commits"
tag_format = "$version"
version_scheme = "pep440"
version_provider = "pep621"
#update_changelog_on_bump = true
version_files = [
"tiramisu_cmdline_parser/__version__.py",
"pyproject.toml:version"
]
update_changelog_on_bump = true
changelog_merge_prerelease = true

146
tests/test_boolean.py Normal file
View file

@ -0,0 +1,146 @@
from io import StringIO
from contextlib import redirect_stdout, redirect_stderr
import pytest
from tiramisu_cmdline_parser import TiramisuCmdlineParser
from tiramisu import BoolOption, OptionDescription, Config
from .utils import TestHelpFormatter, to_dict
def get_config(has_tree=False, default_verbosity=False):
booloption = BoolOption('disabled',
'disabled',
properties=('disabled',),
)
booloption2 = BoolOption('verbosity',
'increase output verbosity',
default=default_verbosity,
)
root = OptionDescription('root',
'root',
[booloption, booloption2],
)
if has_tree:
root = OptionDescription('root',
'root',
[root],
)
config = Config(root)
config.property.read_write()
return config
def test_boolean_help_tree():
output = """usage: prog.py [-h] [--root.verbosity] [--root.no-verbosity]
options:
-h, --help show this help message and exit
root:
--root.verbosity increase output verbosity (default: False)
--root.no-verbosity
"""
parser = TiramisuCmdlineParser(get_config(has_tree=True), 'prog.py', formatter_class=TestHelpFormatter)
f = StringIO()
with redirect_stdout(f):
parser.print_help()
assert f.getvalue() == output
def test_boolean_help():
output = """usage: prog.py [-h] [--verbosity] [--no-verbosity]
options:
-h, --help show this help message and exit
--verbosity increase output verbosity (default: False)
--no-verbosity
"""
parser = TiramisuCmdlineParser(get_config(), 'prog.py', formatter_class=TestHelpFormatter)
f = StringIO()
with redirect_stdout(f):
parser.print_help()
assert f.getvalue() == output
def test_boolean_help2():
output = """usage: prog.py [-h] [--verbosity] [--no-verbosity]
options:
-h, --help show this help message and exit
--verbosity increase output verbosity (default: True)
--no-verbosity
"""
parser = TiramisuCmdlineParser(get_config(default_verbosity=True), 'prog.py', formatter_class=TestHelpFormatter)
f = StringIO()
with redirect_stdout(f):
parser.print_help()
assert f.getvalue() == output
def test_boolean_true():
config = get_config(default_verbosity=True)
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter)
assert to_dict(config.value.get()) == {'verbosity': True}
def test_boolean_false():
config = get_config()
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter)
assert to_dict(config.value.get()) == {'verbosity': False}
def test_boolean_true_to_false():
config = get_config(default_verbosity=True)
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter)
parser.parse_args(['--no-verbosity'])
assert to_dict(config.value.get()) == {'verbosity': False}
def test_boolean_true_to_true():
config = get_config(default_verbosity=True)
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter)
parser.parse_args(['--verbosity'])
assert to_dict(config.value.get()) == {'verbosity': True}
def test_boolean_false_to_true():
config = get_config()
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter)
parser.parse_args(['--verbosity'])
assert to_dict(config.value.get()) == {'verbosity': True}
def test_boolean_false_to_false():
config = get_config()
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter)
parser.parse_args(['--verbosity'])
assert to_dict(config.value.get()) == {'verbosity': True}
def test_boolean_disabled():
config = get_config(default_verbosity=True)
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter)
f = StringIO()
with redirect_stderr(f):
try:
parser.parse_args(['--disabled'])
except SystemExit as err:
assert str(err) == "2"
assert f.getvalue() == """usage: prog.py [-h] [--verbosity] [--no-verbosity]
prog.py: error: unrecognized arguments: --disabled (cannot access to option "disabled" because has property "disabled")
"""
def test_boolean_no_disabled():
config = get_config(default_verbosity=True)
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter)
f = StringIO()
with redirect_stderr(f):
try:
parser.parse_args(['--no-disabled'])
except SystemExit as err:
assert str(err) == "2"
assert f.getvalue() == """usage: prog.py [-h] [--verbosity] [--no-verbosity]
prog.py: error: unrecognized arguments: --no-disabled (cannot access to option "disabled" because has property "disabled")
"""

View file

@ -52,10 +52,10 @@ def json(request):
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} ...]] {str,list,int,none} {1,2,3}
prog.py: error: argument positional: invalid choice: 'error' (choose from 'str', 'list', 'int', 'none')
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} ...]] {str,list,int,none} {1,2,3}
prog.py: error: argument positional_int: invalid choice: '4' (choose from '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', formatter_class=TestHelpFormatter)
@ -88,7 +88,7 @@ prog.py: error: argument positional_int: invalid choice: '4' (choose from '1', '
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} ...]] {str,list,int,none} {1,2,3}
prog.py: error: argument --str: invalid choice: 'error' (choose from 'str1', 'str2', 'str3')
prog.py: error: argument --str: invalid choice: 'error' (choose from str1, str2, str3)
"""
config = get_config(json)
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter)
@ -128,7 +128,7 @@ prog.py: error: argument --str: invalid choice: 'error' (choose from 'str1', 'st
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} ...]] {str,list,int,none} {1,2,3}
prog.py: error: argument --int: invalid choice: '4' (choose from '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', formatter_class=TestHelpFormatter)
@ -156,7 +156,7 @@ prog.py: error: argument --int: invalid choice: '4' (choose from '1', '2', '3')
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} ...]] {str,list,int,none} {1,2,3}
prog.py: error: argument --int_multi: invalid choice: '4' (choose from '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', formatter_class=TestHelpFormatter)

View file

@ -121,7 +121,7 @@ options:
-h, --help show this help message and exit
leader:
-l [LEADER ...], --leader.leader [LEADER ...]
-l, --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)
@ -138,13 +138,13 @@ options:
-h, --help show this help message and exit
leader:
-l [LEADER ...], --leader.leader [LEADER ...]
-l, --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]
-i, --leader.follower_integer INDEX [FOLLOWER_INTEGER]
Follower integer
--leader.follower_boolean INDEX
Follower boolean
@ -306,7 +306,7 @@ def test_leadership_modif_follower_choice(json):
def test_leadership_modif_follower_choice_unknown(json):
output = """usage: prog.py [-h] [--leader.leader [LEADER ...]] [--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}]]
prog.py: error: argument --leader.follower_choice: 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', formatter_class=TestHelpFormatter)

View file

@ -466,7 +466,7 @@ prog.py: error: the following arguments are required: --str
def test_readme_cross(json):
output = """usage: prog.py "none" [-h] [-v] [-nv] {str,list,int,none}
prog.py: error: unrecognized arguments: --int
prog.py: error: unrecognized arguments: --int (cannot access to option "int option" because has property "disabled")
"""
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', formatter_class=TestHelpFormatter)
f = StringIO()
@ -482,7 +482,7 @@ prog.py: error: unrecognized arguments: --int
def test_readme_cross_remove(json):
output = """usage: prog.py "none" [-h] [-v] [-nv]
prog.py: error: unrecognized arguments: --int
prog.py: error: unrecognized arguments: --int (cannot access to option "int option" because has property "disabled")
"""
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', display_modified_value=False, formatter_class=TestHelpFormatter)
f = StringIO()
@ -498,7 +498,7 @@ 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: --root.int
prog.py: error: unrecognized arguments: --root.int (cannot access to option "int option" because has property "disabled")
"""
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', formatter_class=TestHelpFormatter)
f = StringIO()
@ -514,7 +514,7 @@ prog.py: error: unrecognized arguments: --root.int
def test_readme_cross_tree_remove(json):
output = """usage: prog.py "none" [-h] [-v] [-nv]
prog.py: error: unrecognized arguments: --root.int
prog.py: error: unrecognized arguments: --root.int (cannot access to option "int option" because has property "disabled")
"""
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', display_modified_value=False, formatter_class=TestHelpFormatter)
f = StringIO()
@ -530,7 +530,7 @@ prog.py: error: unrecognized arguments: --root.int
def test_readme_cross_tree_flatten(json):
output = """usage: prog.py "none" [-h] [-v] [-nv] {str,list,int,none}
prog.py: error: unrecognized arguments: --int
prog.py: error: unrecognized arguments: --int (cannot access to option "int option" because has property "disabled")
"""
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', fullpath=False, formatter_class=TestHelpFormatter)
f = StringIO()
@ -546,7 +546,7 @@ prog.py: error: unrecognized arguments: --int
def test_readme_cross_tree_flatten_remove(json):
output = """usage: prog.py "none" [-h] [-v] [-nv]
prog.py: error: unrecognized arguments: --int
prog.py: error: unrecognized arguments: --int (cannot access to option "int option" because has property "disabled")
"""
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', fullpath=False, display_modified_value=False, formatter_class=TestHelpFormatter)
f = StringIO()
@ -562,7 +562,7 @@ prog.py: error: unrecognized arguments: --int
def test_readme_unknown(json):
output = """usage: prog.py [-h] [-v] [-nv] {str,list,int,none}
prog.py: error: argument root.cmd: invalid choice: 'unknown' (choose from 'str', 'list', 'int', 'none')
prog.py: error: argument root.cmd: invalid choice: 'unknown' (choose from str, list, int, none)
"""
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', fullpath=False, formatter_class=TestHelpFormatter)
f = StringIO()
@ -873,17 +873,17 @@ def test_readme_longargument(json):
def test_readme_unknown_key(json):
output1 = """usage: prog.py [-h] [-v] [-nv] {str,list,int,none}
output1 = """usage: prog.py "list" -v --list "a" [-h] [-v] [-nv] --list LIST [LIST ...] {str,list,int,none}
prog.py: error: unrecognized arguments: --unknown
"""
output2 = """usage: prog.py [-h] [-v] [-nv] {str,list,int,none}
output2 = """usage: prog.py "list" -v --list "a" [-h] [-v] [-nv] --list LIST [LIST ...] {str,list,int,none}
prog.py: error: unrecognized arguments: --root.unknown
"""
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', fullpath=False, formatter_class=TestHelpFormatter)
f = StringIO()
with redirect_stderr(f):
try:
parser.parse_args(['--unknown'])
parser.parse_args(['list', '--list', 'a', '--v', '--unknown'])
except SystemExit as err:
assert str(err) == "2"
else:
@ -893,7 +893,7 @@ prog.py: error: unrecognized arguments: --root.unknown
f = StringIO()
with redirect_stderr(f):
try:
parser.parse_args(['--root.unknown'])
parser.parse_args(['list', '--list', 'a', '--v', '--root.unknown'])
except SystemExit as err:
assert str(err) == "2"
else:

View file

@ -22,5 +22,6 @@ except ImportError as err:
warnings.warn("cannot not import TiramisuCmdlineParser {err}", ImportWarning)
TiramisuCmdlineParser = None
__version__ = "0.5"
from .__version__ import __version__
__all__ = ("TiramisuCmdlineParser",)

View file

@ -0,0 +1 @@
__version__ = "0.7.0a4"

View file

@ -15,6 +15,7 @@
from typing import Union, List, Dict, Tuple, Optional, Any
from argparse import (
ArgumentParser,
ArgumentError,
Namespace,
SUPPRESS,
_HelpAction,
@ -59,6 +60,30 @@ def get_choice_list(config, properties, display):
return choices
def gen_argument_name(name, is_short_name, force_no, force_del):
if force_no:
if is_short_name:
prefix = "n"
else:
prefix = "no-"
if "." in name:
sname = name.rsplit(".", 1)
name = sname[0] + "." + prefix + sname[1]
else:
name = prefix + name
if force_del:
if is_short_name:
prefix = "p"
else:
prefix = "pop-"
if "." in name:
sname = name.rsplit(".", 1)
name = sname[0] + "." + prefix + sname[1]
else:
name = prefix + name
return name
class TiramisuNamespace(Namespace):
def __init__(self, config: Config, root: Optional[str]) -> None:
super().__setattr__("_config", config)
@ -99,11 +124,13 @@ class TiramisuNamespace(Namespace):
option = self._config.option(true_key)
if option.isfollower():
_setattr = self._setattr_follower
if not value[0].isdecimal():
raise ValueError("index must be a number, not {}".format(value[0]))
index = int(value[0])
index = value[0]
if isinstance(index, str):
if not value[0].isdecimal():
raise ValueError("index must be a number, not {}".format(value[0]))
index = int(index)
option = self._config.option(true_key, index)
true_value = ",".join(value[1:])
true_value = ",".join([str(v) for v in value[1:]])
else:
_setattr = self._setattr
true_value = value
@ -144,7 +171,7 @@ class TiramisuNamespace(Namespace):
"argument {}: invalid choice: '{}' (choose from {})".format(
self.arguments[key],
display_value,
", ".join([f"'{val}'" for val in choices]),
", ".join([f"{val}" for val in choices]),
)
)
else:
@ -153,11 +180,17 @@ class TiramisuNamespace(Namespace):
def _setattr(self, option: "Option", true_key: str, key: str, value: Any) -> None:
if option.ismulti() and value is not None and not isinstance(value, list):
value = [value]
if option.isleader():
# set value for a leader, it began to remove all values!
len_leader = option.value.len()
if len_leader:
for idx in range(len_leader - 1, -1, -1):
option.value.pop(idx)
try:
option.value.set(value)
except PropertiesOptionError:
except PropertiesOptionError as err:
raise AttributeError(
"unrecognized arguments: {}".format(self.arguments[key])
"unrecognized arguments: {} ({})".format(self.arguments[key], err)
)
def _setattr_follower(
@ -185,7 +218,7 @@ class TiramisuHelpFormatter:
# Remove empty OD
if (
self.formatter.remove_empty_od
and len(self.items) == 1
and 0 < len(self.items) <= self.formatter.short_name_max_len
and self.items[0][0].__name__ == "_format_text"
):
return ""
@ -224,34 +257,42 @@ class _BuildKwargs:
(not self.force_no or not add_extra_options)
or (not_display and not display_modified_value)
) and not self.force_del:
if self.force_no:
description = option.information.get("negative_description", None)
else:
description = None
if description is None:
description = option.description()
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:
ga_name = self.gen_argument_name(name, is_short_name)
ga_path = self.gen_argument_name(option.path(), is_short_name)
ga_name = gen_argument_name(
name, is_short_name, self.force_no, self.force_del
)
ga_path = gen_argument_name(
option.path(), is_short_name, self.force_no, self.force_del
)
self.cmdlineparser.namespace.list_force_no[ga_path] = option.path()
elif self.force_del:
ga_name = self.gen_argument_name(name, is_short_name)
ga_path = self.gen_argument_name(option.path(), is_short_name)
ga_name = gen_argument_name(
name, is_short_name, self.force_no, self.force_del
)
ga_path = gen_argument_name(
option.path(), is_short_name, self.force_no, self.force_del
)
self.cmdlineparser.namespace.list_force_del[ga_path] = option.path()
else:
ga_name = name
self.kwargs["dest"] = self.gen_argument_name(option.path(), False)
ga_path = option.path()
self.kwargs["dest"] = gen_argument_name(
option.path(), False, self.force_no, self.force_del
)
argument = self.cmdlineparser._gen_argument(ga_name, is_short_name)
self.cmdlineparser.namespace.arguments[option.path()] = argument
self.cmdlineparser.namespace.arguments[ga_path] = argument
self.args = [argument]
self.ga_name = ga_name
else:
self.cmdlineparser.namespace.arguments[option.path()] = option.path()
self.args = [option.path()]
self.ga_name = name
def __setitem__(self, key: str, value: Any) -> None:
self.kwargs[key] = value
@ -261,38 +302,19 @@ class _BuildKwargs:
option.name(), "longargument" in self.properties
)
if self.force_no:
name = self.gen_argument_name(option.name(), is_short_name)
name = gen_argument_name(
option.name(), is_short_name, self.force_no, self.force_del
)
elif self.force_del:
name = self.gen_argument_name(option.name(), is_short_name)
name = gen_argument_name(
option.name(), is_short_name, self.force_no, self.force_del
)
else:
name = option.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:
if is_short_name:
prefix = "n"
else:
prefix = "no-"
if "." in name:
sname = name.rsplit(".", 1)
name = sname[0] + "." + prefix + sname[1]
else:
name = prefix + name
if self.force_del:
if is_short_name:
prefix = "p"
else:
prefix = "pop-"
if "." in name:
sname = name.rsplit(".", 1)
name = sname[0] + "." + prefix + sname[1]
else:
name = prefix + name
return name
def get(self) -> Tuple[Dict]:
return self.args, self.kwargs
@ -310,6 +332,7 @@ class TiramisuCmdlineParser(ArgumentParser):
unrestraint: bool = False,
add_extra_options: bool = True,
short_name_max_len: int = 1,
add_help: bool = True,
_forhelp: bool = False,
**kwargs,
):
@ -323,11 +346,13 @@ class TiramisuCmdlineParser(ArgumentParser):
self.add_extra_options = add_extra_options
self.display_modified_value = display_modified_value
self.short_name_max_len = short_name_max_len
self.add_help = add_help
if TiramisuHelpFormatter not in formatter_class.__mro__:
formatter_class = type(
"TiramisuHelpFormatter", (TiramisuHelpFormatter, formatter_class), {}
)
formatter_class.remove_empty_od = self.remove_empty_od
formatter_class.short_name_max_len = self.short_name_max_len
kwargs["formatter_class"] = formatter_class
if not _forhelp and self.unrestraint:
subconfig = self.config.unrestraint
@ -338,7 +363,7 @@ class TiramisuCmdlineParser(ArgumentParser):
else:
subconfig = subconfig.option(self.root)
self.namespace = TiramisuNamespace(self.config, self.root)
super().__init__(*args, **kwargs)
super().__init__(*args, add_help=add_help, **kwargs)
self.register("action", "help", _TiramisuHelpAction)
self._config_to_argparser(
_forhelp,
@ -374,9 +399,9 @@ class TiramisuCmdlineParser(ArgumentParser):
return self.prefix_chars + name
return self.prefix_chars * 2 + name
def _parse_known_args(self, args=None, namespace=None):
def _parse_known_args(self, args, namespace, *others):
try:
namespace_, args_ = super()._parse_known_args(args, namespace)
namespace_, args_ = super()._parse_known_args(args, namespace, *others)
except (ValueError, LeadershipError, AttributeError) as err:
self.error(err)
if args != args_ and args_ and args_[0].startswith(self.prefix_chars):
@ -386,6 +411,7 @@ class TiramisuCmdlineParser(ArgumentParser):
self.config,
self.prog,
root=self.root,
exit_on_error=self.exit_on_error,
remove_empty_od=self.remove_empty_od,
display_modified_value=self.display_modified_value,
formatter_class=self.formatter_class,
@ -395,16 +421,16 @@ class TiramisuCmdlineParser(ArgumentParser):
add_extra_options=self.add_extra_options,
short_name_max_len=self.short_name_max_len,
fullpath=self.fullpath,
add_help=self.add_help,
)
namespace_, args_ = new_parser._parse_known_args(
args_, new_parser.namespace
args_, new_parser.namespace, *others
)
else:
if self._registries["action"]["help"].needs:
# display help only when all variables assignemnt are done
self._registries["action"]["help"].needs = False
helper = self._registries["action"]["help"](None)
helper.display(self)
elif self._registries["action"]["help"].needs:
# display help only when all variables assignemnt are done
self._registries["action"]["help"].needs = False
helper = self._registries["action"]["help"](None)
helper.display(self)
return namespace_, args_
def add_argument(self, *args, **kwargs):
@ -454,7 +480,7 @@ class TiramisuCmdlineParser(ArgumentParser):
elif (
self.add_extra_options
and obj.type() == "boolean"
and not obj.issymlinkoption()
# and not obj.issymlinkoption()
):
if not obj.isleader():
yield obj, False, None
@ -472,15 +498,6 @@ class TiramisuCmdlineParser(ArgumentParser):
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
@ -488,7 +505,11 @@ class TiramisuCmdlineParser(ArgumentParser):
# no follower found, search if there is a symlink
for sobj in config.list(uncalculated=True):
try:
if sobj.issymlinkoption() and sobj.option().isleader():
if (
sobj.issymlinkoption()
and sobj.index() is None
and sobj.option().isleader()
):
yield sobj, None, None
except ConfigError:
pass
@ -510,11 +531,19 @@ class TiramisuCmdlineParser(ArgumentParser):
_('name cannot startswith "{}"').format(self.prefix_chars)
)
if option.issymlinkoption():
symlink_name = option.option().name()
if self.fullpath:
argument_name = option.option().path()
else:
argument_name = option.option().name()
is_short_name = len(option.option().name()) == 1
symlink_name = gen_argument_name(
argument_name, is_short_name, force_no, force_del
)
if symlink_name in options_is_not_default:
options_is_not_default[symlink_name]["name"] = name
if symlink_name in actions:
for action in actions[symlink_name]:
action.force_no = force_no
action.add_argument(option)
continue
if force_del:
@ -637,7 +666,7 @@ class TiramisuCmdlineParser(ArgumentParser):
kwargs["nargs"] = 2
if _forhelp and "mandatory" not in properties:
metavar = "[{}]".format(metavar)
if option.type() == "choice":
if _forhelp and option.type() == "choice":
# do not manage choice with argparse there is problem with integer problem
kwargs["metavar"] = (
"INDEX",
@ -656,14 +685,16 @@ class TiramisuCmdlineParser(ArgumentParser):
if _forhelp and option.type() == "boolean":
kwargs["metavar"] = "INDEX"
kwargs["nargs"] = 1
elif option.type() == "choice" and not option.isfollower():
elif _forhelp and option.type() == "choice" and not option.isfollower():
# do not manage choice with argparse there is problem with integer problem
kwargs["choices"] = get_choice_list(option, properties, False)
elif option.type() == "float":
kwargs["type"] = float
else:
pass
actions.setdefault(option.name(), []).append(kwargs)
if not _forhelp and option.type() != "boolean" and "nargs" not in kwargs.kwargs:
kwargs["nargs"] = "?"
actions.setdefault(kwargs.ga_name, []).append(kwargs)
for option_is_not_default in options_is_not_default.values():
self._option_is_not_default(**option_is_not_default)
@ -679,7 +710,9 @@ class TiramisuCmdlineParser(ArgumentParser):
def parse_args(self, *args, valid_mandatory=True, **kwargs):
kwargs["namespace"] = self.namespace
try:
namespaces = super().parse_args(*args, **kwargs)
namespaces, unknown = super().parse_known_args(*args, **kwargs)
if unknown:
msg_unknown = 'unrecognized arguments: %s' % ' '.join(unknown)
except PropertiesOptionError as err:
name = err._subconfig.path
properties = self.config.option(name).property.get()
@ -691,7 +724,7 @@ class TiramisuCmdlineParser(ArgumentParser):
if err.proptype == ["mandatory"]:
self.error("the following arguments are required: {}".format(name))
else:
self.error("unrecognized arguments: {}".format(name))
self.error("unrecognized arguments: {} ({})".format(name, err))
if valid_mandatory:
errors = []
for option in self.config.value.mandatory():
@ -722,6 +755,13 @@ class TiramisuCmdlineParser(ArgumentParser):
self.error(
"the following arguments are required: {}".format(", ".join(errors))
)
if unknown:
if self.exit_on_error:
self.error(msg_unknown)
else:
err = ArgumentError(None, msg_unknown)
err.unknown = unknown
raise err
return namespaces
def format_usage(self, *args, **kwargs):
@ -762,3 +802,9 @@ class TiramisuCmdlineParser(ArgumentParser):
def get_config(self):
return self.config
def error(self, msg):
if self.exit_on_error:
super().error(msg)
else:
raise ArgumentError(None, msg)