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():
"""Get the download directory to use."""
directory = config.val.storage.download_directory
remember_dir = config.val.storage.remember_download_directory
directory = config.val.downloads.location.directory
remember_dir = config.val.downloads.location.remember
if remember_dir and last_used_directory is not None:
return last_used_directory
@ -104,7 +104,7 @@ def _path_suggestion(filename):
Args:
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':
# add trailing '/' if not present
return os.path.join(download_dir(), '')
@ -472,8 +472,6 @@ class AbstractDownloadItem(QObject):
Args:
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"]
start = config.get('colors', 'downloads.{}.start'.format(position))
stop = config.get('colors', 'downloads.{}.stop'.format(position))

View File

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

View File

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

View File

@ -278,7 +278,7 @@ def qute_history(url):
return 'text/html', json.dumps(history_data(start_time))
else:
if (
config.val.content.allow_javascript and
config.val.content.javascript.enabled and
(objects.backend == usertypes.Backend.QtWebEngine or
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))
if config.val.content.javascript.modal_dialog:
raise CallSuper
if config.val.content.ignore_javascript_prompt:
if not config.val.content.javascript.prompt:
return (False, "")
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:
raise CallSuper
if config.val.content.ignore_javascript_alert:
if not config.val.content.javascript.alert:
return
msg = 'From <b>{}</b>:<br/>{}'.format(html.escape(url.toDisplayString()),

View File

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

View File

@ -277,7 +277,7 @@ class BrowserPage(QWebPage):
reply.finished.connect(functools.partial(
self.display_content, reply, 'image/jpeg'))
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
self._show_pdfjs(reply)
else:

View File

@ -25,7 +25,7 @@ import re
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.utils import message, objreg, qtutils, usertypes, utils
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,
QAbstractTextDocumentLayout)
from qutebrowser.config import config, configexc, style
from qutebrowser.config import config, style
from qutebrowser.utils import qtutils

View File

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

View File

@ -536,16 +536,6 @@ completion.show:
- never: Never.
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:
type:
name: TimestampTemplate
@ -909,6 +899,17 @@ downloads.location.remember:
type: Bool
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
# qtwebkit/Source/WebKit/qt/Api/qwebsettings.cpp
@ -1020,13 +1021,11 @@ content.javascript.can_access_clipboard:
allowed.
content.javascript.prompt:
# FIXME:conf meaning changed!
default: true
type: Bool
desc: Show javascript prompts.
content.javascript.alert:
# FIXME:conf meaning changed!
default: false
type: Bool
desc: Show javascript.

View File

@ -161,8 +161,8 @@ class BaseType:
"""Get the setting value from a string.
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
implemented.
string rather than something more sophisticated, this doesn't need to
be implemented.
Args:
value: The original string value.
@ -484,21 +484,21 @@ class BoolAsk(Bool):
self.valid_values = ValidValues('true', 'false', 'ask')
def from_py(self, value):
# basic validation unneeded if it's == 'ask' and done by Bool if we call
# super().from_py
# basic validation unneeded if it's == 'ask' and done by Bool if we
# call super().from_py
if isinstance(value, str) and value.lower() == 'ask':
return 'ask'
return super().from_py(value)
def from_str(self, value):
# basic validation unneeded if it's == 'ask' and done by Bool if we call
# super().from_str
# basic validation unneeded if it's == 'ask' and done by Bool if we
# call super().from_str
if isinstance(value, str) and value.lower() == 'ask':
return 'ask'
return super().from_str(value)
class _Numeric(BaseType):
class _Numeric(BaseType): # pylint: disable=abstract-method
"""Base class for Float/Int.
@ -658,8 +658,8 @@ class PercOrInt(_Numeric):
raise configexc.ValidationError(value, "must be {}% or "
"less!".format(self.maxperc))
# Note we don't actually return the integer here, as we need to know
# whether it was a percentage.
# Note we don't actually return the integer here, as we need to
# know whether it was a percentage.
else:
self._validate_bounds(value)
return value
@ -770,7 +770,9 @@ class Font(BaseType):
if not value:
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")
return value

View File

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

View File

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

View File

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

View File

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

View File

@ -565,7 +565,7 @@ class FilenamePrompt(_BasePrompt):
self.setFocusProxy(self._lineedit)
self._init_key_label()
if config.val.ui.prompt.filebrowser:
if config.val.prompt.filebrowser:
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
@pyqtSlot(str)
@ -627,7 +627,7 @@ class FilenamePrompt(_BasePrompt):
self._file_view.setModel(self._file_model)
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)
else:
self._file_view.hide()

View File

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

View File

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

View File

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

View File

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

View File

@ -841,7 +841,7 @@ def open_file(filename, cmdline=None):
from qutebrowser.config import config
# the default program to open downloads with - will be empty string
# 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

View File

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

View File

@ -22,7 +22,6 @@ import re
import json
import collections
import itertools
import os.path
import warnings
import pytest
@ -796,7 +795,7 @@ class TestPercOrInt:
({'minint': 2, 'maxint': 3}, '4%', '4%'),
])
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', [
({}, '1337%%'),
@ -820,7 +819,7 @@ class TestPercOrInt:
@pytest.mark.parametrize('val', ['1337%', 1337, None])
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'])
def test_from_py_invalid(self, klass, val):
@ -846,7 +845,7 @@ class TestCommand:
'cmd2 baz fish'])
def test_from_py_valid(self, klass, 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', ' '])
def test_from_py_invalid(self, klass, val):
@ -1090,7 +1089,7 @@ class TestFontFamily:
@pytest.mark.parametrize('val', TESTS)
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)
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:
expected = 'baz'
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