Compare commits

...

29 commits

Author SHA1 Message Date
0352b2b2aa bump: version 1.0.0rc0 → 1.0.0 2026-06-21 17:21:02 +02:00
13e561fdc0 fix: tiramisu dependencies 2026-06-21 17:20:37 +02:00
ae2e30ebb7 fix: black 2026-06-21 17:09:52 +02:00
782a4bf7e2 bump: version 0.7.0a7 → 1.0.0rc0 2026-06-16 08:33:20 +02:00
b2f929b30d bump: version 0.7.0a6 → 0.7.0a7 2026-06-12 19:57:17 +02:00
d9017bedde fix: remove prog and description attribute 2026-06-12 19:56:49 +02:00
a3c1fa27dc fix: support exit_on_error 2026-06-12 06:17:47 +02:00
fd8829bb24 bump: version 0.7.0a5 → 0.7.0a6 2026-06-11 22:25:08 +02:00
3fca16c874 feat: allow undefined option 2026-06-11 22:24:49 +02:00
0d4c822210 bump: version 0.7.0a4 → 0.7.0a5 2025-12-30 10:46:12 +01:00
6d8472d005 fix:manage frozen only if frozen is in config 2025-12-29 11:22:17 +01:00
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
12 changed files with 512 additions and 176 deletions

View file

@ -1,3 +1,28 @@
## 1.0.0 (2026-06-21)
### Feat
- allow undefined option
- add 'add_help' option un TiramisuCmdLineParser
- do not exit() with exit_on_error to False
- for boolean always add --xxx and --no-xxx
### Fix
- tiramisu dependencies
- black
- remove prog and description attribute
- support exit_on_error
- update test
- better support for boolean help
- black
- formatter.short_name_max_len for symlink
- version
- better leader support
- 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 = "1.0.0"
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",
@ -26,7 +28,7 @@ classifiers = [
]
dependencies = [
"tiramisu >= 5.0,<6",
"tiramisu > 5.1,<6",
]
[project.urls]
@ -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, color=False)
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, color=False)
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, color=False)
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, color=False)
assert to_dict(config.value.get()) == {'verbosity': True}
def test_boolean_false():
config = get_config()
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter, color=False)
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, color=False)
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, color=False)
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, color=False)
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, color=False)
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, color=False)
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, color=False)
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,13 +52,13 @@ 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)
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter, color=False)
parser.parse_args(['str', '1'])
assert to_dict(config.value.get()) == {'positional': 'str',
'positional_int': 1,
@ -88,10 +88,10 @@ 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)
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter, color=False)
parser.parse_args(['str', '1', '--str', 'str1'])
assert to_dict(config.value.get()) == {'positional': 'str',
'positional_int': 1,
@ -128,10 +128,10 @@ 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)
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter, color=False)
parser.parse_args(['str', '1', '--int', '1'])
assert to_dict(config.value.get()) == {'positional': 'str',
'positional_int': 1,
@ -156,10 +156,10 @@ 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)
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter, color=False)
parser.parse_args(['str', '1', '--int_multi', '1', '2'])
assert to_dict(config.value.get()) == {'positional': 'str',
'positional_int': 1,

85
tests/test_exit.py Normal file
View file

@ -0,0 +1,85 @@
import pytest
from argparse import ArgumentError
from tiramisu_cmdline_parser import TiramisuCmdlineParser
from tiramisu import StrOption, BoolOption, OptionDescription, Config
from .utils import TestHelpFormatter
def get_config(has_tree=False, default_verbosity=False):
booloption = BoolOption('disabled',
'disabled',
properties=('disabled',),
)
booloption2 = BoolOption('verbosity',
'increase output verbosity',
default=default_verbosity,
)
stroption = StrOption('option',
'an option',
)
root = OptionDescription('root',
'root',
[booloption, booloption2, stroption],
)
if has_tree:
root = OptionDescription('root',
'root',
[root],
)
config = Config(root)
config.property.read_write()
return config
def test_exit_boolean():
config = get_config(default_verbosity=True)
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter, color=False, exit_on_error=False)
parser.parse_args(['--verbosity'])
parser.parse_known_args(['--verbosity'])
def test_exit_disabled():
config = get_config(default_verbosity=True)
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter, color=False, exit_on_error=False)
error = None
try:
parser.parse_args(['--disabled'])
except ArgumentError as err:
error = err
assert error
assert str(error) == 'unrecognized arguments: --disabled (cannot access to option "disabled" because has property "disabled")'
def test_exit_string():
config = get_config(default_verbosity=True)
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter, color=False, exit_on_error=False)
parser.parse_args(['--option', 'value'])
parser.parse_known_args(['--option', 'value'])
def test_exit_unknown():
config = get_config(default_verbosity=True)
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter, color=False, exit_on_error=False)
error = None
try:
parser.parse_args(['--unknown', 'value'])
except ArgumentError as err:
error = err
assert error
assert str(error) == 'unrecognized arguments: --unknown value'
parser.parse_known_args(['--unknown', 'value'])
def test_exit_known_unknown():
config = get_config(default_verbosity=True)
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter, color=False, exit_on_error=False)
error = None
try:
parser.parse_args(['--option', 'value', '--unknown', 'value'])
except ArgumentError as err:
error = err
assert error
assert str(error) == 'unrecognized arguments: --unknown value'
parser.parse_known_args(['--unknown', 'value'])

