Newer
Older
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# weboob is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses/>.
import os
import tempfile
import sys
import weboob.tools.date
from .iconfig import ConfigError, IConfig
try:
from yaml import CLoader as Loader
from yaml import CDumper as Dumper
except ImportError:
from yaml import Loader
from yaml import Dumper
class WeboobDumper(Dumper):
pass
class WeboobNoAliasDumper(WeboobDumper):
def ignore_aliases(self, data):
return True
WeboobDumper.add_representer(weboob.tools.date.date,
WeboobDumper.represent_date)
WeboobDumper.add_representer(weboob.tools.date.datetime,
WeboobDumper.represent_datetime)
DUMPER = WeboobDumper
LOADER = Loader
def __init__(self, path):
self.path = path
def load(self, default={}):
self.values = default.copy()
LOGGER.debug(u'Loading configuration file: %s.' % self.path)
self.values = yaml.load(f, Loader=self.LOADER)
LOGGER.debug(u'Configuration file loaded: %s.' % self.path)
LOGGER.debug(u'Configuration file created with default values: %s.' % self.path)
# write in a temporary file to avoid corruption problems
if sys.version_info.major == 2:
f = tempfile.NamedTemporaryFile(dir=os.path.dirname(self.path), delete=False)
else:
f = tempfile.NamedTemporaryFile(mode='w', dir=os.path.dirname(self.path), delete=False, encoding='utf-8')
with f:
yaml.dump(self.values, f, Dumper=self.DUMPER, default_flow_style=False)
LOGGER.debug(u'Configuration file saved: %s.' % self.path)
def get(self, *args, **kwargs):
v = self.values
try:
v = v[a]
except KeyError:
return kwargs['default']
raise ConfigError()
except TypeError:
raise ConfigError()
return v
def set(self, *args):
v = self.values
for a in args[:-2]:
try:
v = v[a]
except KeyError:
except TypeError:
raise ConfigError()