Fix lint and old config options

This commit is contained in:
Florian Bruhin 2017-06-14 19:33:47 +02:00
parent 63bdee8b55
commit 7e7fbf106b
26 changed files with 62 additions and 90 deletions

View File

@ -69,8 +69,8 @@ class UnsupportedOperationError(Exception):
def download_dir(): def download_dir():
"""Get the download directory to use.""" """Get the download directory to use."""
directory = config.val.storage.download_directory directory = config.val.downloads.location.directory
remember_dir = config.val.storage.remember_download_directory remember_dir = config.val.downloads.location.remember
if remember_dir and last_used_directory is not None: if remember_dir and last_used_directory is not None:
return last_used_directory return last_used_directory
@ -104,7 +104,7 @@ def _path_suggestion(filename):
Args: Args:
filename: The filename to use if included in the suggestion. filename: The filename to use if included in the suggestion.
""" """
suggestion = config.val.completion.download_path_suggestion suggestion = config.val.completion.downloads.location.suggestion
if suggestion == 'path': if suggestion == 'path':
# add trailing '/' if not present # add trailing '/' if not present
return os.path.join(download_dir(), '') return os.path.join(download_dir(), '')
@ -472,8 +472,6 @@ class AbstractDownloadItem(QObject):
Args: Args:
position: The color type requested, can be 'fg' or 'bg'. position: The color type requested, can be 'fg' or 'bg'.
""" """
# pylint: disable=bad-config-call
# WORKAROUND for https://bitbucket.org/logilab/astroid/issue/104/
assert position in ["fg", "bg"] assert position in ["fg", "bg"]
start = config.get('colors', 'downloads.{}.start'.format(position)) start = config.get('colors', 'downloads.{}.start'.format(position))
stop = config.get('colors', 'downloads.{}.stop'.format(position)) stop = config.get('colors', 'downloads.{}.stop'.format(position))

View File

@ -119,7 +119,7 @@ class MouseEventFilter(QObject):
return True return True
if e.modifiers() & Qt.ControlModifier: if e.modifiers() & Qt.ControlModifier:
divider = config.val.input.mouse_zoom_divider divider = config.val.zoom.mouse_divider
if divider == 0: if divider == 0:
return False return False
factor = self._tab.zoom.factor() + (e.angleDelta().y() / divider) factor = self._tab.zoom.factor() + (e.angleDelta().y() / divider)

View File

@ -253,6 +253,7 @@ class PACFetcher(QObject):
self._error_message = None self._error_message = None
def __eq__(self, other): def __eq__(self, other):
# pylint: disable=protected-access
return self._pac_url == other._pac_url return self._pac_url == other._pac_url
def __repr__(self): def __repr__(self):

View File

@ -278,7 +278,7 @@ def qute_history(url):
return 'text/html', json.dumps(history_data(start_time)) return 'text/html', json.dumps(history_data(start_time))
else: else:
if ( if (
config.val.content.allow_javascript and config.val.content.javascript.enabled and
(objects.backend == usertypes.Backend.QtWebEngine or (objects.backend == usertypes.Backend.QtWebEngine or
qtutils.is_qtwebkit_ng()) qtutils.is_qtwebkit_ng())
): ):

View File