View file

@ -51,7 +51,7 @@ options:
od:
{str,list,int,none} choice the sub argument
"""
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', formatter_class=TestHelpFormatter)
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stdout(f):
parser.print_help()
@ -69,7 +69,7 @@ od:
two line
"""
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', epilog="\ntwo\nline", formatter_class=TestHelpFormatter)
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', epilog="\ntwo\nline", formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stdout(f):
parser.print_help()

View file

@ -78,7 +78,7 @@ leader:
--leader.follower_mandatory INDEX FOLLOWER_MANDATORY
Follower mandatory
"""
parser = TiramisuCmdlineParser(get_config(json, with_mandatory=True), 'prog.py', formatter_class=TestHelpFormatter)
parser = TiramisuCmdlineParser(get_config(json, with_mandatory=True), 'prog.py', formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stdout(f):
parser.print_help()
@ -107,7 +107,7 @@ leader:
--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)
parser = TiramisuCmdlineParser(get_config(json, with_mandatory=True), 'prog.py', add_extra_options=False, formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stdout(f):
parser.print_help()
@ -121,10 +121,10 @@ 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)
parser = TiramisuCmdlineParser(get_config(json, with_mandatory=True, with_symlink=True, with_default_value=False), 'prog.py', add_extra_options=False, formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stdout(f):
parser.print_help()
@ -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
@ -153,7 +153,7 @@ leader:
--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)
parser = TiramisuCmdlineParser(get_config(json, with_mandatory=True, with_symlink=True), 'prog.py', add_extra_options=False, formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stdout(f):
parser.print_help()
@ -194,7 +194,7 @@ prog.py: error: unrecognized arguments: 255.255.255.0
"""
config = get_config(json)
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter)
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stderr(f):
try:
@ -306,10 +306,10 @@ 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)
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stderr(f):
try:
@ -327,7 +327,7 @@ prog.py: error: index must be a number, not a
"""
config = get_config(json)
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter)
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stderr(f):
try:
@ -384,7 +384,7 @@ def test_leadership_modif_mandatory(json):
prog.py: error: the following arguments are required: --leader.follower_submulti"""
config = get_config(json, with_mandatory=True)
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter)
parser = TiramisuCmdlineParser(config, 'prog.py', formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stderr(f):
try:
@ -422,7 +422,7 @@ def test_leadership_modif_mandatory_remove(json):
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, formatter_class=TestHelpFormatter)
parser = TiramisuCmdlineParser(config, 'prog.py', display_modified_value=False, formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stderr(f):
try:

View file

@ -99,7 +99,7 @@ options:
-v, --verbosity increase output verbosity (default: False)
-nv, --no-verbosity
"""
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', formatter_class=TestHelpFormatter)
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stdout(f):
parser.print_help()
@ -117,7 +117,7 @@ root:
-v, --root.verbosity increase output verbosity (default: False)
-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, color=False)
f = StringIO()
with redirect_stdout(f):
parser.print_help()
@ -135,7 +135,7 @@ root:
-v, --verbosity increase output verbosity (default: False)
-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, color=False)
f = StringIO()
with redirect_stdout(f):
parser.print_help()
@ -154,7 +154,7 @@ options:
-nv, --no-verbosity
--str STR string option
"""
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', formatter_class=TestHelpFormatter)
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stdout(f):
try:
@ -175,7 +175,7 @@ options:
-nv, --no-verbosity
--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, color=False)
f = StringIO()
with redirect_stdout(f):
try:
@ -199,7 +199,7 @@ options:
-nv, --no-verbosity
--str STR string option
"""
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', formatter_class=TestHelpFormatter)
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stdout(f):
try:
@ -219,7 +219,7 @@ options:
-v, --verbosity increase output verbosity (default: False)
-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, color=False)
f = StringIO()
with redirect_stdout(f):
try:
@ -243,7 +243,7 @@ options:
-nv, --no-verbosity
--str STR string option
"""
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', formatter_class=TestHelpFormatter)
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stdout(f):
try:
@ -264,7 +264,7 @@ options:
-nv, --no-verbosity increase output verbosity (default: False)
--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, color=False)
f = StringIO()
with redirect_stdout(f):
try:
@ -288,7 +288,7 @@ options:
-nv, --no-verbosity
--str STR string option
"""
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', formatter_class=TestHelpFormatter)
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stdout(f):
try:
@ -308,7 +308,7 @@ options:
-v, --verbosity increase output verbosity (default: False)
--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, color=False)
f = StringIO()
with redirect_stdout(f):
try:
@ -324,7 +324,7 @@ 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
"""
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', formatter_class=TestHelpFormatter)
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stderr(f):
try:
@ -340,7 +340,7 @@ def test_readme_positional_mandatory_tree(json):
output = """usage: prog.py [-h] [-v] [-nv] {str,list,int,none}
prog.py: error: the following arguments are required: root.cmd
"""
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', formatter_class=TestHelpFormatter)
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stderr(f):
try:
@ -356,7 +356,7 @@ def test_readme_positional_mandatory_tree_flatten(json):
output = """usage: prog.py [-h] [-v] [-nv] {str,list,int,none}
prog.py: error: the following arguments are required: cmd
"""
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, color=False)
f = StringIO()
with redirect_stderr(f):
try:
@ -372,7 +372,7 @@ def test_readme_mandatory(json):
output = """usage: prog.py "str" [-h] [-v] [-nv] --str STR {str,list,int,none}
prog.py: error: the following arguments are required: --str
"""
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', formatter_class=TestHelpFormatter)
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stderr(f):
try:
@ -388,7 +388,7 @@ 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, formatter_class=TestHelpFormatter)
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', display_modified_value=False, formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stderr(f):
try:
@ -404,7 +404,7 @@ 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
"""
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', formatter_class=TestHelpFormatter)
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stderr(f):
try:
@ -420,7 +420,7 @@ 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, formatter_class=TestHelpFormatter)
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', display_modified_value=False, formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stderr(f):
try:
@ -436,7 +436,7 @@ 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
"""
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, color=False)
f = StringIO()
with redirect_stderr(f):
try:
@ -452,7 +452,7 @@ 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, formatter_class=TestHelpFormatter)
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', fullpath=False, display_modified_value=False, formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stderr(f):
try:
@ -466,9 +466,9 @@ 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)
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stderr(f):
try:
@ -482,9 +482,9 @@ 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)
parser = TiramisuCmdlineParser(get_config(json), 'prog.py', display_modified_value=False, formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stderr(f):
try:
@ -498,9 +498,9 @@ 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)
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stderr(f):
try:
@ -514,9 +514,9 @@ 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)
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', display_modified_value=False, formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stderr(f):
try:
@ -530,9 +530,9 @@ 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)
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', fullpath=False, formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stderr(f):
try:
@ -546,9 +546,9 @@ 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)
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', fullpath=False, display_modified_value=False, formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stderr(f):
try:
@ -562,9 +562,9 @@ 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)
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', fullpath=False, formatter_class=TestHelpFormatter, color=False)
f = StringIO()
with redirect_stderr(f):
try:
@ -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)
parser = TiramisuCmdlineParser(get_config(json, True), 'prog.py', fullpath=False, formatter_class=TestHelpFormatter, color=False)
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

