Skip to content

Commit

Permalink
Support multiple -v for verbosity
Browse files Browse the repository at this point in the history
  • Loading branch information
Shrews committed Jun 15, 2023
1 parent ec99827 commit 3be9eec
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 6 deletions.
12 changes: 12 additions & 0 deletions docs/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,18 @@ Customizes the level of verbosity:
$ ansible-builder build --verbosity 2
You may also use ``-v`` for the shorthand version. You may either specify an integer for
the verbosity level, or supply multiples of the option. For example, the following are
equivalent to setting the verbosity level to ``3``:

.. code::
$ ansible-builder build -v 3
.. code::
$ ansible-builder build -vvv
``--prune-images``
******************
Expand Down
32 changes: 27 additions & 5 deletions src/ansible_builder/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,29 @@
logger = logging.getLogger(__name__)


class CustomVerbosityAction(argparse.Action):
"""
Custom argparse Action to maintain backward compatibility for '-v N' and '-vvv'.
"""
def __init__(self, option_strings, *args, **kwargs):
super(CustomVerbosityAction, self).__init__(option_strings=option_strings, *args, **kwargs)
self.count = 0

def __call__(self, parser, namespace, values, option_string=None):
if values is None:
self.count += 1
else:
try:
self.count = int(values)
except ValueError:
self.count = values.count('v') + 1

if self.count > constants.max_verbosity:
raise ValueError(f'maximum verbosity is {constants.max_verbosity}')

setattr(namespace, self.dest, self.count)


def run():
args = parse_args()
configure_logger(args.verbosity)
Expand Down Expand Up @@ -164,12 +187,11 @@ def add_container_options(parser):

n.add_argument('-v', '--verbosity',
dest='verbosity',
type=int,
choices=[0, 1, 2, 3],
action=CustomVerbosityAction,
nargs='?',
default=constants.default_verbosity,
help='Increase the output verbosity, for up to three levels of verbosity '
'(invoked via "--verbosity" or "-v" followed by an integer ranging '
'in value from 0 to 3) (default: %(default)s)')
help='Set the verbosity output level. Adding multiple -v will increase the verbosity to a max of 3 (-vvv). '
'Integer values are also accepted (for example, "-v3" or "--verbosity 3"). Default is %(default)s.')


def parse_args(args=sys.argv[1:]):
Expand Down
1 change: 1 addition & 0 deletions src/ansible_builder/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
default_tag = 'ansible-execution-env:latest'
default_build_context = 'context'
default_verbosity = 2
max_verbosity = 3
runtime_files = {
'podman': 'Containerfile',
'docker': 'Dockerfile'
Expand Down
2 changes: 1 addition & 1 deletion test/integration/test_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def test_create_streams_output_with_invalid_verbosity(cli, build_dir_and_ee_yml)
tmpdir, eeyml = build_dir_and_ee_yml("")
result = cli(f"ansible-builder create -c {tmpdir} -f {eeyml} -v 6", allow_error=True)
assert result.rc != 0
assert 'invalid choice: 6 (choose from 0, 1, 2, 3)' in (result.stdout + result.stderr)
assert f'maximum verbosity is {constants.max_verbosity}' in (result.stdout + result.stderr)


def test_inline_str_galaxy_requirements(cli, build_dir_and_ee_yml):
Expand Down
27 changes: 27 additions & 0 deletions test/unit/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,3 +333,30 @@ def test_as_executable_module(capsys):
assert sysexit.value.code == 2 # default rc for "usage"
captured = capsys.readouterr()
assert "usage" in captured.err


def test_verbosity(exec_env_definition_file, tmp_path):
content = {'version': 3}
path = str(exec_env_definition_file(content=content))

for option_val, expected_val in [('-v', 1),
('-v -v', 2),
('-vvv', 3),
('-v 1', 1),
('--verbosity', 1),
('--verbosity=2', 2)
]:
aee = prepare(['create',
'-f', path,
'-c', str(tmp_path),
option_val,
])
assert aee.verbosity == expected_val


def test_invalid_verbosity(exec_env_definition_file, tmp_path):
content = {'version': 3}
path = str(exec_env_definition_file(content=content))
for verbosity in ['-v4', '-vvvv', '-v -v -v -v', '--verbosity=4']:
with pytest.raises(ValueError, match=f'maximum verbosity is {constants.max_verbosity}'):
prepare(['create', '-f', path, '-c', str(tmp_path), verbosity])

0 comments on commit 3be9eec

Please sign in to comment.