Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

wxGUI: Fixed PTH208 and SIM115 errors in core/ #5016

Merged
merged 3 commits into from
Feb 3, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion gui/wxpython/core/globalvar.py
Original file line number Diff line number Diff line change
@@ -23,6 +23,7 @@
from grass.script.core import get_commands

from core.debug import Debug
from pathlib import Path

# path to python scripts
ETCDIR = os.path.join(os.getenv("GISBASE"), "etc")
@@ -206,7 +207,8 @@ def UpdateGRASSAddOnCommands(eList=None):
if pathList and path not in pathList:
os.environ["PATH"] = path + os.pathsep + os.environ["PATH"]

for fname in os.listdir(path):
for file_path in Path(path).iterdir():
fname = file_path.name
if fname in {"docs", "modules.xml"}:
continue
if grassScripts: # win32
25 changes: 12 additions & 13 deletions gui/wxpython/core/render.py
Original file line number Diff line number Diff line change
@@ -883,25 +883,24 @@ def GetWindow(self):
env["GISDBASE"], env["LOCATION_NAME"], env["MAPSET"], "WIND"
)
try:
windfile = open(filename)
with open(filename) as windfile:
for line in windfile:
line = line.strip()
try:
key, value = line.split(":", 1)
except ValueError as e:
sys.stderr.write(
_("\nERROR: Unable to read WIND file: %s\n") % e
)
return None

self.wind[key.strip()] = value.strip()
except OSError as e:
sys.exit(
_("Error: Unable to open '%(file)s'. Reason: %(ret)s. wxGUI exited.\n")
% {"file": filename, "ret": e}
)

for line in windfile:
line = line.strip()
try:
key, value = line.split(":", 1)
except ValueError as e:
sys.stderr.write(_("\nERROR: Unable to read WIND file: %s\n") % e)
return None

self.wind[key.strip()] = value.strip()

windfile.close()

return self.wind

def AdjustRegion(self):
48 changes: 21 additions & 27 deletions gui/wxpython/core/settings.py
Original file line number Diff line number Diff line change
@@ -29,6 +29,7 @@
from core import globalvar
from core.gcmd import GException, GError
from core.utils import GetSettingsPath, PathJoin, rgb2str
from pathlib import Path


class SettingsJSONEncoder(json.JSONEncoder):
@@ -104,7 +105,8 @@ def __init__(self):
def _generateLocale(self):
"""Generate locales"""
try:
self.locs = os.listdir(os.path.join(os.environ["GISBASE"], "locale"))
locale_path = Path(os.environ["GISBASE"]) / "locale"
self.locs = [p.name for p in locale_path.iterdir() if p.is_dir()]
self.locs.append("en") # GRASS doesn't ship EN po files
self.locs.sort()
# Add a default choice to not override system locale
@@ -941,30 +943,28 @@ def _readLegacyFile(self, settings=None):
settings = self.userSettings

try:
fd = open(self.legacyFilePath)
with open(self.legacyFilePath) as fd:
line = ""
for line in fd:
line = line.rstrip("%s" % os.linesep)
group, key = line.split(self.sep)[0:2]
kv = line.split(self.sep)[2:]
subkeyMaster = None
if len(kv) % 2 != 0: # multiple (e.g. nviz)
subkeyMaster = kv[0]
del kv[0]
idx = 0
while idx < len(kv):
subkey = [subkeyMaster, kv[idx]] if subkeyMaster else kv[idx]
value = kv[idx + 1]
value = self._parseValue(value, read=True)
self.Append(settings, group, key, subkey, value)
idx += 2
except OSError:
sys.stderr.write(
_("Unable to read settings file <%s>\n") % self.legacyFilePath
)
return

