diff --git a/pmb/parse/arguments.py b/pmb/parse/arguments.py index f71a31e2..42e8970c 100644 --- a/pmb/parse/arguments.py +++ b/pmb/parse/arguments.py @@ -23,6 +23,26 @@ import pmb.helpers.pmaports See pmb/helpers/args.py for more information about the args variable. """ +def toggle_other_boolean_flags(*other_destinations, value=True): + """ Helper function to group several argparse flags to one. Sets multiple + other_destination to value. + + :param other_destinations: 'the other argument names' str + :param value 'the value to set the other_destinations to' bool + :returns custom Action""" + + class SetOtherDestinationsAction(argparse.Action): + def __init__(self, option_strings, dest, **kwargs): + super().__init__(option_strings, dest, nargs=0, const=value, + default=value, **kwargs) + + def __call__(self, parser, namespace, values, option_string=None): + for destination in other_destinations: + setattr(namespace, destination, value) + + return SetOtherDestinationsAction + + def type_ondev_cp(val): """ Parse and validate arguments to 'pmbootstrap install --ondev --cp'. @@ -707,6 +727,16 @@ def arguments(): zap.add_argument("-r", "--rust", action="store_true", help="also delete rust related caches") + zap_all_delete_args = ["http", "distfiles", "pkgs_local", + "pkgs_local_mismatch", "netboot", "pkgs_online_mismatch", + "rust"] + zap_all_delete_args_print = [arg.replace("_", "-") + for arg in zap_all_delete_args] + zap.add_argument("-a", "--all", + action=toggle_other_boolean_flags(*zap_all_delete_args), + help="delete everything, equivalent to: " + f"--{' --'.join(zap_all_delete_args_print)}") + # Action: stats stats = sub.add_parser("stats", help="show ccache stats") stats.add_argument("--arch", default=arch_native, choices=arch_choices) diff --git a/test/test_arguments.py b/test/test_arguments.py new file mode 100644 index 00000000..ed841118 --- /dev/null +++ b/test/test_arguments.py @@ -0,0 +1,27 @@ +# SPDX-License-Identifier: GPL-3.0-or-later + +import argparse + +import pytest + +from pmb.parse.arguments import toggle_other_boolean_flags + + +@pytest.fixture +def example_cli_with_flags(): + parser = argparse.ArgumentParser(prog="sample cli") + parser.add_argument("-f1", "--flag1", action="store_true") + parser.add_argument("-f2", "--flag2", action="store_true") + return parser + + +def test_toggle_other_boolean_flags(example_cli_with_flags): + other_flags = ["flag1", "flag2"] + example_cli_with_flags.add_argument( + "-f12", "--flag12", + action=toggle_other_boolean_flags(*other_flags)) + args = example_cli_with_flags.parse_args(['-f12']) + + expected_flags_true = other_flags + ["flag12"] + for flag in expected_flags_true: + assert getattr(args, flag)