Config: add configure method

This method is an entry point of a script you could use to created your 
configuration file.

Note: make sure to load to define all your configuration section and 
options
before running it.
This commit is contained in:
Benjamin Renard 2021-11-23 13:02:12 +01:00
parent 6601891f9d
commit d15c4f36fb

View file

@ -12,6 +12,7 @@ import re
import stat
import sys
import textwrap
import traceback
import argcomplete
import keyring
@ -653,11 +654,14 @@ class Config:
def _loaded(self):
""" Execute loaded callbacks """
error = False
for callback in self._loaded_callbacks:
if callback in self._loaded_callbacks_executed:
continue
callback(self)
if not callback(self):
error = True
self._loaded_callbacks_executed.append(callback)
return not error
def save(self, filepath=None):
""" Save configuration file """
@ -859,6 +863,71 @@ class Config:
return True
return result
def configure(self, argv=None, description=False):
"""
Entry point of a script you could use to created your configuration file
Note: make sure to load to define all your configuration section and options
before running it.
"""
parser = self.get_arguments_parser(
description=description if description else "Generate configuration file"
)
parser.add_argument(
'-i', '--interactive',
action='store_true', dest='interactive',
help="Enable configuration interactive mode"
)
parser.add_argument(
'-O', '--overwrite',
action='store_true', dest='overwrite',
help="Overwrite configuration file if exists"
)
parser.add_argument(
'-V', '--validate',
action='store_true', dest='validate',
help=(
"Validate configuration: initialize application to test if provided parameters works.\n\n"
"Note: Validation will occured after configuration file creation or update. On error, "
"re-run with -O/--overwrite parameter to fix it."
)
)
options = self.parse_arguments_options(
argv, create=False, execute_callback=False)
if os.path.exists(options.config) and not options.overwrite:
print('Configuration file %s already exists' % options.config)
sys.exit(1)
if options.interactive:
self.ask_values(set_it=True)
if self.save(options.config):
print('Configuration file %s created.' % options.config)
if options.validate:
print('Validate your configuration...')
try:
if self._loaded():
print('Your configuration seem valid.')
else:
print('Error(s) occurred validating your configuration. See logs for details.')
sys.exit(1)
except Exception:
print(
'Exception occurred validating your configuration: %s\n\nSee logs for details.' %
traceback.format_exc())
sys.exit(2)
else:
print('Error occured creating configuration file %s' %
options.config)
sys.exit(1)
sys.exit(0)
@property
def config_dir(self):
""" Retrieve configuration directory path """