Move config init out of Application

This commit is contained in:
Florian Bruhin 2014-09-28 00:27:22 +02:00
parent 86fdf981e3
commit 8636562579
3 changed files with 63 additions and 60 deletions

View File

@ -130,7 +130,6 @@ style
- Always use a list as argument for namedtuple? - Always use a list as argument for namedtuple?
- Refactor enum() so it uses a list as second argument (like python - Refactor enum() so it uses a list as second argument (like python
enum/namedtuple). enum/namedtuple).
- Config init and some persistent objects should be moved out of QApplication.
- Use separate logger for config - Use separate logger for config
- Use unittest.Mock and especially unittest.patch more. - Use unittest.Mock and especially unittest.patch more.
- Use decorators for on_config_changed - Use decorators for on_config_changed

View File

@ -31,14 +31,13 @@ import base64
import functools import functools
import traceback import traceback
from PyQt5.QtWidgets import QApplication, QDialog, QMessageBox from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5.QtCore import (pyqtSlot, QTimer, QEventLoop, Qt, QStandardPaths, from PyQt5.QtCore import (pyqtSlot, QTimer, QEventLoop, Qt, QStandardPaths,
qInstallMessageHandler, QObject, QUrl) qInstallMessageHandler, QObject, QUrl)
import qutebrowser import qutebrowser
from qutebrowser.commands import userscripts, runners, cmdutils from qutebrowser.commands import userscripts, runners, cmdutils
from qutebrowser.config import (style, config, websettings, iniparsers, from qutebrowser.config import style, config, websettings
lineparser, configtypes, keyconfparser)
from qutebrowser.network import qutescheme, proxy from qutebrowser.network import qutescheme, proxy
from qutebrowser.browser import quickmarks, cookies, downloads, cache, hints from qutebrowser.browser import quickmarks, cookies, downloads, cache, hints
from qutebrowser.widgets import mainwindow, console, crash from qutebrowser.widgets import mainwindow, console, crash
@ -144,7 +143,7 @@ class Application(QApplication):
objreg.register('readline-bridge', readline_bridge) objreg.register('readline-bridge', readline_bridge)
log.init.debug("Initializing config...") log.init.debug("Initializing config...")
self._init_config() config.init(self._args)
log.init.debug("Initializing crashlog...") log.init.debug("Initializing crashlog...")
self._handle_segfault() self._handle_segfault()
log.init.debug("Initializing modes...") log.init.debug("Initializing modes...")
@ -180,59 +179,6 @@ class Application(QApplication):
debug_console = console.ConsoleWidget() debug_console = console.ConsoleWidget()
objreg.register('debug-console', debug_console) objreg.register('debug-console', debug_console)
def _init_config(self):
"""Inizialize and read the config."""
if self._args.confdir is None:
confdir = utils.get_standard_dir(QStandardPaths.ConfigLocation)
elif self._args.confdir == '':
confdir = None
else:
confdir = self._args.confdir
try:
config_obj = config.ConfigManager(
confdir, 'qutebrowser.conf', self)
except (configtypes.ValidationError,
config.NoOptionError,
config.NoSectionError,
config.UnknownSectionError,
config.InterpolationSyntaxError,
configparser.InterpolationError,
configparser.DuplicateSectionError,
configparser.DuplicateOptionError,
configparser.ParsingError) as e:
log.init.exception(e)
errstr = "Error while reading config:"
if hasattr(e, 'section') and hasattr(e, 'option'):
errstr += "\n\n{} -> {}:".format(e.section, e.option)
errstr += "\n{}".format(e)
msgbox = QMessageBox(QMessageBox.Critical,
"Error while reading config!", errstr)
msgbox.exec_()
# We didn't really initialize much so far, so we just quit hard.
sys.exit(1)
else:
objreg.register('config', config_obj)
try:
key_config = keyconfparser.KeyConfigParser(confdir, 'keys.conf')
except keyconfparser.KeyConfigError as e:
log.init.exception(e)
errstr = "Error while reading key config:\n"
if e.lineno is not None:
errstr += "In line {}: ".format(e.lineno)
errstr += str(e)
msgbox = QMessageBox(QMessageBox.Critical,
"Error while reading key config!", errstr)
msgbox.exec_()
# We didn't really initialize much so far, so we just quit hard.
sys.exit(1)
else:
objreg.register('key-config', key_config)
state_config = iniparsers.ReadWriteConfigParser(confdir, 'state')
objreg.register('state-config', state_config)
command_history = lineparser.LineConfigParser(
confdir, 'cmd_history', ('completion', 'history-length'))
objreg.register('command-history', command_history)
def _handle_segfault(self): def _handle_segfault(self):
"""Handle a segfault from a previous run.""" """Handle a segfault from a previous run."""
# FIXME If an empty logfile exists, we log to stdout instead, which is # FIXME If an empty logfile exists, we log to stdout instead, which is

