Skip to content

Commit

Permalink
style: Fix read-whole-file (FURB101) and write-whole-file (FURB103) (O…
Browse files Browse the repository at this point in the history
…SGeo#4047)

* style: Fix read-whole-file (FURB101)

Ruff rule: https://docs.astral.sh/ruff/rules/read-whole-file/

* style: Extract repeated config_directory variable in generate_release_notes

* style: Fix write-whole-file (FURB103)

Ruff rule: https://docs.astral.sh/ruff/rules/write-whole-file/
  • Loading branch information
echoix authored Jul 13, 2024
1 parent 98222a2 commit 7695805
Show file tree
Hide file tree
Showing 31 changed files with 175 additions and 200 deletions.
5 changes: 3 additions & 2 deletions display/d.text/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# Author: Owen Smith - Rewritten from test.pl by Huidae Cho
# Run: d.mon start=wx0 && ./test.py | d.text at=0,100
import math
from pathlib import Path
import re

# Quiet black syntax checking for fonts and colors to keep the code printed to
Expand Down Expand Up @@ -66,8 +67,8 @@ def text(in_text):
color("gray")
rc(1, 1)

with open(__file__) as f:
src = f.read()

src = Path(__file__).read_text()

print(
".L 0\n"
Expand Down
8 changes: 4 additions & 4 deletions gui/wxpython/core/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"""

import os
from pathlib import Path
import sys
import glob
import math
Expand Down Expand Up @@ -725,10 +726,9 @@ def OnRenderDone(self, env):
continue

if os.path.isfile(layer._legrow) and not layer.hidden:
with open(layer._legrow) as infile:
line = infile.read()
outfile.write(line)
new_legend.append(line)
line = Path(layer._legrow).read_text()
outfile.write(line)
new_legend.append(line)

self._rendering = False
if wx.IsBusy():
Expand Down
4 changes: 2 additions & 2 deletions gui/wxpython/core/toolboxes.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"""

import os
from pathlib import Path
import sys
import copy
import shutil
Expand Down Expand Up @@ -846,8 +847,7 @@ def module_test():
return 0

menudataFile = "data/test_toolboxes_menudata_ref.xml"
with open(menudataFile) as correctMenudata:
correct = str(correctMenudata.read())
correct = str(Path(menudataFile).read_text())

import difflib

Expand Down
9 changes: 4 additions & 5 deletions gui/wxpython/gui_core/pyedit.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
:authors: Martin Landa
"""

from pathlib import Path
import sys
import os
import stat
Expand Down Expand Up @@ -300,8 +301,7 @@ def _openFile(self, file_path):
:return str or None: file content or None
"""
try:
with open(file_path, "r") as f:
return f.read()
return Path(file_path).read_text()
except PermissionError:
GError(
message=_(
Expand All @@ -327,9 +327,8 @@ def _writeFile(self, file_path, content, additional_err_message=""):
:return None or True: file written or None
"""
try:
with open(file_path, "w") as f:
f.write(content)
return True
Path(file_path).write_text(content)
return True
except PermissionError:
GError(
message=_(
Expand Down
6 changes: 3 additions & 3 deletions man/build_manual_gallery.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#############################################################################

import os
from pathlib import Path
import sys
import fnmatch
import re
Expand Down Expand Up @@ -97,9 +98,8 @@ def img_in_html(filename, imagename):
# for some reason, calling search just once is much faster
# than calling it on every line (time is spent in _compile)
pattern = re.compile("<img .*src=.{0}.*>".format(imagename))
with open(filename) as file:
if re.search(pattern, file.read()):
return True
if re.search(pattern, Path(filename).read_text()):
return True
return False


Expand Down
2 changes: 0 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,6 @@ ignore = [
"FBT001", # boolean-type-hint-positional-argument
"FBT002", # boolean-default-value-positional-argument
"FBT003", # boolean-positional-value-in-call
"FURB101", # read-whole-file
"FURB103", # write-whole-file.
"FURB118", # reimplemented-operator
"FURB152", # math-constant
"FURB154", # repeated-global
Expand Down
7 changes: 3 additions & 4 deletions python/grass/benchmark/results.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

import copy
import json
from pathlib import Path
from types import SimpleNamespace


Expand Down Expand Up @@ -48,8 +49,7 @@ def save_results_to_file(results, filename):
See :func:`save_results` for details.
"""
text = save_results(results)
with open(filename, "w", encoding="utf-8") as file:
file.write(text)
Path(filename).write_text(text, encoding="utf-8")


def load_results(data):
Expand All @@ -67,8 +67,7 @@ def load_results_from_file(filename):
See :func:`load_results` for details.
"""
with open(filename, "r", encoding="utf-8") as file:
return load_results(file.read())
return load_results(Path(filename).read_text(encoding="utf-8"))


def join_results(results, prefixes=None, select=None, prefixes_as_labels=False):
Expand Down
39 changes: 18 additions & 21 deletions python/grass/grassdb/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,27 +103,24 @@ def _read_from_JSON(history_path):
"""
content_list = []
try:
with open(
history_path, encoding="utf-8", mode="r", errors="replace"
) as file_history:
content = file_history.read()
if content:
try:
history_entries = json.loads(content)
except ValueError as ve:
raise ValueError(
_("Error decoding content of JSON history file {}").format(
history_path
)
) from ve
# Process the content as a list of dictionaries
content_list = [
{
"command": entry["command"],
"command_info": entry["command_info"],
}
for entry in history_entries
]
content = Path(history_path).read_text(encoding="utf-8", errors="replace")
if content:
try:
history_entries = json.loads(content)
except ValueError as ve:
raise ValueError(
_("Error decoding content of JSON history file {}").format(
history_path
)
) from ve
# Process the content as a list of dictionaries
content_list = [
{
"command": entry["command"],
"command_info": entry["command_info"],
}
for entry in history_entries
]
except OSError as e:
raise OSError(
_("Unable to read from JSON history file {}").format(history_path)
Expand Down
33 changes: 15 additions & 18 deletions python/grass/gunittest/invoker.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import collections
import os
from pathlib import Path
import shutil
import subprocess
import sys
Expand Down Expand Up @@ -39,8 +40,7 @@
# TODO: this might be more extend then update
def update_keyval_file(filename, module, returncode):
if os.path.exists(filename):
with open(filename, "r") as keyval_file:
keyval = text_to_keyvalue(keyval_file.read(), sep="=")
keyval = text_to_keyvalue(Path(filename).read_text(), sep="=")
else:
keyval = {}

Expand All @@ -62,8 +62,7 @@ def update_keyval_file(filename, module, returncode):
keyval["returncode"] = returncode
keyval["test_file_authors"] = test_file_authors

with open(filename, "w") as keyval_file:
keyval_file.write(keyvalue_to_text(keyval))
Path(filename).write_text(keyvalue_to_text(keyval))
return keyval


Expand Down Expand Up @@ -243,8 +242,7 @@ def try_decode(data, encodings):
stdout = try_decode(stdout, encodings=encodings)
stderr = try_decode(stderr, encodings=encodings)

with open(stdout_path, "w") as stdout_file:
stdout_file.write(stdout)
Path(stdout_path).write_text(stdout)
with open(stderr_path, "w") as stderr_file:
if type(stderr) == "bytes":
stderr_file.write(decode(stderr))
Expand Down Expand Up @@ -337,18 +335,17 @@ def run_in_location(self, gisdbase, location, location_type, results_dir, exclud

# TODO: move this to some (new?) reporter
# TODO: add basic summary of linked files so that the page is not empty
with open(os.path.join(results_dir, "index.html"), "w") as main_index:
main_index.write(
"<html><body>"
"<h1>Tests for &lt;{location}&gt;"
" using &lt;{type}&gt; type tests</h1>"
"<ul>"
'<li><a href="testsuites.html">Results by testsuites</a>'
" (testsuite directories)</li>"
'<li><a href="testfiles.html">Results by test files</a></li>'
"<ul>"
"</body></html>".format(location=location, type=location_type)
)
Path(os.path.join(results_dir, "index.html")).write_text(
"<html><body>"
"<h1>Tests for &lt;{location}&gt;"
" using &lt;{type}&gt; type tests</h1>"
"<ul>"
'<li><a href="testsuites.html">Results by testsuites</a>'
" (testsuite directories)</li>"
'<li><a href="testfiles.html">Results by test files</a></li>'
"<ul>"
"</body></html>".format(location=location, type=location_type)
)

testsuite_dir_reporter = TestsuiteDirReporter(
main_page_name="testsuites.html",
Expand Down
12 changes: 5 additions & 7 deletions python/grass/gunittest/reporters.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import os
import datetime
from pathlib import Path
from xml.sax import saxutils
import xml.etree.ElementTree as et
import subprocess
Expand Down Expand Up @@ -906,9 +907,8 @@ def finish(self):
summary[key] = value

summary_filename = os.path.join(self.result_dir, "test_keyvalue_result.txt")
with open(summary_filename, "w") as summary_file:
text = keyvalue_to_text(summary, sep="=", vsep="\n", isep=",")
summary_file.write(text)
text = keyvalue_to_text(summary, sep="=", vsep="\n", isep=",")
Path(summary_filename).write_text(text)

def end_file_test(
self, module, cwd, returncode, stdout, stderr, test_summary, timed_out=None
Expand Down Expand Up @@ -1025,8 +1025,7 @@ def end_file_test(
width = 72
self._stream.write(width * "=")
self._stream.write("\n")
with open(stderr) as text:
self._stream.write(text.read())
self._stream.write(Path(stderr).read_text())
self._stream.write(width * "=")
self._stream.write("\n")
self._stream.write(f"FAILED {module.file_path}")
Expand Down Expand Up @@ -1116,8 +1115,7 @@ def report_for_dir(self, root, directory, test_files):
root, directory, test_file_name, "test_keyvalue_result.txt"
)
# if os.path.exists(summary_filename):
with open(summary_filename, "r") as keyval_file:
summary = text_to_keyvalue(keyval_file.read(), sep="=")
summary = text_to_keyvalue(Path(summary_filename).read_text(), sep="=")
# else:
# TODO: write else here
# summary = None
Expand Down
12 changes: 6 additions & 6 deletions python/grass/gunittest/testsuite/test_assertions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"""

import os
from pathlib import Path

import grass.script.core as gcore
from grass.pygrass.modules import Module
Expand Down Expand Up @@ -348,20 +349,19 @@ def setUpClass(cls):
open(cls.emtpy_file, "w").close()
cls.file_with_md5 = cls.__name__ + "_this_is_a_file_with_known_md5"
file_content = "Content of the file with known MD5.\n"
with open(cls.file_with_md5, "w") as f:
f.write(file_content)
Path(cls.file_with_md5).write_text(file_content)
# MD5 sum created using:
# echo 'Content of the file with known MD5.' > some_file.txt
# md5sum some_file.txt
cls.file_md5 = "807bba4ffac4bb351bc3f27853009949"

cls.file_with_same_content = cls.__name__ + "_file_with_same_content"
with open(cls.file_with_same_content, "w") as f:
f.write(file_content)
Path(cls.file_with_same_content).write_text(file_content)

cls.file_with_different_content = cls.__name__ + "_file_with_different_content"
with open(cls.file_with_different_content, "w") as f:
f.write(file_content + " Something else here.")
Path(cls.file_with_different_content).write_text(
file_content + " Something else here."
)

@classmethod
def tearDownClass(cls):
Expand Down
4 changes: 2 additions & 2 deletions python/grass/jupyter/baseseriesmap.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Base class for SeriesMap and TimeSeriesMap"""

import os
from pathlib import Path
import tempfile
import weakref
import shutil
Expand Down Expand Up @@ -177,8 +178,7 @@ def change_slider(change):
# Display image associated with datetime
def change_image(index):
filename = self._base_filename_dict[index]
with open(filename, "rb") as rfile:
out_img.value = rfile.read()
out_img.value = Path(filename).read_bytes()

widgets.interactive_output(change_image, {"index": slider})

Expand Down
6 changes: 3 additions & 3 deletions python/grass/jupyter/interactivemap.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

import base64
import json
from pathlib import Path
from .reprojection_renderer import ReprojectionRenderer


Expand Down Expand Up @@ -119,9 +120,8 @@ def add_to(self, interactive_map):
# ImageOverlays don't work well with local files,
# they need relative address and behavior differs
# for notebooks and jupyterlab
with open(self._filename, "rb") as file:
data = base64.b64encode(file.read()).decode("ascii")
url = "data:image/png;base64," + data
data = base64.b64encode(Path(self._filename).read_bytes()).decode("ascii")
url = "data:image/png;base64," + data
image = ipyleaflet.ImageOverlay(
url=url, bounds=self._bounds, name=self._title, **self._layer_kwargs
)
Expand Down
14 changes: 7 additions & 7 deletions python/grass/pygrass/raster/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import ctypes
from operator import itemgetter
from pathlib import Path

import grass.lib.raster as libraster
from grass.exceptions import ImplementationError
Expand Down Expand Up @@ -325,13 +326,12 @@ def write_rules(self, filename, sep=":"):
:param str filename: the name of file with categories rules
:param str sep: the separator used to divide values and category
"""
with open(filename, "w") as f:
cats = []
for cat in self.__iter__():
if cat[-1] is None:
cat = cat[:-1]
cats.append(sep.join([str(i) for i in cat]))
f.write("\n".join(cats))
cats = []
for cat in self.__iter__():
if cat[-1] is None:
cat = cat[:-1]
cats.append(sep.join([str(i) for i in cat]))
Path(filename).write_text("\n".join(cats))

def sort(self):
libraster.Rast_sort_cats(ctypes.byref(self.c_cats))
Expand Down
Loading

0 comments on commit 7695805

Please sign in to comment.