try:
line = ""
for line in fd:
line = line.rstrip("%s" % os.linesep)
group, key = line.split(self.sep)[0:2]
kv = line.split(self.sep)[2:]
subkeyMaster = None
if len(kv) % 2 != 0: # multiple (e.g. nviz)
subkeyMaster = kv[0]
del kv[0]
idx = 0
while idx < len(kv):
subkey = [subkeyMaster, kv[idx]] if subkeyMaster else kv[idx]
value = kv[idx + 1]
value = self._parseValue(value, read=True)
self.Append(settings, group, key, subkey, value)
idx += 2
except ValueError as e:
print(
_(
@@ -975,9 +975,6 @@ def _readLegacyFile(self, settings=None):
% {"file": self.legacyFilePath, "detail": e, "line": line},
file=sys.stderr,
)
fd.close()

fd.close()

def SaveToFile(self, settings=None):
"""Save settings to the file"""
@@ -998,10 +995,7 @@ def SaveToFile(self, settings=None):
raise GException(e)
except Exception as e:
raise GException(
_(
"Writing settings to file <%(file)s> failed."
"\n\nDetails: %(detail)s"
)
_("Writing settings to file <%(file)s> failed.\n\nDetails: %(detail)s")
% {"file": self.filePath, "detail": e}
)
return self.filePath
1 change: 0 additions & 1 deletion gui/wxpython/core/testsuite/test_gcmd.py
Original file line number Diff line number Diff line change
@@ -17,7 +17,6 @@ def recv(self):


class Recv_SomeTest(TestCase):

@xfail_windows
def test_decode(self):
"""
5 changes: 1 addition & 4 deletions gui/wxpython/core/toolboxes.py
Original file line number Diff line number Diff line change
@@ -149,10 +149,7 @@ def getMenudataFile(userRootFile, newFile, fallback):
generateNew = True
_debug(
2,
(
"toolboxes.getMenudataFile: only one of the user "
"defined files"
),
("toolboxes.getMenudataFile: only one of the user defined files"),
)
else:
# if newer files -> generate new
50 changes: 24 additions & 26 deletions gui/wxpython/core/utils.py
Original file line number Diff line number Diff line change
@@ -828,30 +828,28 @@ def StoreEnvVariable(key, value=None, envFile=None):
lineSkipped = []
if os.path.exists(envFile):
try:
fd = open(envFile)
with open(envFile) as fd:
for line in fd:
line = line.rstrip(os.linesep)
try:
k, v = (x.strip() for x in line.split(" ", 1)[1].split("=", 1))
except Exception as e:
sys.stderr.write(
_("%s: line skipped - unable to parse '%s'\nReason: %s\n")
% (envFile, line, e)
)
lineSkipped.append(line)
continue
if k in environ:
sys.stderr.write(_("Duplicated key: %s\n") % k)
environ[k] = v
except OSError as error:
sys.stderr.write(
_("Unable to open file '{name}': {error}\n").format(
name=envFile, error=error
)
)
return
for line in fd:
line = line.rstrip(os.linesep)
try:
k, v = (x.strip() for x in line.split(" ", 1)[1].split("=", 1))
except Exception as e:
sys.stderr.write(
_("%s: line skipped - unable to parse '%s'\nReason: %s\n")
% (envFile, line, e)
)
lineSkipped.append(line)
continue
if k in environ:
sys.stderr.write(_("Duplicated key: %s\n") % k)
environ[k] = v

fd.close()

# update environmental variables
if value is None:
@@ -861,22 +859,22 @@ def StoreEnvVariable(key, value=None, envFile=None):

# write update env file
try:
fd = open(envFile, "w")
with open(envFile, "w") as fd:
expCmd = "set" if windows else "export"

fd.writelines(
"%s %s=%s\n" % (expCmd, key, value) for key, value in environ.items()
)

# write also skipped lines
fd.writelines(line + os.linesep for line in lineSkipped)
except OSError as error:
sys.stderr.write(
_("Unable to create file '{name}': {error}\n").format(
name=envFile, error=error
)
)
return
expCmd = "set" if windows else "export"

fd.writelines("%s %s=%s\n" % (expCmd, key, value) for key, value in environ.items())

# write also skipped lines
fd.writelines(line + os.linesep for line in lineSkipped)

fd.close()


def SetAddOnPath(addonPath=None, key="PATH"):
13 changes: 5 additions & 8 deletions gui/wxpython/core/workspace.py
Original file line number Diff line number Diff line change
@@ -1730,7 +1730,11 @@ def read(self, parent):
:return: list of map layers
"""
try:
file = open(self.filename)
with open(self.filename) as file: # Changed to context manager
line_id = 1
for line in file:
self.process_line(line.rstrip("\n"), line_id)
line_id += 1
except OSError:
wx.MessageBox(
parent=parent,
@@ -1740,13 +1744,6 @@ def read(self, parent):
)
return []

line_id = 1
for line in file:
self.process_line(line.rstrip("\n"), line_id)
line_id += 1

file.close()

if self.num_error > 0:
wx.MessageBox(
parent=parent,
5 changes: 0 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -268,11 +268,6 @@ ignore = [
# Other ignores:
"**.py" = ["PYI066"]
"*/testsuite/**.py" = ["PT009", "PT027"]
"gui/wxpython/core/globalvar.py" = ["PTH208"]
"gui/wxpython/core/render.py" = ["SIM115"]
"gui/wxpython/core/settings.py" = ["PTH208", "SIM115"]
"gui/wxpython/core/utils.py" = ["SIM115"]
"gui/wxpython/core/workspace.py" = ["SIM115"]
"gui/wxpython/datacatalog/catalog.py" = ["PTH208"]
"gui/wxpython/dbmgr/base.py" = ["SIM115"]
"gui/wxpython/gcp/manager.py" = ["PTH208"]