From 03fa1a6318c08e275bd41e8839b8fb6387cffd0b Mon Sep 17 00:00:00 2001 From: ulif <uli@gnufix.de> Date: Wed, 11 May 2016 18:16:14 +0200 Subject: [PATCH] Allow plugins to work with the argparser. If plugins want to work with their own commandline args, we allow this by calling their `update_argparser` methods. This has to be a classmethod, if it exists. --- diceware/__init__.py | 6 +++++- tests/test_diceware.py | 12 ++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/diceware/__init__.py b/diceware/__init__.py index 9834639..8df4fcd 100644 --- a/diceware/__init__.py +++ b/diceware/__init__.py @@ -79,7 +79,8 @@ def get_random_sources(): def handle_options(args): """Handle commandline options. """ - random_sources = get_random_sources().keys() + plugins = get_random_sources() + random_sources = plugins.keys() wordlist_names = get_wordlist_names() defaults = get_config_dict() parser = argparse.ArgumentParser( @@ -127,6 +128,9 @@ def handle_options(args): '--version', action='store_true', help='output version information and exit.', ) + for plugin in plugins.values(): + if hasattr(plugin, "update_argparser"): + parser = plugin.update_argparser(parser) parser.set_defaults(**defaults) args = parser.parse_args(args) return args diff --git a/tests/test_diceware.py b/tests/test_diceware.py index 05ad229..2f8cc3a 100644 --- a/tests/test_diceware.py +++ b/tests/test_diceware.py @@ -147,6 +147,18 @@ class TestHandleOptions(object): assert options.delimiter == "my-delim" assert options.caps is False + def test_handle_options_allows_plugins_updating(self, monkeypatch): + # we allow plugins to update our argparser, before being used + import diceware + class FakePlugin(object): + @classmethod + def update_argparser(cls, parser): + parser.add_argument('--foo', default=2, type=int) + return parser + monkeypatch.setattr(diceware, 'get_random_sources', lambda: dict(foo=FakePlugin)) + options = handle_options([]) + assert options.foo == 2 + class TestDicewareModule(object): -- GitLab