qutebrowser/qutebrowser/config/config.py

279 lines
9.4 KiB
Python
Raw Normal View History

2014-02-06 14:01:23 +01:00
# Copyright 2014 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <http://www.gnu.org/licenses/>.
2014-02-18 14:37:49 +01:00
"""Configuration storage and config-related utilities."""
2014-02-17 12:23:52 +01:00
2014-01-27 21:42:00 +01:00
import os
2014-01-31 10:24:00 +01:00
import io
2014-02-17 12:23:52 +01:00
import os.path
2014-01-27 21:42:00 +01:00
import logging
2014-02-27 07:18:36 +01:00
import textwrap
2014-02-18 14:34:46 +01:00
from configparser import (ConfigParser, ExtendedInterpolation, NoSectionError,
NoOptionError)
2014-01-27 21:42:00 +01:00
2014-02-26 09:18:27 +01:00
#from qutebrowser.utils.misc import read_file
2014-02-27 18:46:30 +01:00
import qutebrowser.config.configdata as configdata
2014-02-18 10:07:52 +01:00
2014-01-28 12:21:00 +01:00
config = None
2014-02-18 11:57:35 +01:00
state = None
2014-01-28 12:21:00 +01:00
2014-02-18 14:34:46 +01:00
# Special value for an unset fallback, so None can be passed as fallback.
_UNSET = object()
2014-01-28 23:04:02 +01:00
2014-01-28 12:21:00 +01:00
def init(confdir):
2014-02-19 10:58:32 +01:00
"""Initialize the global objects based on the config in configdir.
Args:
confdir: The directory where the configs are stored in.
"""
global config, state
2014-02-18 11:57:35 +01:00
logging.debug("Config init, confdir {}".format(confdir))
2014-02-26 09:18:27 +01:00
#config = Config(confdir, 'qutebrowser.conf',
# read_file('qutebrowser.conf'))
2014-02-26 07:44:39 +01:00
config = NewConfig()
2014-02-18 11:57:35 +01:00
state = Config(confdir, 'state', always_save=True)
2014-02-10 07:03:51 +01:00
2014-02-18 14:21:39 +01:00
2014-02-26 07:44:39 +01:00
class NewConfig:
2014-02-24 07:17:17 +01:00
2014-02-24 16:47:32 +01:00
"""Contains the structure of the config file."""
2014-02-27 13:11:52 +01:00
2014-02-24 07:17:17 +01:00
def __init__(self):
2014-02-27 18:46:30 +01:00
self.config = configdata.configdata()
2014-02-27 21:23:06 +01:00
self._wrapper_args = {
'width': 72,
'replace_whitespace': False,
'break_long_words': False,
'break_on_hyphens': False,
'drop_whitespace': False,
}
print(str(self))
2014-02-27 07:50:44 +01:00
2014-02-26 07:44:39 +01:00
def __getitem__(self, key):
"""Get a section from the config."""
return self.config[key]
def __str__(self):
"""Get the whole config as a string."""
2014-02-27 21:05:51 +01:00
lines = configdata.FIRST_COMMENT.strip('\n').splitlines()
for secname, section in self.config.items():
2014-02-27 21:05:51 +01:00
lines.append('\n[{}]'.format(secname))
2014-02-27 21:23:06 +01:00
lines += self._str_section_desc(secname)
lines += self._str_option_desc(secname, section)
lines += self._str_items(section)
return '\n'.join(lines)
2014-02-27 21:23:06 +01:00
def _str_section_desc(self, secname):
wrapper = textwrap.TextWrapper(initial_indent='# ',
subsequent_indent='# ',
**self._wrapper_args)
lines = []
seclines = configdata.SECTION_DESC[secname].splitlines()
for secline in seclines:
if 'http://' in secline:
lines.append('# ' + secline)
else:
lines += wrapper.wrap(secline)
if self.config[secname].descriptions:
lines.append('#')
return lines
def _str_option_desc(self, secname, section):
wrapper = textwrap.TextWrapper(initial_indent='#' + ' ' * 5,
subsequent_indent='#' + ' ' * 5,
**self._wrapper_args)
lines = []
for optname, option in section.items():
try:
desc = self.config[secname].descriptions[optname]
except KeyError:
continue
wrapped_desc = []
for descline in desc.splitlines():
wrapped_desc += wrapper.wrap(descline)
lines.append('# {}:\n{}'.format(optname, '\n'.join(wrapped_desc)))
return lines
def _str_items(self, section):
keyval_wrapper = textwrap.TextWrapper(initial_indent='',
subsequent_indent=' ' * 4,
**self._wrapper_args)
lines = []
for optname, option in section.items():
keyval = '{} = {}'.format(optname, option)
if 'http://' in keyval:
lines.append(keyval)
else:
lines += keyval_wrapper.wrap(keyval)
return lines
2014-02-26 07:44:39 +01:00
def get(self, section, option, fallback=_UNSET):
"""Get the real (transformed) value from a section/option."""
try:
val = self.config[section][option]
except KeyError:
if fallback is _UNSET:
raise
else:
return fallback
else:
return val.value
def save(self):
2014-02-26 09:18:27 +01:00
"""Save the config file."""
# FIXME to be implemented
2014-02-26 07:44:39 +01:00
pass
def dump_userconfig(self):
2014-02-26 09:18:27 +01:00
"""Get the part of the config which was changed by the user.
Return:
The changed config part as string.
"""
# FIXME to be implemented
2014-02-26 07:44:39 +01:00
pass
2014-01-27 21:42:00 +01:00
class Config(ConfigParser):
2014-02-07 20:21:50 +01:00
2014-02-18 16:38:13 +01:00
"""Our own ConfigParser subclass.
2014-01-29 15:30:19 +01:00
2014-02-18 16:38:13 +01:00
Attributes:
_configdir: The dictionary to save the config in.
_default_cp: The ConfigParser instance supplying the default values.
_config_loaded: Whether the config was loaded successfully.
"""
2014-01-27 21:42:00 +01:00
2014-02-18 11:57:35 +01:00
def __init__(self, configdir, fname, default_config=None,
always_save=False):
2014-01-29 15:30:19 +01:00
"""Config constructor.
2014-02-19 10:58:32 +01:00
Args:
configdir: Directory to store the config in.
fname: Filename of the config file.
default_config: Default config as string.
always_save: Whether to always save the config, even when it wasn't
loaded.
2014-02-07 20:21:50 +01:00
2014-01-29 15:30:19 +01:00
"""
2014-02-07 14:01:17 +01:00
super().__init__(interpolation=ExtendedInterpolation())
2014-02-18 16:38:13 +01:00
self._config_loaded = False
2014-02-18 11:57:35 +01:00
self.always_save = always_save
2014-02-18 16:38:13 +01:00
self._configdir = configdir
self._default_cp = ConfigParser(interpolation=ExtendedInterpolation())
self._default_cp.optionxform = lambda opt: opt # be case-insensitive
2014-02-18 11:57:35 +01:00
if default_config is not None:
2014-02-18 16:38:13 +01:00
self._default_cp.read_string(default_config)
if not self._configdir:
2014-02-01 20:55:37 +01:00
return
2014-01-28 23:04:02 +01:00
self.optionxform = lambda opt: opt # be case-insensitive
2014-02-18 16:38:13 +01:00
self._configdir = configdir
self.configfile = os.path.join(self._configdir, fname)
2014-01-27 21:42:00 +01:00
if not os.path.isfile(self.configfile):
return
2014-01-27 21:42:00 +01:00
logging.debug("Reading config from {}".format(self.configfile))
self.read(self.configfile)
2014-02-18 16:38:13 +01:00
self._config_loaded = True
2014-01-27 21:42:00 +01:00
def __getitem__(self, key):
"""Get an item from the configparser or default dict.
2014-02-13 18:57:19 +01:00
Extend ConfigParser's __getitem__.
2014-02-07 20:21:50 +01:00
2014-02-19 10:58:32 +01:00
Args:
key: The key to get from the dict.
Return:
The value of the main or fallback ConfigParser.
"""
try:
return super().__getitem__(key)
except KeyError:
2014-02-18 16:38:13 +01:00
return self._default_cp[key]
2014-02-18 14:34:46 +01:00
def get(self, *args, raw=False, vars=None, fallback=_UNSET):
"""Get an item from the configparser or default dict.
2014-02-13 18:57:19 +01:00
Extend ConfigParser's get().
2014-02-07 20:21:50 +01:00
2014-02-18 11:57:19 +01:00
This is a bit of a hack, but it (hopefully) works like this:
- Get value from original configparser.
- If that's not available, try the default_cp configparser
- If that's not available, try the fallback given as kwarg
- If that's not available, we're doomed.
2014-02-19 10:58:32 +01:00
Args:
*args: Passed to the other configparsers.
raw: Passed to the other configparsers (do not interpolate).
var: Passed to the other configparsers.
fallback: Fallback value if value wasn't found in any configparser.
Raise:
configparser.NoSectionError/configparser.NoOptionError if the
default configparser raised them and there is no fallback.
"""
2014-02-18 14:34:46 +01:00
# pylint: disable=redefined-builtin
# The arguments returned by the ConfigParsers actually are strings
# already, but we add an explicit str() here to trick pylint into
# thinking a string is returned (rather than an object) to avoid
# maybe-no-member errors.
2014-02-18 14:34:46 +01:00
try:
return str(super().get(*args, raw=raw, vars=vars))
2014-02-18 14:34:46 +01:00
except (NoSectionError, NoOptionError):
pass
2014-02-18 11:57:19 +01:00
try:
return str(self._default_cp.get(*args, raw=raw, vars=vars))
2014-02-18 14:34:46 +01:00
except (NoSectionError, NoOptionError):
if fallback is _UNSET:
raise
else:
return fallback
2014-01-27 21:42:00 +01:00
def save(self):
2014-01-29 15:30:19 +01:00
"""Save the config file."""
2014-02-18 16:38:13 +01:00
if self._configdir is None or (not self._config_loaded and
not self.always_save):
2014-02-20 20:49:31 +01:00
logging.warning("Not saving config (dir {}, config {})".format(
self._configdir, 'loaded' if self._config_loaded
2014-02-21 19:44:46 +01:00
else 'not loaded'))
2014-01-27 21:42:00 +01:00
return
2014-02-18 16:38:13 +01:00
if not os.path.exists(self._configdir):
os.makedirs(self._configdir, 0o755)
2014-01-27 21:42:00 +01:00
logging.debug("Saving config to {}".format(self.configfile))
with open(self.configfile, 'w') as f:
self.write(f)
2014-01-31 15:58:14 +01:00
f.flush()
os.fsync(f.fileno())
2014-01-31 10:24:00 +01:00
def dump_userconfig(self):
2014-02-19 10:58:32 +01:00
"""Get the part of the config which was changed by the user.
Return:
The changed config part as string.
"""
2014-01-31 10:24:00 +01:00
with io.StringIO() as f:
self.write(f)
return f.getvalue()