View File

@ -25,15 +25,18 @@ we borrow some methods and classes from there where it makes sense.
""" """
import os import os
import sys
import os.path import os.path
import functools import functools
import configparser import configparser
import collections.abc import collections.abc
from PyQt5.QtCore import pyqtSignal, QObject from PyQt5.QtCore import pyqtSignal, QObject, QStandardPaths
from PyQt5.QtWidgets import QMessageBox
from qutebrowser.utils import log from qutebrowser.utils import log
from qutebrowser.config import configdata, iniparsers, configtypes, textwrapper from qutebrowser.config import (configdata, iniparsers, configtypes,
textwrapper, lineparser, keyconfparser)
from qutebrowser.commands import cmdexc, cmdutils from qutebrowser.commands import cmdexc, cmdutils
from qutebrowser.utils import message, objreg, utils from qutebrowser.utils import message, objreg, utils
from qutebrowser.utils.usertypes import Completion from qutebrowser.utils.usertypes import Completion
@ -49,6 +52,61 @@ def section(sect):
return objreg.get('config')[sect] return objreg.get('config')[sect]
def init(args):
"""Initialize the config.
Args:
args: The argparse namespace.
"""
if args.confdir is None:
confdir = utils.get_standard_dir(QStandardPaths.ConfigLocation)
elif args.confdir == '':
confdir = None
else:
confdir = args.confdir
try:
app = objreg.get('app')
config_obj = ConfigManager(confdir, 'qutebrowser.conf', app)
except (configtypes.ValidationError, NoOptionError, NoSectionError,
UnknownSectionError, InterpolationSyntaxError,
configparser.InterpolationError,
configparser.DuplicateSectionError,
configparser.DuplicateOptionError,
configparser.ParsingError) as e:
log.init.exception(e)
errstr = "Error while reading config:"
if hasattr(e, 'section') and hasattr(e, 'option'):
errstr += "\n\n{} -> {}:".format(e.section, e.option)
errstr += "\n{}".format(e)
msgbox = QMessageBox(QMessageBox.Critical,
"Error while reading config!", errstr)
msgbox.exec_()
# We didn't really initialize much so far, so we just quit hard.
sys.exit(1)
else:
objreg.register('config', config_obj)
try:
key_config = keyconfparser.KeyConfigParser(confdir, 'keys.conf')
except keyconfparser.KeyConfigError as e:
log.init.exception(e)
errstr = "Error while reading key config:\n"
if e.lineno is not None:
errstr += "In line {}: ".format(e.lineno)
errstr += str(e)
msgbox = QMessageBox(QMessageBox.Critical,
"Error while reading key config!", errstr)
msgbox.exec_()
# We didn't really initialize much so far, so we just quit hard.
sys.exit(1)
else:
objreg.register('key-config', key_config)
state_config = iniparsers.ReadWriteConfigParser(confdir, 'state')
objreg.register('state-config', state_config)
command_history = lineparser.LineConfigParser(
confdir, 'cmd_history', ('completion', 'history-length'))
objreg.register('command-history', command_history)
class NoSectionError(configparser.NoSectionError): class NoSectionError(configparser.NoSectionError):
"""Exception raised when a section was not found.""" """Exception raised when a section was not found."""