config: Add format_initial helper to populate empty configs.

This commit is contained in:
Thomas Adamcik 2013-11-16 21:07:51 +01:00
parent bd1ee7ff39
commit 17a1336e5c
2 changed files with 32 additions and 3 deletions

View File

@ -10,7 +10,7 @@ import re
from mopidy.config import keyring
from mopidy.config.schemas import * # noqa
from mopidy.config.types import * # noqa
from mopidy.utils import path
from mopidy.utils import path, versioning
logger = logging.getLogger('mopidy.config')
@ -41,6 +41,17 @@ _proxy_schema['password'] = Secret(optional=True)
_schemas = [_logging_schema, _loglevels_schema, _audio_schema, _proxy_schema]
_INITIAL_HELP = """
# For further information about options in this file see:
# http://docs.mopidy.com/en/latest/config/
#
# The initial commented out values reflect the defaults as of:
# %(versions)s
#
# Available options and defaults might have changed since then,
# run `mopidy config` to see the current effective config.
"""
def read(config_file):
"""Helper to load config defaults in same way across core and extensions"""
@ -69,6 +80,24 @@ def format(config, extensions, comments=None, display=True):
return _format(config, comments or {}, schemas, display, False)
def format_initial(extensions):
config_dir = os.path.dirname(__file__)
defaults = [read(os.path.join(config_dir, 'default.conf'))]
defaults.extend(e.get_default_config() for e in extensions)
raw_config = _load([], defaults, [])
schemas = _schemas[:]
schemas.extend(e.get_config_schema() for e in extensions)
config, errors = _validate(raw_config, schemas)
versions = ['Mopidy %s' % versioning.get_version()]
for extension in sorted(extensions, key=lambda ext: ext.dist_name):
versions.append('%s %s' % (extension.dist_name, extension.version))
description = _INITIAL_HELP.strip() % {'versions': '\n# '.join(versions)}
return description + '\n\n' + _format(config, {}, schemas, False, True)
def _load(files, defaults, overrides):
parser = configparser.RawConfigParser()
@ -146,7 +175,7 @@ def _format(config, comments, schemas, display, disable):
if disable:
output[-1] = re.sub(r'^', b'#', output[-1], flags=re.M)
output.append(b'')
return b'\n'.join(output[:-1])
return b'\n'.join(output[:-1]).strip()
def _preprocess(config_string):

View File

@ -167,7 +167,7 @@ class List(ConfigValue):
return tuple(values)
def serialize(self, value, display=False):
return b'\n ' + b'\n '.join(encode(v) for v in value if v)
return b'\n ' + b'\n '.join(encode(v) for v in value if v)
class LogLevel(ConfigValue):