Skip to content

Commit

Permalink
enable and fix more ruff errors
Browse files Browse the repository at this point in the history
  • Loading branch information
ilius committed Feb 19, 2024
1 parent 09ddbd6 commit 263f220
Show file tree
Hide file tree
Showing 28 changed files with 105 additions and 84 deletions.
2 changes: 1 addition & 1 deletion distro/base/install.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
20 changes: 10 additions & 10 deletions plugins/pray_times_files/pray_times_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -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
Expand Down
10 changes: 7 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,20 @@ 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
"TID", # flake8-tidy-imports
"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
]
Expand Down Expand Up @@ -80,6 +81,7 @@ ignore = [

# Allow autofix for all enabled rules (when `--fix`) is provided.
fixable = [
# "SIM",
"F401",
# "E", "F", "W",
"RET",
Expand Down Expand Up @@ -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",
]
Expand Down
2 changes: 1 addition & 1 deletion scal3/account/google.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ def do_GET(s):
b"</body></html>",
)

def log_message(self, format, *args):
def log_message(self, msgFormat, *args):
"""Do not log messages to stdout while running as command line program."""


Expand Down
10 changes: 5 additions & 5 deletions scal3/event_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
16 changes: 8 additions & 8 deletions scal3/format_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,24 +52,24 @@ 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
continue
if i == n - 1:
pyFmt += c0
break
c1 = format[i + 1]
c1 = fmt[i + 1]
if c1 == "%":
pyFmt += "%"
i += 2
Expand Down Expand Up @@ -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):
Expand Down
3 changes: 2 additions & 1 deletion scal3/ics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
4 changes: 2 additions & 2 deletions scal3/plugin_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand All @@ -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])
Expand Down
8 changes: 5 additions & 3 deletions scal3/plugin_man.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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):

Expand Down
2 changes: 1 addition & 1 deletion scal3/s_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
4 changes: 2 additions & 2 deletions scal3/startup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion scal3/ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}, "
Expand Down
2 changes: 1 addition & 1 deletion scal3/ui_gtk/about.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
3 changes: 2 additions & 1 deletion scal3/ui_gtk/arch-enable-locale.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 8 additions & 8 deletions scal3/ui_gtk/event/import_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = ""
Expand Down Expand Up @@ -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()

Expand Down
3 changes: 2 additions & 1 deletion scal3/ui_gtk/hijri.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
12 changes: 6 additions & 6 deletions scal3/ui_gtk/mywidgets/clock.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 "<b>%T</b>"
local is bool. if True, use Local time. and if False, use GMT time.
selectable is bool that passes to GtkLabel.
Expand All @@ -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)
Expand All @@ -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 "<b>%T</b>"
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)
Expand Down
2 changes: 1 addition & 1 deletion scal3/ui_gtk/mywidgets/num_ranges_entry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 8 additions & 8 deletions scal3/ui_gtk/wizard_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = ""
Expand All @@ -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=}")
Expand Down
Loading

0 comments on commit 263f220

Please sign in to comment.