@ -39,19 +39,19 @@ def test_short(json):
#
output = {'list': None, 'l': None}
config = get_config()
parser = TiramisuCmdlineParser(config, 'prog.py')
parser = TiramisuCmdlineParser(config, 'prog.py', color=False)
parser.parse_args([])
assert to_dict(config.value.get()) == output
#
output = {'list': 'a', 'l': 'a'}
config = get_config()
parser = TiramisuCmdlineParser(config, 'prog.py')
parser = TiramisuCmdlineParser(config, 'prog.py', color=False)
parser.parse_args(['--list', 'a'])
assert to_dict(config.value.get()) == output
#
output = {'list': 'a', 'l': 'a'}
config = get_config()
parser = TiramisuCmdlineParser(config, 'prog.py')
parser = TiramisuCmdlineParser(config, 'prog.py', color=False)
parser.parse_args(['-l', 'a'])
assert to_dict(config.value.get()) == output
#
@ -81,7 +81,7 @@ def test_short_mandatory(json):
prog.py: error: the following arguments are required: --list
"""
config = get_config()
parser = TiramisuCmdlineParser(config, 'prog.py')
parser = TiramisuCmdlineParser(config, 'prog.py', color=False)
f = StringIO()
with redirect_stderr(f):
try:
@ -94,13 +94,13 @@ prog.py: error: the following arguments are required: --list
#
output = {'list': 'a', 'l': 'a'}
config = get_config()
parser = TiramisuCmdlineParser(config, 'prog.py')
parser = TiramisuCmdlineParser(config, 'prog.py', color=False)
parser.parse_args(['--list', 'a'])
assert to_dict(config.value.get()) == output
#
output = {'list': 'a', 'l': 'a'}
config = get_config()
parser = TiramisuCmdlineParser(config, 'prog.py')
parser = TiramisuCmdlineParser(config, 'prog.py', color=False)
parser.parse_args(['-l', 'a'])
assert to_dict(config.value.get()) == output
@ -124,31 +124,31 @@ def test_short_multi(json):
#
output = {'list': [], 'l': []}
config = get_config()
parser = TiramisuCmdlineParser(config, 'prog.py')
parser = TiramisuCmdlineParser(config, 'prog.py', color=False)
parser.parse_args([])
assert to_dict(config.value.get()) == output
#
output = {'list': ['a'], 'l': ['a']}
config = get_config()
parser = TiramisuCmdlineParser(config, 'prog.py')
parser = TiramisuCmdlineParser(config, 'prog.py', color=False)
parser.parse_args(['--list', 'a'])
assert to_dict(config.value.get()) == output
#
output = {'list': ['a', 'b'], 'l': ['a', 'b']}
config = get_config()
parser = TiramisuCmdlineParser(config, 'prog.py')
parser = TiramisuCmdlineParser(config, 'prog.py', color=False)
parser.parse_args(['--list', 'a', 'b'])
assert to_dict(config.value.get()) == output
#
output = {'list': ['a'], 'l': ['a']}
config = get_config()
parser = TiramisuCmdlineParser(config, 'prog.py')
parser = TiramisuCmdlineParser(config, 'prog.py', color=False)
parser.parse_args(['-l', 'a'])
assert to_dict(config.value.get()) == output
#
output = {'list': ['a', 'b'], 'l': ['a', 'b']}
config = get_config()
parser = TiramisuCmdlineParser(config, 'prog.py')
parser = TiramisuCmdlineParser(config, 'prog.py', color=False)
parser.parse_args(['-l', 'a', 'b'])
assert to_dict(config.value.get()) == output
@ -175,7 +175,7 @@ def test_short_multi_mandatory(json):
prog.py: error: the following arguments are required: --list
"""
config = get_config()
parser = TiramisuCmdlineParser(config, 'prog.py')
parser = TiramisuCmdlineParser(config, 'prog.py', color=False)
f = StringIO()
with redirect_stderr(f):
try:
@ -188,24 +188,24 @@ prog.py: error: the following arguments are required: --list
#
output = {'list': ['a'], 'l': ['a']}
config = get_config()
parser = TiramisuCmdlineParser(config, 'prog.py')
parser = TiramisuCmdlineParser(config, 'prog.py', color=False)
parser.parse_args(['--list', 'a'])
assert to_dict(config.value.get()) == output
#
output = {'list': ['a', 'b'], 'l': ['a', 'b']}
config = get_config()
parser = TiramisuCmdlineParser(config, 'prog.py')
parser = TiramisuCmdlineParser(config, 'prog.py', color=False)
parser.parse_args(['--list', 'a', 'b'])
assert to_dict(config.value.get()) == output
#
output = {'list': ['a'], 'l': ['a']}
config = get_config()
parser = TiramisuCmdlineParser(config, 'prog.py')
parser = TiramisuCmdlineParser(config, 'prog.py', color=False)
parser.parse_args(['-l', 'a'])
assert to_dict(config.value.get()) == output
#
output = {'list': ['a', 'b'], 'l': ['a', 'b']}
config = get_config()
parser = TiramisuCmdlineParser(config, 'prog.py')
parser = TiramisuCmdlineParser(config, 'prog.py', color=False)
parser.parse_args(['-l', 'a', 'b'])
assert to_dict(config.value.get()) == output

