config: Extract encode and decode helpers from String

This commit is contained in:
Thomas Adamcik 2013-04-14 17:34:54 +02:00
parent 9f18d50ab0
commit 7ed9b8adab
3 changed files with 23 additions and 9 deletions

View File

@ -44,8 +44,12 @@ def main():
extensions = [] # Make sure it is defined before the finally block
# TODO: figure out a way to make the boilerplate in this file reusable in
# scanner and other places we need it.
try:
create_file_structures()
# TODO: run raw logging config trough escape code etc, or just validate?
logging_config = config_lib.load(config_files, config_overrides)
log.setup_logging(
logging_config, options.verbosity_level, options.save_debug_log)

View File

@ -8,6 +8,21 @@ from mopidy.utils import path
from mopidy.config import validators
def decode(value):
if isinstance(value, unicode):
return value
# TODO: only unescape \n \t and \\?
return value.decode('string-escape').decode('utf-8')
def encode(value):
if not isinstance(value, unicode):
return value
for char in ('\\', '\n', '\t'): # TODO: more escapes?
value = value.replace(char, char.encode('unicode-escape'))
return value.encode('utf-8')
class ConfigValue(object):
"""Represents a config key's value and how to handle it.
@ -80,10 +95,7 @@ class String(ConfigValue):
Supported kwargs: ``optional``, ``choices``, and ``secret``.
"""
def deserialize(self, value):
if not isinstance(value, unicode):
# TODO: only unescape \n \t and \\?
value = value.decode('string-escape').decode('utf-8')
value = value.strip()
value = decode(value).strip()
validators.validate_required(value, not self.optional)
validators.validate_choice(value, self.choices)
if not value:
@ -91,11 +103,7 @@ class String(ConfigValue):
return value
def serialize(self, value):
if isinstance(value, unicode):
for char in ('\\', '\n', '\t'): # TODO: more escapes?
value = value.replace(char, char.encode('unicode-escape'))
value = value.encode('utf-8')
return value
return encode(value)
class Integer(ConfigValue):

View File

@ -10,6 +10,8 @@ from mopidy.config import types
from tests import unittest
# TODO: DecodeTest and EncodeTest
class ConfigValueTest(unittest.TestCase):
def test_init(self):