From 263f2201f8838d4577aebeab71ee5bc536ad69df Mon Sep 17 00:00:00 2001 From: Saeed Rasooli Date: Sat, 10 Feb 2024 20:21:20 +0330 Subject: [PATCH] enable and fix more ruff errors --- distro/base/install.py | 2 +- .../pray_times_files/pray_times_backend.py | 20 +++++++++---------- pyproject.toml | 10 +++++++--- scal3/account/google.py | 2 +- scal3/event_lib.py | 10 +++++----- scal3/format_time.py | 16 +++++++-------- scal3/ics.py | 3 ++- scal3/plugin_api.py | 4 ++-- scal3/plugin_man.py | 8 +++++--- scal3/s_object.py | 2 +- scal3/startup.py | 4 ++-- scal3/ui.py | 2 +- scal3/ui_gtk/about.py | 2 +- scal3/ui_gtk/arch-enable-locale.py | 3 ++- scal3/ui_gtk/event/import_event.py | 16 +++++++-------- scal3/ui_gtk/hijri.py | 3 ++- scal3/ui_gtk/mywidgets/clock.py | 12 +++++------ scal3/ui_gtk/mywidgets/num_ranges_entry.py | 2 +- scal3/ui_gtk/wizard_demo.py | 16 +++++++-------- scripts/bson_to_json.py | 6 ++++-- scripts/compact_json.py | 6 ++++-- scripts/json_to_bson.py | 6 ++++-- scripts/pretty_json.py | 6 ++++-- scripts/py2json.py | 6 ++++-- scripts/version.py | 12 +++++------ tools/kalzium-elements-discovery.py | 3 ++- tools/wikipedia-fa-events/2-parse.py | 5 +++-- .../wikipedia-fa-events/3-starcal2-import.py | 2 +- 28 files changed, 105 insertions(+), 84 deletions(-) diff --git a/distro/base/install.py b/distro/base/install.py index 6f75a28b8..ab7a13274 100755 --- a/distro/base/install.py +++ b/distro/base/install.py @@ -172,7 +172,7 @@ def main(): prefix = options["prefix"].rstrip("/") elif installType == "for-pkg": prefix = "/usr" - elif installType == "portable": + elif installType == "portable": # noqa: SIM114 prefix = "/usr/local" elif installType == "system": prefix = "/usr/local" diff --git a/plugins/pray_times_files/pray_times_backend.py b/plugins/pray_times_files/pray_times_backend.py index bae37506c..5a4ef3de9 100644 --- a/plugins/pray_times_files/pray_times_backend.py +++ b/plugins/pray_times_files/pray_times_backend.py @@ -260,25 +260,25 @@ def getTimesByJd(self, jd, utcOffset): self.jDate = jd - 0.5 - self.lng / (15 * 24) return self.computeTimes() - def getFormattedTime(self, tm, format=None): - """Convert float time to the given format (see timeFormats).""" + def getFormattedTime(self, tm, timeFormat=None): + """Convert float time to the given timeFormat (see timeFormats).""" assert isinstance(tm, float) - if not format: - format = self.timeFormat - if format == "float": + if not timeFormat: + timeFormat = self.timeFormat + if timeFormat == "float": return tm tm = fixHour(tm + 0.5 / 60) # add 0.5 minutes to round hours = floor(tm) minutes = floor((tm - hours) * 60) - if format == "24h": + if timeFormat == "24h": return f"{hours:d}:{minutes:02d}" - if format == "12h": + if timeFormat == "12h": ampm = tr("AM") if hours < 12 else tr("PM") return f"{(hours-1)%12+1:d}:{minutes:02d} {ampm}" - if format == "12hNS": + if timeFormat == "12hNS": return f"{(hours-1)%12+1:d}:{minutes:02d}" - raise ValueError(f"bad time format '{format}'") + raise ValueError(f"bad time format '{timeFormat}'") def midDay(self, tm): """Compute mid-day time.""" @@ -453,7 +453,7 @@ def computeTimes(self): # times = self.tuneTimes(times) # FIXME # for key in times: - # times[key] = self.getFormattedTime(times[key], format) + # times[key] = self.getFormattedTime(times[key], timeFormat) times["timezone"] = f"GMT{self.utcOffset:+.1f}" # ^^^ utcOffset is not timeZone FIXME diff --git a/pyproject.toml b/pyproject.toml index c1b7853b0..70e8cd2ef 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -15,7 +15,6 @@ select = [ "PGH", # pygrep-hooks "PIE", # flake8-pie "RET", # flake8-return - # "SIM", # flake8-simplify "T10", # flake8-debugger "TCH", # flake8-type-checking, not done for plugins "TID", # flake8-tidy-imports @@ -23,11 +22,13 @@ select = [ "UP", # pyupgrade "W", # pycodestyle Warning "YTT", # flake8-2020 - + "A", # flake8-builtins + "SIM", # flake8-simplify + # "ARG", # flake8-unused-arguments: Unused function argument: 571 remaining # "C90", # mccabe: C901: {name} is too complex ({complexity}) # "ANN", # flake8-annotationsq # "N", # pep8-naming - "ARG", # flake8-unused-arguments: ARG001 Unused function argument + # "ARG", # flake8-unused-arguments: ARG001 Unused function argument # "A", # flake8-builtins # "S", # flake8-bandit ] @@ -80,6 +81,7 @@ ignore = [ # Allow autofix for all enabled rules (when `--fix`) is provided. fixable = [ + # "SIM", "F401", # "E", "F", "W", "RET", @@ -108,6 +110,8 @@ unfixable = [] # Exclude a variety of commonly ignored directories. exclude = [ + "scal3/import_config_2to3.py", + "scal3/ui_gtk/import_config_2to3.py", "libs", # "setup.py", ] diff --git a/scal3/account/google.py b/scal3/account/google.py index 6e7a28a13..fc6b625b5 100644 --- a/scal3/account/google.py +++ b/scal3/account/google.py @@ -211,7 +211,7 @@ def do_GET(s): b"", ) - def log_message(self, format, *args): + def log_message(self, msgFormat, *args): """Do not log messages to stdout while running as command line program.""" diff --git a/scal3/event_lib.py b/scal3/event_lib.py index dcf655c72..f6f101925 100644 --- a/scal3/event_lib.py +++ b/scal3/event_lib.py @@ -2065,11 +2065,11 @@ def iconAbsToRelativelnData(data): iconDir, iconName = split(icon) if iconName == "obituary.png": iconName = "green_clover.svg" - if iconDir == "event": - icon = iconName - elif iconDir == join(svgDir, "event"): - icon = iconName - elif iconDir == join(pixDir, "event"): + elif iconDir in ( + "event", + join(svgDir, "event"), + join(pixDir, "event"), + ): icon = iconName data["icon"] = icon diff --git a/scal3/format_time.py b/scal3/format_time.py index 17dbe41c5..1af9e5084 100644 --- a/scal3/format_time.py +++ b/scal3/format_time.py @@ -52,16 +52,16 @@ def isow(jd): return (jd - iso_to_jd(year, 1, 1)) // 7 + 1 -def compileTmFormat(format, hasTime=True) -> CompiledTimeFormat: - # format: "Today: %Y/%m/%d" - # pyFmt: "Today: %s/%s/%s" - # funcs: (get_y, get_m, get_d) +def compileTmFormat(fmt, hasTime=True) -> CompiledTimeFormat: + # fmt: "Today: %Y/%m/%d" + # pyFmt: "Today: %s/%s/%s" + # funcs: (get_y, get_m, get_d) pyFmt = "" funcs = [] - n = len(format) + n = len(fmt) i = 0 while i < n: - c0 = format[i] + c0 = fmt[i] if c0 != "%": pyFmt += c0 i += 1 @@ -69,7 +69,7 @@ def compileTmFormat(format, hasTime=True) -> CompiledTimeFormat: if i == n - 1: pyFmt += c0 break - c1 = format[i + 1] + c1 = fmt[i + 1] if c1 == "%": pyFmt += "%" i += 2 @@ -319,7 +319,7 @@ def tz(cell, _calType, _tm): continue # if c1 == "Z": # alphabetic time zone abbreviation (e.g., EDT) if c1 == ":": - c2 = format[i + 2] + c2 = fmt[i + 2] if c2 == "z": # %:z def tz(cell, _calType, _tm): diff --git a/scal3/ics.py b/scal3/ics.py index 50ea687bb..0562575c6 100644 --- a/scal3/ics.py +++ b/scal3/ics.py @@ -155,4 +155,5 @@ def convertBuiltinTextPlugToIcs( icsText += "END:VCALENDAR\n" fname = split(plug.fpath)[-1] fname = splitext(fname)[0] + f"{namePostfix}.ics" - open(fname, "w").write(icsText) + with open(fname, "w") as _file: + _file.write(icsText) diff --git a/scal3/plugin_api.py b/scal3/plugin_api.py index 6c9a1861c..81289b045 100644 --- a/scal3/plugin_api.py +++ b/scal3/plugin_api.py @@ -30,7 +30,7 @@ class PluginError(Exception): pass -def get(moduleName, attr, default=None, absolute=False): +def getAttr(moduleName, attr, default=None, absolute=False): if not absolute: moduleName = "scal3." + moduleName # module = __import__(moduleName, fromlist=["__plugin_api_get__", attr]) @@ -45,7 +45,7 @@ def get(moduleName, attr, default=None, absolute=False): return getattr(module, attr, default) -def set(moduleName, attr, value, absolute=False): +def setAttr(moduleName, attr, value, absolute=False): if not absolute: moduleName = "scal3." + moduleName # module = __import__(moduleName, fromlist=["__plugin_api_set__", attr]) diff --git a/scal3/plugin_man.py b/scal3/plugin_man.py index dc7b4c221..64676701f 100644 --- a/scal3/plugin_man.py +++ b/scal3/plugin_man.py @@ -211,7 +211,8 @@ def exportToIcs(self, fileName, startJd, endJd): + "\n" ) icsText += "END:VCALENDAR\n" - open(fileName, "w", encoding="utf-8").write(icsText) + with open(fileName, "w", encoding="utf-8") as _file: + _file.write(icsText) class BaseJsonPlugin(BasePlugin, JsonSObj): @@ -405,7 +406,7 @@ def exportToIcs(self, fileName, startJd, endJd): for jd in range(startJd, endJd): isHoliday = False - for calType in self.holidays.keys(): + for calType in self.holidays: myear, mmonth, mday = jd_to(jd, calType) if (mmonth, mday) in self.holidays[calType]: isHoliday = True @@ -437,7 +438,8 @@ def exportToIcs(self, fileName, startJd, endJd): + "\n" ) icsText += "END:VCALENDAR\n" - open(fileName, "w", encoding="utf-8").write(icsText) + with open(fileName, "w", encoding="utf-8") as _file: + _file.write(icsText) # def getJdList(self, startJd, endJd): diff --git a/scal3/s_object.py b/scal3/s_object.py index 9074af553..d6eb759af 100644 --- a/scal3/s_object.py +++ b/scal3/s_object.py @@ -66,7 +66,7 @@ def open(self, fpath, mode="r", encoding=None): fpath = self.abspath(fpath) if mode == "r" and encoding is None: encoding = "utf-8" - return open(fpath, mode=mode, encoding=encoding) + return open(fpath, mode=mode, encoding=encoding) # noqa: SIM115 def listdir(self, dpath): if isabs(dpath): diff --git a/scal3/startup.py b/scal3/startup.py index c7f86c440..b616eed2b 100644 --- a/scal3/startup.py +++ b/scal3/startup.py @@ -42,12 +42,12 @@ def addStartup(): # does it work with single quotes too?? makeDir(comDeskDir) try: - fp = open(comDesk, "w") + with open(comDesk, "w") as _file: + _file.write(text) except Exception: log.exception("") return False else: - fp.write(text) return True elif osName == "mac": # FIXME pass diff --git a/scal3/ui.py b/scal3/ui.py index bff41380c..6d8994170 100644 --- a/scal3/ui.py +++ b/scal3/ui.py @@ -368,7 +368,7 @@ def formatIsValid(fmt: "list[int]"): def checkNeedRestart() -> bool: - for key in needRestartPref.keys(): + for key in needRestartPref: if needRestartPref[key] != evalParam(key): log.info( f"checkNeedRestart: {key!r}, " diff --git a/scal3/ui_gtk/about.py b/scal3/ui_gtk/about.py index 04e711772..ea16477a3 100644 --- a/scal3/ui_gtk/about.py +++ b/scal3/ui_gtk/about.py @@ -11,7 +11,7 @@ def __init__( title: str = "", authors: "list[str] | None" = None, comments: str = "", - license: str = "", + license: str = "", # noqa: A002 website: str = "", logo: "GdkPixbuf.Pixbuf" = None, **kwargs, diff --git a/scal3/ui_gtk/arch-enable-locale.py b/scal3/ui_gtk/arch-enable-locale.py index 2c3f75323..c154cd027 100755 --- a/scal3/ui_gtk/arch-enable-locale.py +++ b/scal3/ui_gtk/arch-enable-locale.py @@ -46,7 +46,8 @@ def errorExit(text, parent=None): if line.lower().startswith("#" + localeName): lines[i] = line[1:] os.rename(localeGen, f"{localeGen}.{now()}") - open(localeGen, "w").write("\n".join(lines)) + with open(localeGen, "w") as _file: + _file.write("\n".join(lines)) exit_code = subprocess.call("/usr/sbin/locale-gen") log.info(f'enabling locale "{localeName}" done') break diff --git a/scal3/ui_gtk/event/import_event.py b/scal3/ui_gtk/event/import_event.py index 44dd49d83..b8771207d 100644 --- a/scal3/ui_gtk/event/import_event.py +++ b/scal3/ui_gtk/event/import_event.py @@ -80,12 +80,12 @@ def onNextClick(self, obj): if not fpath: return if self.radioJson.get_active(): - format = "json" + format_ = "json" # elif self.radioIcs.get_active(): - # format = "ics" + # format_ = "ics" else: return - self.win.showStep(1, format, fpath) + self.win.showStep(1, format_, fpath) class SecondStep(gtk.Box): desc = "" @@ -122,16 +122,16 @@ def restoreStdOutErr(self): sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ - def run(self, format, fpath): + def run(self, format_, fpath): self.redirectStdOutErr() - self.win.waitingDo(self._runAndCleanup, format, fpath) + self.win.waitingDo(self._runAndCleanup, format_, fpath) - def _runAndCleanup(self, format, fpath): + def _runAndCleanup(self, format_, fpath): try: - if format == "json": + if format_ == "json": self._runJson(fpath) else: - raise ValueError(f"invalid format {format!r}") + raise ValueError(f"invalid format {format_!r}") finally: self.restoreStdOutErr() diff --git a/scal3/ui_gtk/hijri.py b/scal3/ui_gtk/hijri.py index 7b297a767..b7a469f04 100644 --- a/scal3/ui_gtk/hijri.py +++ b/scal3/ui_gtk/hijri.py @@ -356,7 +356,8 @@ def __init__(self, **kwargs): def onResponse(self, dialog, response_id): if self.noShowCheckb.get_active(): - open(hijri.monthDbExpiredIgnoreFile, "w").write("") + with open(hijri.monthDbExpiredIgnoreFile, "w") as _file: + _file.write("") self.destroy() return True diff --git a/scal3/ui_gtk/mywidgets/clock.py b/scal3/ui_gtk/mywidgets/clock.py index f176b2208..740b1a58b 100644 --- a/scal3/ui_gtk/mywidgets/clock.py +++ b/scal3/ui_gtk/mywidgets/clock.py @@ -67,9 +67,9 @@ def stop(self): class FClockLabel(gtk.Label): - def __init__(self, format="%T", local=True, selectable=False): + def __init__(self, clockFormat="%T", local=True, selectable=False): """ - format is a string that used in strftime(), it can contains markup + clockFormat is a string that used in strftime(), it can contains markup that apears in GtkLabel for example format can be "%T" local is bool. if True, use Local time. and if False, use GMT time. selectable is bool that passes to GtkLabel. @@ -78,7 +78,7 @@ def __init__(self, format="%T", local=True, selectable=False): self.set_use_markup(True) self.set_selectable(selectable) self.set_direction(gtk.TextDirection.LTR) - self.format = format + self.format = clockFormat self.local = local self.running = False # self.connect("button-press-event", self.onButtonPress) @@ -101,16 +101,16 @@ def stop(self): class FClockWidget(gtk.DrawingArea): ## Time is in Local - def __init__(self, format="%T", selectable=False): + def __init__(self, clockFormat="%T", selectable=False): """ - format is a string that used in strftime(), it can contains markup + clockFormat is a string that used in strftime(), it can contains markup that apears in GtkLabel for example format can be "%T" local is bool. if True, use Local time. and if False, use GMT time. selectable is bool that passes to GtkLabel. """ gtk.DrawingArea.__init__(self) self.set_direction(gtk.TextDirection.LTR) - self.format = format + self.format = clockFormat self.text = "" self.running = False self.connect("draw", self.onDraw) diff --git a/scal3/ui_gtk/mywidgets/num_ranges_entry.py b/scal3/ui_gtk/mywidgets/num_ranges_entry.py index d7e31d141..3672c8ced 100644 --- a/scal3/ui_gtk/mywidgets/num_ranges_entry.py +++ b/scal3/ui_gtk/mywidgets/num_ranges_entry.py @@ -138,7 +138,7 @@ def onKeyPress(self, obj: gtk.Widget, gevent: gdk.EventKey): self.numPlus(self.page_inc) elif kname == "page_down": self.numPlus(-self.page_inc) - elif kname == "left": + elif kname == "left": # noqa: SIM114 return False # FIXME elif kname == "right": return False # FIXME diff --git a/scal3/ui_gtk/wizard_demo.py b/scal3/ui_gtk/wizard_demo.py index 03e94aac0..630bddc89 100644 --- a/scal3/ui_gtk/wizard_demo.py +++ b/scal3/ui_gtk/wizard_demo.py @@ -71,10 +71,10 @@ def onCancelClick(self, obj): def onNextClick(self, obj): fpath = self.fcb.get_filename() - format = None + format_ = None if self.radioJson.get_active(): - format = "json" - self.win.showStep(1, format, fpath) + format_ = "json" + self.win.showStep(1, format_, fpath) class SecondStep(gtk.Box): desc = "" @@ -93,14 +93,14 @@ def __init__(self, win): #### self.show_all() - def run(self, format, fpath): - self.win.waitingDo(self._runAndCleanup, format, fpath) + def run(self, format_, fpath): + self.win.waitingDo(self._runAndCleanup, format_, fpath) - def _runAndCleanup(self, format, fpath): - if format == "json": + def _runAndCleanup(self, format_, fpath): + if format_ == "json": self._runJson(fpath) else: - raise ValueError(f"invalid format {format!r}") + raise ValueError(f"invalid format {format_!r}") def _runJson(self, fpath): print(f"_runAndCleanup: {fpath=}") diff --git a/scripts/bson_to_json.py b/scripts/bson_to_json.py index 70ef17c4d..c7bf1246d 100755 --- a/scripts/bson_to_json.py +++ b/scripts/bson_to_json.py @@ -11,6 +11,8 @@ for fname_json in sys.argv[1:]: fname, ext = splitext(fname_json) - bson_s = open(fname_json, "rb").read() + with open(fname_json, "rb") as _file: + bson_s = _file.read() data = bson.loads(bson_s) - open(fname + ".json", "w").write(json.dumps(data)) + with open(fname + ".json", "w") as _file: + _file.write(json.dumps(data)) diff --git a/scripts/compact_json.py b/scripts/compact_json.py index 25d0081f9..d4d8a8e59 100755 --- a/scripts/compact_json.py +++ b/scripts/compact_json.py @@ -3,6 +3,8 @@ import sys for fname in sys.argv[1:]: - data = json.loads(open(fname).read()) + with open(fname) as _file: + data = json.loads(_file.read()) jstr = json.dumps(data, sort_keys=True, separators=(",", ":")) - open(fname, "w").write(jstr) + with open(fname, "w") as _file: + _file.write(jstr) diff --git a/scripts/json_to_bson.py b/scripts/json_to_bson.py index 527c6b429..ca04e4627 100755 --- a/scripts/json_to_bson.py +++ b/scripts/json_to_bson.py @@ -11,6 +11,8 @@ for fname_json in sys.argv[1:]: fname, ext = splitext(fname_json) - json_s = open(fname_json).read() + with open(fname_json) as _file: + json_s = _file.read() data = json.loads(json_s) - open(fname + ".bson", "wb").write(bytes(bson.dumps(data))) + with open(fname + ".bson", "wb") as _file: + _file.write(bytes(bson.dumps(data))) diff --git a/scripts/pretty_json.py b/scripts/pretty_json.py index 47b869130..4ebf59607 100755 --- a/scripts/pretty_json.py +++ b/scripts/pretty_json.py @@ -3,6 +3,8 @@ import sys for fname in sys.argv[1:]: - data = json.loads(open(fname).read()) + with open(fname) as _file: + data = json.loads(_file.read()) jstr = json.dumps(data, sort_keys=True, indent=2) - open(fname, "w").write(jstr) + with open(fname, "w") as _file: + _file.write(jstr) diff --git a/scripts/py2json.py b/scripts/py2json.py index 988696f5d..62e7092dd 100755 --- a/scripts/py2json.py +++ b/scripts/py2json.py @@ -21,10 +21,12 @@ def dataToPrettyJson(data, ensure_ascii=False): for fpath_py in sys.argv[1:]: - text_py = open(fpath_py).read() + with open(fpath_py) as _file: + text_py = _file.read() data = OrderedDict() exec(text_py, {}, data) text_json = dataToPrettyJson(data) fpath_nox = splitext(fpath_py)[0] fpath_json = fpath_nox + ".json" - open(fpath_json, "w").write(text_json) + with open(fpath_json, "w") as _file: + _file.write(text_json) diff --git a/scripts/version.py b/scripts/version.py index a7e3aaeee..b2587ded0 100755 --- a/scripts/version.py +++ b/scripts/version.py @@ -20,12 +20,12 @@ sys.exit(0) VERSION = "" -fp = open("%s/core.py" % scalDir) -while True: - line = fp.readline() - if line.startswith("VERSION"): - exec(line) - break +with open("%s/core.py" % scalDir) as _file: + while True: + line = _file.readline() + if line.startswith("VERSION"): + exec(line) + break gitDir = os.path.join(rootDir, ".git") if os.path.isdir(gitDir): diff --git a/tools/kalzium-elements-discovery.py b/tools/kalzium-elements-discovery.py index f6330ea1c..6e7aea7c6 100644 --- a/tools/kalzium-elements-discovery.py +++ b/tools/kalzium-elements-discovery.py @@ -7,7 +7,8 @@ log = logger.get() -tree = XML(open("/usr/share/apps/libkdeedu/data/elements.xml").read()) +with open("/usr/share/apps/libkdeedu/data/elements.xml") as _file: + tree = XML(_file.read()) def decodeAtomElement(atom): diff --git a/tools/wikipedia-fa-events/2-parse.py b/tools/wikipedia-fa-events/2-parse.py index e1c92986c..6e289ced2 100644 --- a/tools/wikipedia-fa-events/2-parse.py +++ b/tools/wikipedia-fa-events/2-parse.py @@ -42,7 +42,7 @@ def parseFile(fpath, month, day): # log.debug(fpath, month, day) category = "" data = [] - for line in open(fpath).read().split("\n"): + for line in open(fpath).read().split("\n"): # noqa: SIM115 if line.startswith("== "): category = line[2:-2].strip() if category in ignoreCategories: @@ -105,7 +105,8 @@ def writeToTabfile(data, fpath): ], ), ) - open(fpath, "w").write("\n".join(lines)) + with open(fpath, "w") as _file: + _file.write("\n".join(lines)) if __name__ == "__main__": diff --git a/tools/wikipedia-fa-events/3-starcal2-import.py b/tools/wikipedia-fa-events/3-starcal2-import.py index 4e69b1b36..0f989c727 100644 --- a/tools/wikipedia-fa-events/3-starcal2-import.py +++ b/tools/wikipedia-fa-events/3-starcal2-import.py @@ -43,7 +43,7 @@ def getGroupByTitle(title): return group -for line in open("wikipedia-fa.tab"): +for line in open("wikipedia-fa.tab"): # noqa: SIM115 line = line.strip() if not line: continue