View file

@ -1,4 +1,4 @@
# Copyright (C) 2018-2019 Team tiramisu (see AUTHORS for all contributors)
# Copyright (C) 2018-2026 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
@ -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__ = "1.0.0"

View file

@ -1,4 +1,4 @@
# Copyright (C) 2018-2019 Team tiramisu (see AUTHORS for all contributors)
# Copyright (C) 2018-2025 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
@ -15,6 +15,7 @@
from typing import Union, List, Dict, Tuple, Optional, Any
from argparse import (
ArgumentParser,
ArgumentError,
Namespace,
SUPPRESS,
_HelpAction,
@ -26,19 +27,12 @@ from gettext import gettext as _
# try:
from tiramisu import Config
from tiramisu.error import PropertiesOptionError, LeadershipError, ConfigError
# except ImportError:
# Config = None
# from tiramisu_api.error import PropertiesOptionError
# LeadershipError = ValueError
try:
from tiramisu_api import Config as ConfigJson
if Config is None:
Config = ConfigJson
except ImportError:
ConfigJson = Config
from tiramisu.error import (
PropertiesOptionError,
LeadershipError,
ConfigError,
AttributeOptionError,
)
def get_choice_list(config, properties, display):
@ -59,6 +53,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)
@ -97,13 +115,21 @@ class TiramisuNamespace(Namespace):
else:
true_key = key
option = self._config.option(true_key)
try:
option.get()
except AttributeOptionError:
# We are in this case when we call a parent ArgumentParser not present in current config
# it's useful to dispatch attribute in differents configs
return
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 +170,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 +179,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 +217,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 +256,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 +301,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
@ -300,7 +321,7 @@ class _BuildKwargs:
class TiramisuCmdlineParser(ArgumentParser):
def __init__(
self,
config: Union[Config, ConfigJson],
config: Config,
*args,
root: str = None,
fullpath: bool = True,
@ -310,6 +331,8 @@ class TiramisuCmdlineParser(ArgumentParser):
unrestraint: bool = False,
add_extra_options: bool = True,
short_name_max_len: int = 1,
add_help: bool = True,
exit_on_error: bool = True,
_forhelp: bool = False,
**kwargs,
):
@ -317,17 +340,24 @@ class TiramisuCmdlineParser(ArgumentParser):
unrestraint = True
self.fullpath = fullpath
self.config = config
config_properties = config.property.get()
self.config_frozen = (
"frozen" in config_properties or "everything_frozen" in config_properties
)
self.root = root
self.remove_empty_od = remove_empty_od
self.unrestraint = unrestraint
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
self.kwargs = kwargs.copy()
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 +368,9 @@ 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, exit_on_error=exit_on_error, **kwargs
)
self.register("action", "help", _TiramisuHelpAction)
self._config_to_argparser(
_forhelp,
@ -374,18 +406,20 @@ 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):
kwargs = self.clean_kwargs()
# option that was disabled are no more disable
# so create a new parser
new_parser = TiramisuCmdlineParser(
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 +429,17 @@ 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,
**kwargs,
)
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):
@ -436,7 +471,7 @@ class TiramisuCmdlineParser(ArgumentParser):
obj = None
for obj in config:
# do not display frozen option
if "frozen" in obj.property.get():
if self.config_frozen and "frozen" in obj.property.get():
continue
if obj.isoptiondescription():
if _forhelp:
@ -454,7 +489,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 +507,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 +514,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 +540,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 +675,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 +694,20 @@ 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)
@ -673,13 +717,24 @@ class TiramisuCmdlineParser(ArgumentParser):
args, kwargs = value.get()
group.add_argument(*args, **kwargs)
# def _valid_mandatory(self):
# pass
#
def parse_args(self, *args, valid_mandatory=True, **kwargs):
namespaces, unknown = self.parse_known_args(
*args, valid_mandatory=valid_mandatory, **kwargs
)
if unknown:
msg_unknown = "unrecognized arguments: %s" % " ".join(unknown)
if self.exit_on_error:
self.error(msg_unknown)
else:
err = ArgumentError(None, msg_unknown)
err.unknown = unknown
raise err
return namespaces
def parse_known_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)
except PropertiesOptionError as err:
name = err._subconfig.path
properties = self.config.option(name).property.get()
@ -691,7 +746,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,9 +777,10 @@ class TiramisuCmdlineParser(ArgumentParser):
self.error(
"the following arguments are required: {}".format(", ".join(errors))
)
return namespaces
return namespaces, unknown
def format_usage(self, *args, **kwargs):
kwargs_ = self.clean_kwargs()
help_formatter = TiramisuCmdlineParser(
self.config,
self.prog,
@ -738,12 +794,14 @@ class TiramisuCmdlineParser(ArgumentParser):
epilog=self.epilog,
description=self.description,
_forhelp=True,
**kwargs_,
)
return super(TiramisuCmdlineParser, help_formatter).format_usage(
*args, **kwargs
)
def format_help(self):
kwargs = self.clean_kwargs()
help_formatter = TiramisuCmdlineParser(
self.config,
self.prog,
@ -757,8 +815,22 @@ class TiramisuCmdlineParser(ArgumentParser):
epilog=self.epilog,
description=self.description,
_forhelp=True,
**kwargs,
)
return super(TiramisuCmdlineParser, help_formatter).format_help()
def get_config(self):
return self.config
def error(self, msg):
if self.exit_on_error:
super().error(msg)
else:
raise ArgumentError(None, msg)
def clean_kwargs(self):
kwargs = self.kwargs.copy()
for arg in ["epilog", "prog", "description"]:
if arg in kwargs:
del kwargs[arg]
return kwargs