Config: Add config_file_env_variable parameter

The new config_file_env_variable parameter allow to specify environment
variable name that will be used to determine configuration file path if
it's not explicitly provided using -c/--config parameter.
This commit is contained in:
Benjamin Renard 2021-11-19 16:16:46 +01:00
parent e6ce412db0
commit 8438f95e68

View file

@ -412,7 +412,8 @@ class RawWrappedTextHelpFormatter(argparse.RawDescriptionHelpFormatter):
class Config:
""" Configuration helper """
def __init__(self, appname, shortname=None, version=None, encoding=None):
def __init__(self, appname, shortname=None, version=None, encoding=None,
config_file_env_variable=None):
self.appname = appname
self.shortname = shortname
self.version = version if version else '0.0'
@ -424,6 +425,7 @@ class Config:
self._loaded_callbacks = []
self._loaded_callbacks_executed = []
self._filepath = None
self.config_file_env_variable = config_file_env_variable
def add_section(self, name, loaded_callback=None, **kwargs):
"""
@ -567,12 +569,14 @@ class Config:
formatter_class=RawWrappedTextHelpFormatter,
**kwargs)
config_file_help = 'Configuration file to use (default: %s)' % self.config_filepath
if self.config_file_env_variable:
config_file_help += '\n\nYou also could set %s environment variable to specify your configuration file path.' % self.config_file_env_variable
self.options_parser.add_argument(
'-c',
'--config',
default=self.config_filepath,
help='Configuration file to use (default: %s)' %
self.config_filepath
help=config_file_help
)
self.options_parser.add_argument(
@ -684,6 +688,8 @@ class Config:
""" Retrieve configuration file path """
if self._filepath:
return self._filepath
if self.config_file_env_variable and os.environ.get(self.config_file_env_variable):
return os.environ.get(self.config_file_env_variable)
return os.path.join(
self.config_dir,
("%s.ini" % self.shortname) if self.shortname