From 9ec1b24c2e5443b034533dd500861afa2e0ee8e3 Mon Sep 17 00:00:00 2001 From: Daniel Mach Date: Mon, 17 Jul 2023 08:59:10 +0200 Subject: [PATCH] Add '--setopt' option for setting config options from the command-line --- osc/commandline.py | 13 +++++++++++++ osc/conf.py | 21 ++++++++++++++++++--- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/osc/commandline.py b/osc/commandline.py index 9ec6a08841..4698835a14 100644 --- a/osc/commandline.py +++ b/osc/commandline.py @@ -383,6 +383,13 @@ def init_arguments(self): metavar="FILE", help="specify alternate configuration file", ) + self.add_argument( + "--setopt", + metavar="KEY=VALUE", + action="append", + default=[], + help="set a config option for the current program run", + ) self.add_argument( "--no-keyring", action="store_true", @@ -401,6 +408,11 @@ def post_parse_args(self, args): # let's leave setting the right value to conf.get_config() pass + overrides = {} + for i in args.setopt: + key, value = i.split("=") + overrides[key] = value + try: conf.get_config( override_apiurl=args.apiurl, @@ -412,6 +424,7 @@ def post_parse_args(self, args): override_post_mortem=args.post_mortem, override_traceback=args.traceback, override_verbose=args.verbose, + overrides=overrides, ) except oscerr.NoConfigfile as e: print(e.msg, file=sys.stderr) diff --git a/osc/conf.py b/osc/conf.py index cb65bb372c..b7d9d7bbf1 100644 --- a/osc/conf.py +++ b/osc/conf.py @@ -232,11 +232,13 @@ def apply_option_types(config, conffile=""): cp = OscConfigParser.OscConfigParser(config) cp.add_section("general") - typed_opts = ((_boolean_opts, cp.getboolean), (_integer_opts, cp.getint)) - for opts, meth in typed_opts: + typed_opts = ((_boolean_opts, cp.getboolean, bool), (_integer_opts, cp.getint, int)) + for opts, meth, typ in typed_opts: for opt in opts: if opt not in config: continue + if isinstance(config[opt], typ): + continue try: config[opt] = meth('general', opt) except ValueError as e: @@ -750,7 +752,9 @@ def get_config(override_conffile=None, override_traceback=None, override_post_mortem=None, override_no_keyring=None, - override_verbose=None): + override_verbose=None, + overrides=None + ): """do the actual work (see module documentation)""" global config @@ -786,6 +790,17 @@ def get_config(override_conffile=None, raise oscerr.ConfigError(msg, conffile) config = dict(cp.items('general', raw=1)) + + # if the overrides trigger an exception, the 'post_mortem' option + # must be set to the appropriate type otherwise the non-empty string gets evaluated as True + config = apply_option_types(config, conffile) + + overrides = overrides or {} + for key, value in overrides.items(): + if key not in config: + raise oscerr.ConfigError(f"Unknown config option '{key}'", "") + config[key] = value + config['conffile'] = conffile config = apply_option_types(config, conffile)