Skip to content

Commit

Permalink
Enabled more lint rules (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
zsimic committed Mar 5, 2024
1 parent fc150a0 commit b4b9c59
Show file tree
Hide file tree
Showing 31 changed files with 154 additions and 134 deletions.
37 changes: 37 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,43 @@ cache-dir = ".tox/.ruff_cache"
line-length = 140
src = ["src", "tests"]

[tool.ruff.lint]
extend-select = [
# "A", # flake8-builtins
# "ARG", # flake8-unused-arguments
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"C90", # mccabe
# "D", # pydocstyle
"DTZ", # flake8-datetimez
"E", # pycodestyle errors
"ERA", # eradicate
"EXE", # flake8-executable
"F", # pyflakes
"FLY", # flynt
"G", # flake8-logging-format
# "I", # isort
"INT", # flake8-gettext
"PGH", # pygrep-hooks
"PIE", # flake8-pie
# "PT", # flake8-pytest
# "PYI", # flake8-pyi
# "Q", # flake8-quotes
# "RSE", # flake8-raise
# "RET", # flake8-return
## "RUF", # ruff-specific
## "S", # flake8-bandit
## "SIM", # flake8-simplify
## "SLF", # flake8-self
# "SLOT", # flake8-slots
# "T10", # flake8-debugger
# "TID", # flake8-tidy-imports
# "TCH", # flake8-type-checking
## "TD", # flake8-todos
## "TRY", # tryceratops
# "W", # pycodestyle warnings
]

[tool.ruff.lint.isort]
order-by-type = false

Expand Down
5 changes: 1 addition & 4 deletions src/runez/_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,7 @@


def simple_inspection():
return dict(
version=".".join(str(s) for s in sys.version_info[:3]),
machine=platform.machine(),
)
return {"version": ".".join(str(s) for s in sys.version_info[:3]), "machine": platform.machine()}


if __name__ == "__main__":
Expand Down
4 changes: 2 additions & 2 deletions src/runez/click.py
Original file line number Diff line number Diff line change
Expand Up @@ -397,9 +397,9 @@ def __init__(self, attrs):
def _get_values(self, value):
value = flattened(value, split=self.split)
values = [t.partition("=") for t in value if t]
values = dict((k, v) for k, _, v in values)
values = {k: v for k, _, v in values}
if self.prefix:
values = dict((affixed(k, prefix=self.prefix), v) for k, v in values.items())
values = {affixed(k, prefix=self.prefix): v for k, v in values.items()}

return values

Expand Down
4 changes: 2 additions & 2 deletions src/runez/colors/terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def named_triplet(self):
"""Triplet of named bg, fg and style-s"""
bg = NamedColors(
cls=AnsiColor,
params=dict(ansi=self.ansi, flavor=self.flavor),
params={"ansi": self.ansi, "flavor": self.flavor},
black=-0x000001,
blue=-0x0000FF,
brown=-0xA52A2A,
Expand All @@ -140,7 +140,7 @@ def named_triplet(self):
)
fg = NamedColors(
cls=AnsiColor,
params=dict(ansi=self.ansi, flavor=self.flavor),
params={"ansi": self.ansi, "flavor": self.flavor},
black=0x000000,
blue=0x0000FF,
brown=0x850A0A,
Expand Down
22 changes: 8 additions & 14 deletions src/runez/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,7 @@ def test_my_cli(cli):
if r.failed:
msg = "%s --help failed" % runez.short(script)
logging.error("%s\n%s", msg, r.full_output)
assert False, msg
raise AssertionError(msg)

def run(self, *args, exe=None, main=UNSET, trace=UNSET):
"""
Expand Down Expand Up @@ -431,13 +431,11 @@ def expect_messages(self, *expected, **kwargs):
for message in expected:
if message[0] == "!":
m = self.match(message[1:], **kwargs)
if m:
assert False, "Unexpected match in output: %s" % m
assert not m, "Unexpected match in output: %s" % m

else:
m = self.match(message, **kwargs)
if not m:
assert False, "Not seen in output: %s" % message
assert m, "Not seen in output: %s" % message

def expect_success(self, args, *expected, **kwargs):
spec = RunSpec()
Expand Down Expand Up @@ -499,15 +497,11 @@ def _run_main(self, main, args):

return result

if isinstance(main, str):
script = self._resolved_script(main)
if not script:
assert False, "Can't find script '%s', invalid main" % script

r = runez.run(sys.executable, script, *args, fatal=False)
return ClickWrapper(r.output, r.error, r.exit_code, r.exc_info)

assert False, "Can't invoke invalid main: %s" % main
assert isinstance(main, str), "Can't invoke invalid main: %s" % main
script = self._resolved_script(main)
assert script, "Can't find script '%s', invalid main" % main
r = runez.run(sys.executable, script, *args, fatal=False)
return ClickWrapper(r.output, r.error, r.exit_code, r.exc_info)


class RunSpec(Slotted):
Expand Down
3 changes: 1 addition & 2 deletions src/runez/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -491,5 +491,4 @@ def parsed_line(self, line):
data[current.name].append(text)
m = self.regex.search(line, wend + 1)

data = dict((k, joined(v)) for k, v in data.items())
return data
return {k: joined(v) for k, v in data.items()}
5 changes: 2 additions & 3 deletions src/runez/date.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def dst(self, dt):


UTC = timezone(datetime.timedelta(0), "UTC")
NAMED_TIMEZONES = dict(Z=UTC, UTC=UTC)
NAMED_TIMEZONES = {"Z": UTC, "UTC": UTC}


def date_from_epoch(epoch, in_ms=None):
Expand Down Expand Up @@ -358,7 +358,6 @@ def to_seconds(duration):
v = m.group(1)
seconds = to_seconds(duration.replace(v, ""))

# v = v.strip()
if v.endswith("w"):
seconds += int(v[:-1], 0) * SECONDS_IN_ONE_DAY * 7

Expand Down Expand Up @@ -432,7 +431,7 @@ def _date_from_text(text, epocher, tz=UNSET):

return None

# _, number, _, _, y, m, d, _, hh, mm, ss, sf, _, tz, _, _ = match.groups()
# Groups: _, number, _, _, y, m, d, _, hh, mm, ss, sf, _, tz, _, _
components = match.groups()
if components[1]:
return epocher(_float_from_text(components[1], lenient=True), tz=tz)
Expand Down
2 changes: 1 addition & 1 deletion src/runez/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ def ini_to_dict(path, keep_empty=False, fatal=False, logger=False):
section[key] = value

if not keep_empty:
result = dict((k, v) for k, v in result.items() if k and v)
result = {k: v for k, v in result.items() if k and v}

return result

Expand Down
4 changes: 2 additions & 2 deletions src/runez/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ def stop(self):
def response_for_url(self, method, url):
spec = self.specs.get(url)
if spec is None:
return MockResponse(404, dict(message="Default status code 404"))
return MockResponse(404, {"message": "Default status code 404"})

if isinstance(spec, BaseException):
raise spec
Expand Down Expand Up @@ -1025,7 +1025,7 @@ def _get_response(self, method, url, fatal, logger, dryrun=False, state=None, ac
absolute_url = self.full_url(url)
message = "%s %s" % (action or method, absolute_url)
if _R.hdry(dryrun, logger, message):
return RestResponse(method, absolute_url, MockResponse(200, dict(message="dryrun %s" % message)))
return RestResponse(method, absolute_url, MockResponse(200, {"message": "dryrun %s" % message}))

cache_key = cache_expire = None
if self.cache_wrapper is not None:
Expand Down
2 changes: 1 addition & 1 deletion src/runez/inspector.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def foo(...):
import pkgutil

imported = []
for loader, module_name, _ in pkgutil.walk_packages([caller.folder], prefix="%s." % caller.package_name):
for _, module_name, _ in pkgutil.walk_packages([caller.folder], prefix="%s." % caller.package_name):
if _should_auto_import(module_name, skip):
importlib.import_module(module_name)
imported.append(module_name)
Expand Down
19 changes: 11 additions & 8 deletions src/runez/logsetup.py
Original file line number Diff line number Diff line change
Expand Up @@ -526,7 +526,7 @@ def should_log_to_file(self):
return bool(self.locations)

def _props(self, **additional):
r = dict(argv=self.argv, pid=self.pid)
r = {"argv": self.argv, "pid": self.pid}
r.update(self.to_dict())
r.update(additional)
return r
Expand Down Expand Up @@ -702,7 +702,7 @@ class LogManager:

# Spec defines how logs should be setup()
# Best way to provide your spec is via: runez.log.setup(), for example:
# runez.log.setup(rotate="size:50m")
# >>> runez.log.setup(rotate="size:50m")
spec = LogSpec(_default_spec)

# Thread-local / global context
Expand Down Expand Up @@ -950,14 +950,17 @@ def is_using_format(cls, markers, used_formats=None):
return any(marker in used_formats for marker in flattened(markers, split=" "))

@classmethod
def enable_faulthandler(cls, signum=getattr(signal, "SIGUSR1", None)):
def enable_faulthandler(cls, signum=UNSET):
"""Enable dumping thread stack traces when specified signals are received, similar to java's handling of SIGQUIT
Note: this must be called from the surviving process in case of daemonization.
Args:
signum (int | None): Signal number to register for full thread stack dump (use None to disable)
"""
if signum is UNSET:
signum = getattr(signal, "SIGUSR1", None)

with cls._lock:
if not signum:
cls._disable_faulthandler()
Expand All @@ -968,8 +971,8 @@ def enable_faulthandler(cls, signum=getattr(signal, "SIGUSR1", None)):

cls.faulthandler_signum = signum
dump_file = cls.file_handler.stream
faulthandler.enable(file=dump_file, all_threads=True) # noqa
faulthandler.register(signum, file=dump_file, all_threads=True, chain=False) # noqa
faulthandler.enable(file=dump_file, all_threads=True)
faulthandler.register(signum, file=dump_file, all_threads=True, chain=False)

@classmethod
def override_spec(cls, **settings):
Expand Down Expand Up @@ -1055,10 +1058,10 @@ def _props(cls):
def _auto_enable_progress_handler(cls):
if cls.progress.is_running:
if ProgressHandler not in logging.root.handlers:
logging.root.handlers.append(ProgressHandler) # noqa
logging.root.handlers.append(ProgressHandler)

elif ProgressHandler in logging.root.handlers:
logging.root.handlers.remove(ProgressHandler) # noqa
logging.root.handlers.remove(ProgressHandler)

@classmethod
def _update_used_formats(cls):
Expand Down Expand Up @@ -1292,7 +1295,7 @@ def _formatted_text(text, props, strict=False, max_depth=3):
if not max_depth or not isinstance(max_depth, int) or max_depth <= 0:
return text

result = dict((k, _format_recursive(k, v, definitions, max_depth)) for k, v in definitions.items())
result = {k: _format_recursive(k, v, definitions, max_depth) for k, v in definitions.items()}
return text.format(**result)


Expand Down
4 changes: 2 additions & 2 deletions src/runez/program.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def cmd_basename(self):

@cached_property
def ps_follow(self):
return dict(tmux=("tmux", "display-message", "-p", "#{client_pid}"))
return {"tmux": ("tmux", "display-message", "-p", "#{client_pid}")}

@cached_property
def followed_parent(self):
Expand Down Expand Up @@ -560,7 +560,7 @@ def require_installed(program, instructions=None, platform=None):
"""
if which(program) is None:
if not instructions:
instructions = dict(macos="run: `brew install {program}`", linux="run: `apt install {program}`")
instructions = {"macos": "run: `brew install {program}`", "linux": "run: `apt install {program}`"}

if isinstance(instructions, dict):
instructions = _install_instructions(instructions, platform or SYS_INFO.platform_id.platform)
Expand Down
6 changes: 3 additions & 3 deletions src/runez/pyenv.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ def ls_pypi(cls, package_name, client=None, index=None, source=None, fatal=False
@classmethod
def _versions_from_pypi(cls, releases, source=None):
if isinstance(releases, dict):
for v, infos in releases.items():
for _, infos in releases.items():
for info in infos:
if not info.get("yanked"):
size = info.get("size")
Expand Down Expand Up @@ -497,7 +497,7 @@ def find_python(self, spec):

def _find_python(self, spec):
if isinstance(spec, str):
if spec.startswith("~") or spec.startswith(".") or "/" in spec or os.path.exists(spec):
if spec.startswith(("~", ".", "/")) or "/" in spec or os.path.exists(spec):
return PythonInstallation.from_path(Path(resolved_path(spec)), short_name=short(spec))

elif spec == "invoker":
Expand Down Expand Up @@ -715,7 +715,7 @@ def local_parts(self):
v = getattr(self, "_local_parts", None)
if v is None:
v = self.local_part.split(".")
setattr(self, "_local_parts", v)
self._local_parts = v

return v

Expand Down
32 changes: 16 additions & 16 deletions src/runez/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,19 @@
from runez.system import SYS_INFO, UNSET, wcswidth


NAMED_BORDERS = dict(
ascii="rstgrid,t:+++=,m:+++-",
compact="c: ,h: -",
colon="c: : ,h: : -",
dots="t:....,b::::.,c::::,h:.:..",
empty="",
framed="t:┍┯┑━,m:┝┿┥━,b:┕┷┙━,c:│││,h:╞╪╡═",
github="h:-|--,c:|||",
mysql="t:+++-,b:+++-,c:|||",
reddit="h:-|--,c: | ",
rst="t: ==,b: ==,c: ",
rstgrid="mysql,h:+++=",
)
NAMED_BORDERS = {
"ascii": "rstgrid,t:+++=,m:+++-",
"compact": "c: ,h: -",
"colon": "c: : ,h: : -",
"dots": "t:....,b::::.,c::::,h:.:..",
"empty": "",
"framed": "t:┍┯┑━,m:┝┿┥━,b:┕┷┙━,c:│││,h:╞╪╡═",
"github": "h:-|--,c:|||",
"mysql": "t:+++-,b:+++-,c:|||",
"reddit": "h:-|--,c: | ",
"rst": "t: ==,b: ==,c: ",
"rstgrid": "mysql,h:+++=",
}


class Align:
Expand Down Expand Up @@ -138,7 +138,7 @@ def set_pad(self, value):
self.pad = to_int(value)

def _get_defaults(self):
return dict(c=_PTBorderChars(), pad=1)
return {"c": _PTBorderChars(), "pad": 1}

def _values_from_string(self, text):
values = {}
Expand Down Expand Up @@ -192,7 +192,7 @@ def formatted(self, text):

@staticmethod
def merged(*chain):
values = dict(align=Align.left)
values = {"align": Align.left}
for item in chain:
if item is not None:
values.update(item.to_dict())
Expand Down Expand Up @@ -472,7 +472,7 @@ def _values_from_object(self, obj):
obj += [""] * missing

first, mid, last, h = obj
return dict(first=first, mid=mid, last=last, h=h)
return {"first": first, "mid": mid, "last": last, "h": h}

return super()._values_from_object(obj)

Expand Down
4 changes: 2 additions & 2 deletions src/runez/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ def _problem(self, value):
return "value: %s" % problem

def _converted(self, value):
return dict((self.key.converted(k), self.value.converted(v)) for k, v in value.items())
return {self.key.converted(k): self.value.converted(v) for k, v in value.items()}


class Enum(Any):
Expand Down Expand Up @@ -358,7 +358,7 @@ def to_dict(self):
Returns:
(dict): This object serialized to a dict
"""
return dict((name, getattr(self, name)) for name in self.meta.attributes)
return {name: getattr(self, name) for name in self.meta.attributes}

def set_from_dict(self, data, source=None):
"""
Expand Down

0 comments on commit b4b9c59

Please sign in to comment.