@ -86,7 +86,7 @@ def javascript_prompt(url, js_msg, default, abort_on):
log.js.debug("prompt: {}".format(js_msg)) log.js.debug("prompt: {}".format(js_msg))
if config.val.content.javascript.modal_dialog: if config.val.content.javascript.modal_dialog:
raise CallSuper raise CallSuper
if config.val.content.ignore_javascript_prompt: if not config.val.content.javascript.prompt:
return (False, "") return (False, "")
msg = '<b>{}</b> asks:<br/>{}'.format(html.escape(url.toDisplayString()), msg = '<b>{}</b> asks:<br/>{}'.format(html.escape(url.toDisplayString()),
@ -108,7 +108,7 @@ def javascript_alert(url, js_msg, abort_on):
if config.val.content.javascript.modal_dialog: if config.val.content.javascript.modal_dialog:
raise CallSuper raise CallSuper
if config.val.content.ignore_javascript_alert: if not config.val.content.javascript.alert:
return return
msg = 'From <b>{}</b>:<br/>{}'.format(html.escape(url.toDisplayString()), msg = 'From <b>{}</b>:<br/>{}'.format(html.escape(url.toDisplayString()),

View File

@ -36,7 +36,7 @@ class WebKitInspector(inspector.AbstractWebInspector):
self._set_widget(qwebinspector) self._set_widget(qwebinspector)
def inspect(self, page): def inspect(self, page):
if not config.val.developer_extras: if not config.val.content.developer_extras:
raise inspector.WebInspectorError( raise inspector.WebInspectorError(
"Please enable developer-extras before using the " "Please enable developer-extras before using the "
"webinspector!") "webinspector!")

View File

@ -277,7 +277,7 @@ class BrowserPage(QWebPage):
reply.finished.connect(functools.partial( reply.finished.connect(functools.partial(
self.display_content, reply, 'image/jpeg')) self.display_content, reply, 'image/jpeg'))
elif (mimetype in ['application/pdf', 'application/x-pdf'] and elif (mimetype in ['application/pdf', 'application/x-pdf'] and
config.val.content.enable_pdfjs): config.val.content.pdfjs):
# Use pdf.js to display the page # Use pdf.js to display the page
self._show_pdfjs(reply) self._show_pdfjs(reply)
else: else:

View File

@ -25,7 +25,7 @@ import re
from PyQt5.QtCore import pyqtSlot, QUrl, QObject from PyQt5.QtCore import pyqtSlot, QUrl, QObject
from qutebrowser.config import config, configexc from qutebrowser.config import config
from qutebrowser.commands import cmdexc, cmdutils from qutebrowser.commands import cmdexc, cmdutils
from qutebrowser.utils import message, objreg, qtutils, usertypes, utils from qutebrowser.utils import message, objreg, qtutils, usertypes, utils
from qutebrowser.misc import split from qutebrowser.misc import split

View File

@ -30,7 +30,7 @@ from PyQt5.QtCore import QRectF, QSize, Qt
from PyQt5.QtGui import (QIcon, QPalette, QTextDocument, QTextOption, from PyQt5.QtGui import (QIcon, QPalette, QTextDocument, QTextOption,
QAbstractTextDocumentLayout) QAbstractTextDocumentLayout)
from qutebrowser.config import config, configexc, style from qutebrowser.config import config, style
from qutebrowser.utils import qtutils from qutebrowser.utils import qtutils

View File

@ -33,7 +33,7 @@ import sys
import re import re
import collections import collections
from qutebrowser.config import configtypes, sections from qutebrowser.config import configtypes
from qutebrowser.utils import usertypes, qtutils, utils from qutebrowser.utils import usertypes, qtutils, utils
DATA = None DATA = None
@ -601,8 +601,8 @@ def _parse_yaml_backends_dict(name, node):
backends = [] backends = []
# The value associated to the key, and whether we should add that backend or # The value associated to the key, and whether we should add that backend
# not. # or not.
conditionals = { conditionals = {
True: True, True: True,
False: False, False: False,

View File

@ -536,16 +536,6 @@ completion.show:
- never: Never. - never: Never.
desc: When to show the autocompletion window. desc: When to show the autocompletion window.
downloads.path_suggestion:
default: path
type:
name: String
valid_values:
- path: Show only the download path.
- filename: Show only download filename.
- both: Show download path and filename.
desc: What to display in the download filename input.
completion.timestamp_format: completion.timestamp_format:
type: type:
name: TimestampTemplate name: TimestampTemplate
@ -909,6 +899,17 @@ downloads.location.remember:
type: Bool type: Bool
desc: Whether to remember the last used download directory. desc: Whether to remember the last used download directory.
downloads.location.suggestion:
default: path
type:
name: String
valid_values:
- path: Show only the download path.
- filename: Show only download filename.
- both: Show download path and filename.
desc: What to display in the download filename input.
# Defaults from QWebSettings::QWebSettings() in # Defaults from QWebSettings::QWebSettings() in
# qtwebkit/Source/WebKit/qt/Api/qwebsettings.cpp # qtwebkit/Source/WebKit/qt/Api/qwebsettings.cpp
@ -1020,13 +1021,11 @@ content.javascript.can_access_clipboard:
allowed. allowed.
content.javascript.prompt: content.javascript.prompt:
# FIXME:conf meaning changed!
default: true default: true
type: Bool type: Bool
desc: Show javascript prompts. desc: Show javascript prompts.
content.javascript.alert: content.javascript.alert:
# FIXME:conf meaning changed!
default: false default: false
type: Bool type: Bool
desc: Show javascript. desc: Show javascript.

View File

@ -161,8 +161,8 @@ class BaseType:
"""Get the setting value from a string. """Get the setting value from a string.
By default this tries to invoke from_py(), so if from_py() accepts a By default this tries to invoke from_py(), so if from_py() accepts a
string rather than something more sophisticated, this doesn't need to be string rather than something more sophisticated, this doesn't need to
implemented. be implemented.
Args: Args:
value: The original string value. value: The original string value.
@ -484,21 +484,21 @@ class BoolAsk(Bool):
self.valid_values = ValidValues('true', 'false', 'ask') self.valid_values = ValidValues('true', 'false', 'ask')
def from_py(self, value): def from_py(self, value):
# basic validation unneeded if it's == 'ask' and done by Bool if we call # basic validation unneeded if it's == 'ask' and done by Bool if we
# super().from_py # call super().from_py
if isinstance(value, str) and value.lower() == 'ask': if isinstance(value, str) and value.lower() == 'ask':
return 'ask' return 'ask'
return super().from_py(value) return super().from_py(value)
def from_str(self, value): def from_str(self, value):
# basic validation unneeded if it's == 'ask' and done by Bool if we call # basic validation unneeded if it's == 'ask' and done by Bool if we
# super().from_str # call super().from_str
if isinstance(value, str) and value.lower() == 'ask': if isinstance(value, str) and value.lower() == 'ask':
return 'ask' return 'ask'
return super().from_str(value) return super().from_str(value)
class _Numeric(BaseType): class _Numeric(BaseType): # pylint: disable=abstract-method
"""Base class for Float/Int. """Base class for Float/Int.
@ -658,8 +658,8 @@ class PercOrInt(_Numeric):
raise configexc.ValidationError(value, "must be {}% or " raise configexc.ValidationError(value, "must be {}% or "
"less!".format(self.maxperc)) "less!".format(self.maxperc))
# Note we don't actually return the integer here, as we need to know # Note we don't actually return the integer here, as we need to
# whether it was a percentage. # know whether it was a percentage.
else: else:
self._validate_bounds(value) self._validate_bounds(value)
return value return value
@ -770,7 +770,9 @@ class Font(BaseType):
if not value: if not value:
return None return None
if not self.font_regex.match(value): # FIXME:conf this used to have "pragma: no cover" if not self.font_regex.match(value): # pragma: no cover
# This should never happen, as the regex always matches everything
# as family.
raise configexc.ValidationError(value, "must be a valid font") raise configexc.ValidationError(value, "must be a valid font")
return value return value

View File

@ -138,10 +138,10 @@ class NewConfigManager(QObject):
def get(self, option): def get(self, option):
try: try:
val = self._values[option] value = self._values[option]
except KeyError as e: except KeyError:
raise configexc.NoOptionError(option) raise configexc.NoOptionError(option)
return val.typ.from_py(val.default) return value.typ.from_py(value.default)
class ConfigContainer: class ConfigContainer:

View File

@ -20,10 +20,8 @@
"""Utilities related to the look&feel of qutebrowser.""" """Utilities related to the look&feel of qutebrowser."""
import functools import functools
import collections
import sip import sip
from PyQt5.QtGui import QColor
from qutebrowser.config import config from qutebrowser.config import config
from qutebrowser.utils import log, objreg, jinja from qutebrowser.utils import log, objreg, jinja

View File

@ -271,7 +271,7 @@ class BaseKeyParser(QObject):
count: The count to pass. count: The count to pass.
""" """
self._debug_log("Ambiguous match for '{}'".format(self._keystring)) self._debug_log("Ambiguous match for '{}'".format(self._keystring))
time = config.val.input.timeout time = config.val.input.ambiguous_timeout
if time == 0: if time == 0:
# execute immediately # execute immediately
self.clear_keystring() self.clear_keystring()

View File

@ -98,7 +98,7 @@ def get_window(via_ipc, force_window=False, force_tab=False,
def get_target_window(): def get_target_window():
"""Get the target window for new tabs, or None if none exist.""" """Get the target window for new tabs, or None if none exist."""
try: try:
win_mode = config.val.new_instance_open_target.window win_mode = config.val.new_instance_open_target_window
if win_mode == 'last-focused': if win_mode == 'last-focused':
return objreg.last_focused_window() return objreg.last_focused_window()
elif win_mode == 'first-opened': elif win_mode == 'first-opened':

View File

@ -565,7 +565,7 @@ class FilenamePrompt(_BasePrompt):
self.setFocusProxy(self._lineedit) self.setFocusProxy(self._lineedit)
self._init_key_label() self._init_key_label()
if config.val.ui.prompt.filebrowser: if config.val.prompt.filebrowser:
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
@pyqtSlot(str) @pyqtSlot(str)
@ -627,7 +627,7 @@ class FilenamePrompt(_BasePrompt):
self._file_view.setModel(self._file_model) self._file_view.setModel(self._file_model)
self._file_view.clicked.connect(self._insert_path) self._file_view.clicked.connect(self._insert_path)
if config.val.ui.prompt.filebrowser: if config.val.prompt.filebrowser:
self._vbox.addWidget(self._file_view) self._vbox.addWidget(self._file_view)
else: else:
self._file_view.hide() self._file_view.hide()

View File

@ -484,7 +484,7 @@ class TabBar(QTabBar):
minimum_size = self.minimumTabSizeHint(index) minimum_size = self.minimumTabSizeHint(index)
height = minimum_size.height() height = minimum_size.height()
if self.vertical: if self.vertical:
confwidth = str(config.val.tabs.width) confwidth = str(config.val.tabs.width.bar)
if confwidth.endswith('%'): if confwidth.endswith('%'):
main_window = objreg.get('main-window', scope='window', main_window = objreg.get('main-window', scope='window',
window=self._win_id) window=self._win_id)
@ -593,7 +593,7 @@ class TabBar(QTabBar):
Args: Args:
e: The QWheelEvent e: The QWheelEvent
""" """
if config.val.tabs.mousewheel_tab_switching: if config.val.tabs.mousewheel_switching:
super().wheelEvent(e) super().wheelEvent(e)
else: else:
tabbed_browser = objreg.get('tabbed-browser', scope='window', tabbed_browser = objreg.get('tabbed-browser', scope='window',

View File

@ -75,7 +75,7 @@ class ExternalEditor(QObject):
try: try:
if exitcode != 0: if exitcode != 0:
return return
encoding = config.val.editor_encoding encoding = config.val.editor.encoding
try: try:
with open(self._file.name, 'r', encoding=encoding) as f: with open(self._file.name, 'r', encoding=encoding) as f:
text = f.read() text = f.read()
@ -102,14 +102,14 @@ class ExternalEditor(QObject):
if self._text is not None: if self._text is not None:
raise ValueError("Already editing a file!") raise ValueError("Already editing a file!")
self._text = text self._text = text
encoding = config.val.editor_encoding
try: try:
# Close while the external process is running, as otherwise systems # Close while the external process is running, as otherwise systems
# with exclusive write access (e.g. Windows) may fail to update # with exclusive write access (e.g. Windows) may fail to update
# the file from the external editor, see # the file from the external editor, see
# https://github.com/qutebrowser/qutebrowser/issues/1767 # https://github.com/qutebrowser/qutebrowser/issues/1767
with tempfile.NamedTemporaryFile( with tempfile.NamedTemporaryFile(
mode='w', prefix='qutebrowser-editor-', encoding=encoding, mode='w', prefix='qutebrowser-editor-',
encoding=config.val.editor.encoding,
delete=False) as fobj: delete=False) as fobj:
if text: if text:
fobj.write(text) fobj.write(text)
@ -120,7 +120,7 @@ class ExternalEditor(QObject):
self._proc = guiprocess.GUIProcess(what='editor', parent=self) self._proc = guiprocess.GUIProcess(what='editor', parent=self)
self._proc.finished.connect(self.on_proc_closed) self._proc.finished.connect(self.on_proc_closed)
self._proc.error.connect(self.on_proc_error) self._proc.error.connect(self.on_proc_error)
editor = config.val.editor editor = config.val.editor.command
executable = editor[0] executable = editor[0]
args = [arg.replace('{}', self._file.name) for arg in editor[1:]] args = [arg.replace('{}', self._file.name) for arg in editor[1:]]
log.procs.debug("Calling \"{}\" with args {}".format(executable, args)) log.procs.debug("Calling \"{}\" with args {}".format(executable, args))

View File

@ -382,7 +382,7 @@ class SessionManager(QObject):
path = self._get_session_path(name, check_exists=True) path = self._get_session_path(name, check_exists=True)
try: try:
with open(path, encoding='utf-8') as f: with open(path, encoding='utf-8') as f:
data = utils.yaml_load(f, Loader=YamlLoader) data = utils.yaml_load(f)
except (OSError, UnicodeDecodeError, yaml.YAMLError) as e: except (OSError, UnicodeDecodeError, yaml.YAMLError) as e:
raise SessionError(e) raise SessionError(e)

View File

@ -78,6 +78,8 @@ class Loader(jinja2.BaseLoader):
class Environment(jinja2.Environment): class Environment(jinja2.Environment):
"""Our own jinja environment which is more strict."""
def __init__(self): def __init__(self):
super().__init__(loader=Loader('html'), super().__init__(loader=Loader('html'),
autoescape=self._guess_autoescape, autoescape=self._guess_autoescape,

View File

@ -99,6 +99,7 @@ def _get_search_url(txt):
engine, term = _parse_search_term(txt) engine, term = _parse_search_term(txt)
assert term assert term
if engine is None: if engine is None:
# FIXME:conf
template = config.val.searchengines.DEFAULT template = config.val.searchengines.DEFAULT
else: else:
template = config.get('searchengines', engine) template = config.get('searchengines', engine)

View File

@ -841,7 +841,7 @@ def open_file(filename, cmdline=None):
from qutebrowser.config import config from qutebrowser.config import config
# the default program to open downloads with - will be empty string # the default program to open downloads with - will be empty string
# if we want to use the default # if we want to use the default
override = config.val.default_open_dispatcher override = config.val.downloads.open_dispatcher
# precedence order: cmdline > default-open-dispatcher > openUrl # precedence order: cmdline > default-open-dispatcher > openUrl

View File

@ -195,8 +195,8 @@ class TestParseYamlBackend:
@pytest.mark.parametrize('backend, expected', [ @pytest.mark.parametrize('backend, expected', [
('QtWebKit', [usertypes.Backend.QtWebKit]), ('QtWebKit', [usertypes.Backend.QtWebKit]),
('QtWebEngine', [usertypes.Backend.QtWebEngine]), ('QtWebEngine', [usertypes.Backend.QtWebEngine]),
# This is also what _parse_yaml_backends gets when backend: is not given # This is also what _parse_yaml_backends gets when backend: is not
# at all # given at all
('null', [usertypes.Backend.QtWebKit, usertypes.Backend.QtWebEngine]), ('null', [usertypes.Backend.QtWebKit, usertypes.Backend.QtWebEngine]),
]) ])
def test_simple(self, backend, expected): def test_simple(self, backend, expected):

View File

@ -22,7 +22,6 @@ import re
import json import json
import collections import collections
import itertools import itertools
import os.path
import warnings import warnings
import pytest import pytest
@ -796,7 +795,7 @@ class TestPercOrInt:
({'minint': 2, 'maxint': 3}, '4%', '4%'), ({'minint': 2, 'maxint': 3}, '4%', '4%'),
]) ])
def test_from_str_valid(self, klass, kwargs, val, expected): def test_from_str_valid(self, klass, kwargs, val, expected):
klass(**kwargs).from_str(val) == expected assert klass(**kwargs).from_str(val) == expected
@pytest.mark.parametrize('kwargs, val', [ @pytest.mark.parametrize('kwargs, val', [
({}, '1337%%'), ({}, '1337%%'),
@ -820,7 +819,7 @@ class TestPercOrInt:
@pytest.mark.parametrize('val', ['1337%', 1337, None]) @pytest.mark.parametrize('val', ['1337%', 1337, None])
def test_from_py_valid(self, klass, val): def test_from_py_valid(self, klass, val):
klass(none_ok=True).from_py(val) == val assert klass(none_ok=True).from_py(val) == val
@pytest.mark.parametrize('val', ['1337%%', '1337']) @pytest.mark.parametrize('val', ['1337%%', '1337'])
def test_from_py_invalid(self, klass, val): def test_from_py_invalid(self, klass, val):
@ -846,7 +845,7 @@ class TestCommand:
'cmd2 baz fish']) 'cmd2 baz fish'])
def test_from_py_valid(self, klass, val): def test_from_py_valid(self, klass, val):
expected = None if not val else val expected = None if not val else val
klass(none_ok=True).from_py(val) == expected assert klass(none_ok=True).from_py(val) == expected
@pytest.mark.parametrize('val', ['', 'cmd3', 'cmd3 foo bar', ' ']) @pytest.mark.parametrize('val', ['', 'cmd3', 'cmd3 foo bar', ' '])
def test_from_py_invalid(self, klass, val): def test_from_py_invalid(self, klass, val):
@ -1090,7 +1089,7 @@ class TestFontFamily:
@pytest.mark.parametrize('val', TESTS) @pytest.mark.parametrize('val', TESTS)
def test_from_py_valid(self, klass, val): def test_from_py_valid(self, klass, val):
klass(none_ok=True).from_py(val) == val assert klass(none_ok=True).from_py(val) == val
@pytest.mark.parametrize('val', INVALID) @pytest.mark.parametrize('val', INVALID)
def test_from_py_invalid(self, klass, val): def test_from_py_invalid(self, klass, val):

View File

@ -85,31 +85,3 @@ def test_set_register_stylesheet(delete, qtbot, config_stub, caplog):
else: else:
expected = 'baz' expected = 'baz'
assert obj.rendered_stylesheet == expected assert obj.rendered_stylesheet == expected
class TestColorDict:
@pytest.mark.parametrize('key, expected', [
('foo', 'one'),
('foo.fg', 'two'),
('foo.bg', 'three'),
])
def test_values(self, key, expected):
d = style.ColorDict()
d['foo'] = 'one'
d['foo.fg'] = 'two'
d['foo.bg'] = 'three'
assert d[key] == expected
def test_key_error(self, caplog):
d = style.ColorDict()
with caplog.at_level(logging.ERROR):
d['foo'] # pylint: disable=pointless-statement
assert len(caplog.records) == 1
assert caplog.records[0].message == 'No color defined for foo!'
def test_qcolor(self):
d = style.ColorDict()
d['foo'] = QColor()
with pytest.raises(TypeError):
d['foo'] # pylint: disable=pointless-statement