summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorFlorian Bruhin <me@the-compiler.org>2021-12-02 17:30:47 +0100
committerFlorian Bruhin <me@the-compiler.org>2021-12-02 17:30:47 +0100
commited2342a43093a137f5260923eeb5946f4bbb65ee (patch)
treec27fc570fe52e56000c5d0963a5a8d77de89abd1
parentb9d58034d11674c65dfc5db0d424017cef09ff56 (diff)
downloadqutebrowser-ed2342a43093a137f5260923eeb5946f4bbb65ee.tar.gz
qutebrowser-ed2342a43093a137f5260923eeb5946f4bbb65ee.zip
pylint: Handle consider-using-with
-rw-r--r--qutebrowser/browser/downloads.py2
-rw-r--r--qutebrowser/browser/qtnetworkdownloads.py1
-rw-r--r--qutebrowser/browser/shared.py7
-rw-r--r--qutebrowser/commands/userscripts.py5
-rw-r--r--qutebrowser/components/hostblock.py7
-rw-r--r--qutebrowser/components/utils/blockutils.py2
-rw-r--r--qutebrowser/misc/crashsignal.py1
-rw-r--r--qutebrowser/misc/quitter.py2
-rwxr-xr-xscripts/dev/build_release.py14
-rwxr-xr-xscripts/dev/update_3rdparty.py10
-rwxr-xr-xscripts/dictcli.py14
-rw-r--r--scripts/hostblock_blame.py4
-rw-r--r--tests/end2end/data/brave-adblock/generate.py6
-rw-r--r--tests/end2end/fixtures/test_webserver.py5
-rw-r--r--tests/unit/utils/test_qtutils.py3
15 files changed, 43 insertions, 40 deletions
diff --git a/qutebrowser/browser/downloads.py b/qutebrowser/browser/downloads.py
index 4f7897c9d..32bfd2693 100644
--- a/qutebrowser/browser/downloads.py
+++ b/qutebrowser/browser/downloads.py
@@ -1352,6 +1352,7 @@ class TempDownloadManager:
The tempfile.TemporaryDirectory that is used.
"""
if self._tmpdir is None:
+ # pylint: disable=consider-using-with
self._tmpdir = tempfile.TemporaryDirectory(
prefix='qutebrowser-downloads-')
return self._tmpdir
@@ -1373,6 +1374,7 @@ class TempDownloadManager:
suggested_name = utils.sanitize_filename(suggested_name)
# Make sure that the filename is not too long
suggested_name = utils.elide_filename(suggested_name, 50)
+ # pylint: disable=consider-using-with
fobj = tempfile.NamedTemporaryFile(dir=tmpdir.name, delete=False,
suffix='_' + suggested_name)
self.files.append(fobj)
diff --git a/qutebrowser/browser/qtnetworkdownloads.py b/qutebrowser/browser/qtnetworkdownloads.py
index f048d293d..82ed94380 100644
--- a/qutebrowser/browser/qtnetworkdownloads.py
+++ b/qutebrowser/browser/qtnetworkdownloads.py
@@ -110,6 +110,7 @@ class DownloadItem(downloads.AbstractDownloadItem):
"""Create a file object using the internal filename."""
assert self._filename is not None
try:
+ # pylint: disable=consider-using-with
fileobj = open(self._filename, 'wb')
except OSError as e:
self._die(e.strerror)
diff --git a/qutebrowser/browser/shared.py b/qutebrowser/browser/shared.py
index 8d3ebe730..2fd0d0c65 100644
--- a/qutebrowser/browser/shared.py
+++ b/qutebrowser/browser/shared.py
@@ -418,12 +418,11 @@ def choose_file(qb_mode: FileSelectionMode) -> List[str]:
}[qb_mode]
use_tmp_file = any('{}' in arg for arg in command[1:])
if use_tmp_file:
- handle = tempfile.NamedTemporaryFile(
+ with tempfile.NamedTemporaryFile(
prefix='qutebrowser-fileselect-',
delete=False,
- )
- handle.close()
- tmpfilename = handle.name
+ ) as handle:
+ tmpfilename = handle.name
with utils.cleanup_file(tmpfilename):
command = (
command[:1] +
diff --git a/qutebrowser/commands/userscripts.py b/qutebrowser/commands/userscripts.py
index 70c639207..8282aa7c7 100644
--- a/qutebrowser/commands/userscripts.py
+++ b/qutebrowser/commands/userscripts.py
@@ -342,9 +342,8 @@ class _WindowsUserscriptRunner(_BaseUserscriptRunner):
self._kwargs = kwargs
try:
- handle = tempfile.NamedTemporaryFile(delete=False)
- handle.close()
- self._filepath = handle.name
+ with tempfile.NamedTemporaryFile(delete=False) as handle:
+ self._filepath = handle.name
except OSError as e:
message.error("Error while creating tempfile: {}".format(e))
return
diff --git a/qutebrowser/components/hostblock.py b/qutebrowser/components/hostblock.py
index 1860b734c..191719f10 100644
--- a/qutebrowser/components/hostblock.py
+++ b/qutebrowser/components/hostblock.py
@@ -64,9 +64,10 @@ def get_fileobj(byte_io: IO[bytes]) -> IO[bytes]:
byte_io.seek(0) # rewind downloaded file
if zipfile.is_zipfile(byte_io):
byte_io.seek(0) # rewind what zipfile.is_zipfile did
- zf = zipfile.ZipFile(byte_io)
- filename = _guess_zip_filename(zf)
- byte_io = zf.open(filename, mode="r")
+ with zipfile.ZipFile(byte_io) as zf:
+ filename = _guess_zip_filename(zf)
+ # pylint: disable=consider-using-with
+ byte_io = zf.open(filename, mode="r")
else:
byte_io.seek(0) # rewind what zipfile.is_zipfile did
return byte_io
diff --git a/qutebrowser/components/utils/blockutils.py b/qutebrowser/components/utils/blockutils.py
index bd27baece..98681a488 100644
--- a/qutebrowser/components/utils/blockutils.py
+++ b/qutebrowser/components/utils/blockutils.py
@@ -125,7 +125,7 @@ class BlocklistDownloads(QObject):
filename: path to a local file to import.
"""
try:
- fileobj = open(filename, "rb")
+ fileobj = open(filename, "rb") # pylint: disable=consider-using-with
except OSError as e:
message.error(
"blockutils: Error while reading {}: {}".format(filename, e.strerror)
diff --git a/qutebrowser/misc/crashsignal.py b/qutebrowser/misc/crashsignal.py
index 45c52f54c..4ba1aca44 100644
--- a/qutebrowser/misc/crashsignal.py
+++ b/qutebrowser/misc/crashsignal.py
@@ -150,6 +150,7 @@ class CrashHandler(QObject):
"""Start a new logfile and redirect faulthandler to it."""
logname = os.path.join(standarddir.data(), 'crash.log')
try:
+ # pylint: disable=consider-using-with
self._crash_log_file = open(logname, 'w', encoding='ascii')
except OSError:
log.init.exception("Error while opening crash log file!")
diff --git a/qutebrowser/misc/quitter.py b/qutebrowser/misc/quitter.py
index a51891685..905429989 100644
--- a/qutebrowser/misc/quitter.py
+++ b/qutebrowser/misc/quitter.py
@@ -194,7 +194,7 @@ class Quitter(QObject):
# Open a new process and immediately shutdown the existing one
try:
args = self._get_restart_args(pages, session, override_args)
- subprocess.Popen(args)
+ subprocess.Popen(args) # pylint: disable=consider-using-with
except OSError:
log.destroy.exception("Failed to restart")
return False
diff --git a/scripts/dev/build_release.py b/scripts/dev/build_release.py
index 4961cbdc8..241d27f1d 100755
--- a/scripts/dev/build_release.py
+++ b/scripts/dev/build_release.py
@@ -489,15 +489,15 @@ def build_sdist():
dist_file = os.path.join('dist', dist_files[0])
subprocess.run(['gpg', '--detach-sign', '-a', dist_file], check=True)
- tar = tarfile.open(dist_file)
by_ext = collections.defaultdict(list)
- for tarinfo in tar.getmembers():
- if not tarinfo.isfile():
- continue
- name = os.sep.join(tarinfo.name.split(os.sep)[1:])
- _base, ext = os.path.splitext(name)
- by_ext[ext].append(name)
+ with tarfile.open(dist_file) as tar:
+ for tarinfo in tar.getmembers():
+ if not tarinfo.isfile():
+ continue
+ name = os.sep.join(tarinfo.name.split(os.sep)[1:])
+ _base, ext = os.path.splitext(name)
+ by_ext[ext].append(name)
assert '.pyc' not in by_ext
diff --git a/scripts/dev/update_3rdparty.py b/scripts/dev/update_3rdparty.py
index 88f56b7f3..60b72d110 100755
--- a/scripts/dev/update_3rdparty.py
+++ b/scripts/dev/update_3rdparty.py
@@ -160,11 +160,11 @@ def test_dicts():
print('Testing dictionary {}... '.format(lang.code), end='')
lang_url = urllib.parse.urljoin(dictcli.API_URL, lang.remote_filename)
request = urllib.request.Request(lang_url, method='HEAD')
- response = urllib.request.urlopen(request)
- if response.status == 200:
- print('OK')
- else:
- print('ERROR: {}'.format(response.status))
+ with urllib.request.urlopen(request) as response:
+ if response.status == 200:
+ print('OK')
+ else:
+ print('ERROR: {}'.format(response.status))
def run(nsis=False, ace=False, pdfjs=True, fancy_dmg=False, pdfjs_version=None,
diff --git a/scripts/dictcli.py b/scripts/dictcli.py
index 8cb93fb8a..a937fd31d 100755
--- a/scripts/dictcli.py
+++ b/scripts/dictcli.py
@@ -142,11 +142,11 @@ def parse_entry(entry):
def language_list_from_api():
"""Return a JSON with a list of available languages from Google API."""
listurl = API_URL + '?format=JSON'
- response = urllib.request.urlopen(listurl)
- # A special 5-byte prefix must be stripped from the response content
- # See: https://github.com/google/gitiles/issues/22
- # https://github.com/google/gitiles/issues/82
- json_content = response.read()[5:]
+ with urllib.request.urlopen(listurl) as response:
+ # A special 5-byte prefix must be stripped from the response content
+ # See: https://github.com/google/gitiles/issues/22
+ # https://github.com/google/gitiles/issues/82
+ json_content = response.read()[5:]
entries = json.loads(json_content.decode('utf-8'))['entries']
parsed_entries = [parse_entry(entry) for entry in entries]
return [entry for entry in parsed_entries if entry is not None]
@@ -176,8 +176,8 @@ def available_languages():
def download_dictionary(url, dest):
"""Download a decoded dictionary file."""
- response = urllib.request.urlopen(url)
- decoded = base64.decodebytes(response.read())
+ with urllib.request.urlopen(url) as response:
+ decoded = base64.decodebytes(response.read())
with open(dest, 'bw') as dict_file:
dict_file.write(decoded)
diff --git a/scripts/hostblock_blame.py b/scripts/hostblock_blame.py
index 38acaa58d..b18c62925 100644
--- a/scripts/hostblock_blame.py
+++ b/scripts/hostblock_blame.py
@@ -41,8 +41,8 @@ def main():
for url in configdata.DATA['content.blocking.hosts.lists'].default:
print("checking {}...".format(url))
- raw_file = urllib.request.urlopen(url)
- byte_io = io.BytesIO(raw_file.read())
+ with urllib.request.urlopen(url) as raw_file:
+ byte_io = io.BytesIO(raw_file.read())
f = hostblock.get_fileobj(byte_io)
for line in f:
line = line.decode('utf-8')
diff --git a/tests/end2end/data/brave-adblock/generate.py b/tests/end2end/data/brave-adblock/generate.py
index 7a23a21ab..393cda4e7 100644
--- a/tests/end2end/data/brave-adblock/generate.py
+++ b/tests/end2end/data/brave-adblock/generate.py
@@ -53,9 +53,9 @@ def main():
else:
request = urllib.request.Request(URL)
print(f"Downloading {URL} ...")
- response = urllib.request.urlopen(request)
- assert response.status == 200
- data_str = response.read().decode("utf-8")
+ with urllib.request.urlopen(request) as response:
+ assert response.status == 200
+ data_str = response.read().decode("utf-8")
print(f"Saving to cache file {CACHE_PATH} ...")
CACHE_PATH.write_text(data_str, encoding="utf-8")
data = io.StringIO(data_str)
diff --git a/tests/end2end/fixtures/test_webserver.py b/tests/end2end/fixtures/test_webserver.py
index 3c825e5bc..ed0c32ae5 100644
--- a/tests/end2end/fixtures/test_webserver.py
+++ b/tests/end2end/fixtures/test_webserver.py
@@ -37,7 +37,8 @@ def test_server(server, qtbot, path, content, expected):
with qtbot.wait_signal(server.new_request, timeout=100):
url = 'http://localhost:{}{}'.format(server.port, path)
try:
- response = urllib.request.urlopen(url)
+ with urllib.request.urlopen(url) as response:
+ data = response.read().decode('utf-8')
except urllib.error.HTTPError as e:
# "Though being an exception (a subclass of URLError), an HTTPError
# can also function as a non-exceptional file-like return value
@@ -46,8 +47,6 @@ def test_server(server, qtbot, path, content, expected):
print(e.read().decode('utf-8'))
raise
- data = response.read().decode('utf-8')
-
assert server.get_requests() == [server.ExpectedRequest('GET', path)]
assert (content in data) == expected
diff --git a/tests/unit/utils/test_qtutils.py b/tests/unit/utils/test_qtutils.py
index 2d98feece..d78a132bb 100644
--- a/tests/unit/utils/test_qtutils.py
+++ b/tests/unit/utils/test_qtutils.py
@@ -559,7 +559,8 @@ if test_file is not None:
qiodev.mode = mode
# Create empty TESTFN file because the Python tests try to unlink
# it.after the test.
- open(test_file.TESTFN, 'w', encoding='utf-8').close()
+ with open(test_file.TESTFN, 'w', encoding='utf-8'):
+ pass
return qiodev
class PyAutoFileTests(PyIODeviceTestMixin, test_file.AutoFileTests,