cli-function: raise if the config file is given and does not exist

This commit is contained in:
Ciro Santilli 六四事件 法轮功
2019-05-05 00:00:00 +00:00
parent 8dae332c17
commit 5411daa2d3
2 changed files with 27 additions and 22 deletions

View File

@@ -147,15 +147,15 @@ class CliFunction:
def _do_main(self, kwargs):
return self.main(**self._get_args(kwargs))
def __init__(self, config_file=None, description=None, extra_config_params=None):
def __init__(self, default_config_file=None, description=None, extra_config_params=None):
self._arguments = collections.OrderedDict()
self._config_file = config_file
self._default_config_file = default_config_file
self._description = description
self.extra_config_params = extra_config_params
if self._config_file is not None:
if self._default_config_file is not None:
self.add_argument(
'--config-file',
default=self._config_file,
default=self._default_config_file,
help='Path to the configuration file to use'
)
@@ -172,30 +172,35 @@ class CliFunction:
args_with_defaults = kwargs.copy()
# Add missing args from config file.
config_file = None
args_given = {}
if 'config_file' in args_with_defaults and args_with_defaults['config_file'] is not None:
config_file = args_with_defaults['config_file']
args_given['config_file'] = True
else:
config_file = self._config_file
args_given = {}
config_file = self._default_config_file
args_given['config_file'] = False
for key in self._arguments:
args_given[key] = not (
not key in args_with_defaults or
args_with_defaults[key] is None or
self._arguments[key].nargs == '*' and args_with_defaults[key] == []
)
if config_file is not None and os.path.exists(config_file):
config_configs = {}
config = imp.load_source('config', config_file)
if self.extra_config_params is None:
config.set_args(config_configs)
else:
config.set_args(config_configs, self.extra_config_params)
for key in config_configs:
if key not in self._arguments:
raise Exception('Unknown key in config file: ' + key)
if not args_given[key]:
args_with_defaults[key] = config_configs[key]
args_given[key] = True
if config_file is not None:
if os.path.exists(config_file):
config_configs = {}
config = imp.load_source('config', config_file)
if self.extra_config_params is None:
config.set_args(config_configs)
else:
config.set_args(config_configs, self.extra_config_params)
for key in config_configs:
if key not in self._arguments:
raise Exception('Unknown key in config file: ' + key)
if not args_given[key]:
args_with_defaults[key] = config_configs[key]
args_given[key] = True
elif args_given['config_file']:
raise Exception('Config file does not exist: ' + config_file)
# Add missing args from hard-coded defaults.
for key in self._arguments:
argument = self._arguments[key]
@@ -329,7 +334,7 @@ if __name__ == '__main__':
class OneCliFunction(CliFunction):
def __init__(self):
super().__init__(
config_file='cli_function_test_config.py',
default_config_file='cli_function_test_config.py',
description = '''\
Description of this
amazing function!