Skip to content

Commit

Permalink
ruff: update config
Browse files Browse the repository at this point in the history
  • Loading branch information
karlicoss committed Aug 29, 2024
1 parent b4bb205 commit 6ddc810
Show file tree
Hide file tree
Showing 13 changed files with 232 additions and 99 deletions.
122 changes: 122 additions & 0 deletions ruff.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,50 @@
target-version = "py38" # NOTE: inferred from pyproject.toml if present

lint.extend-select = [
"F", # flakes rules -- default, but extend just in case
"E", # pycodestyle -- default, but extend just in case
"W", # various warnings

"B", # 'bugbear' set -- various possible bugs
"C4", # flake8-comprehensions -- unnecessary list/map/dict calls
"COM", # trailing commas
"EXE", # various checks wrt executable files
"I", # sort imports
"ICN", # various import conventions
"FBT", # detect use of boolean arguments
"FURB", # various rules
"PERF", # various potential performance speedups
"PD", # pandas rules
"PIE", # 'misc' lints
"PLC", # pylint convention rules
"PLR", # pylint refactor rules
"PLW", # pylint warnings
"PT", # pytest stuff
"PYI", # various type hinting rules
"RET", # early returns
"RUF", # various ruff-specific rules
"TID", # various imports suggestions
"TRY", # various exception handling rules
"UP", # detect deprecated python stdlib stuff
# "FA", # TODO enable later after we make sure cachew works?
"PTH", # pathlib migration
"ARG", # unused argument checks
"A", # builtin shadowing
# "EM", # TODO hmm could be helpful to prevent duplicate err msg in traceback.. but kinda annoying

# "ALL", # uncomment this to check for new rules!
]

lint.ignore = [
"D", # annoying nags about docstrings
"N", # pep naming
"TCH", # type checking rules, mostly just suggests moving imports under TYPE_CHECKING
"S", # bandit (security checks) -- tends to be not very useful, lots of nitpicks
"DTZ", # datetimes checks -- complaining about missing tz and mostly false positives
"FIX", # complains about fixmes/todos -- annoying
"TD", # complains about todo formatting -- too annoying
"ANN", # missing type annotations? seems way to strict though

### too opinionated style checks
"E501", # too long lines
"E702", # Multiple statements on one line (semicolon)
Expand All @@ -22,4 +68,80 @@ lint.ignore = [
"F841", # Local variable `count` is assigned to but never used
"F401", # imported but unused
###

### TODO should be fine to use these with from __future__ import annotations?
### there was some issue with cachew though... double check this?
"UP006", # use type instead of Type
"UP007", # use X | Y instead of Union
###
"RUF100", # unused noqa -- handle later
"RUF012", # mutable class attrs should be annotated with ClassVar... ugh pretty annoying for user configs

### these are just nitpicky, we usually know better
"PLR0911", # too many return statements
"PLR0912", # too many branches
"PLR0913", # too many function arguments
"PLR0915", # too many statements
"PLR1714", # consider merging multiple comparisons
"PLR2044", # line with empty comment
"PLR5501", # use elif instead of else if
"PLR2004", # magic value in comparison -- super annoying in tests
###
"PLR0402", # import X.Y as Y -- TODO maybe consider enabling it, but double check

"B009", # calling gettattr with constant attribute -- this is useful to convince mypy
"B010", # same as above, but setattr
"B011", # complains about assert False
"B017", # pytest.raises(Exception)
"B023", # seems to result in false positives?
"B028", # suggest using explicit stacklevel? TODO double check later, but not sure it's useful

# complains about useless pass, but has sort of a false positive if the function has a docstring?
# this is common for click entrypoints (e.g. in __main__), so disable
"PIE790",

# a bit too annoying, offers to convert for loops to list comprehension
# , which may heart readability
"PERF401",

# suggests no using exception in for loops
# we do use this technique a lot, plus in 3.11 happy path exception handling is "zero-cost"
"PERF203",

"RET504", # unnecessary assignment before returning -- that can be useful for readability
"RET505", # unnecessary else after return -- can hurt readability

"PLW0603", # global variable update.. we usually know why we are doing this
"PLW2901", # for loop variable overwritten, usually this is intentional

"PT004", # deprecated rule, will be removed later
"PT011", # pytest raises should is too broad
"PT012", # pytest raises should contain a single statement

"COM812", # trailing comma missing -- mostly just being annoying with long multiline strings

"PD901", # generic variable name df

"TRY003", # suggests defining exception messages in exception class -- kinda annoying
"TRY004", # prefer TypeError -- don't see the point
"TRY201", # raise without specifying exception name -- sometimes hurts readability
"TRY400", # TODO double check this, might be useful
"TRY401", # redundant exception in logging.exception call? TODO double check, might result in excessive logging

"PGH", # TODO force error code in mypy instead

"TID252", # Prefer absolute imports over relative imports from parent modules

## too annoying
"T20", # just complains about prints and pprints
"Q", # flake quotes, too annoying
"C90", # some complexity checking
"G004", # logging statement uses f string
"ERA001", # commented out code
"SLF001", # private member accessed
"BLE001", # do not catch 'blind' Exception
"INP001", # complains about implicit namespace packages
"SIM", # some if statements crap
"RSE102", # complains about missing parens in exceptions
##
]
10 changes: 6 additions & 4 deletions src/orger/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from .org_view import StaticView, OrgWithKey
from .org_view import Mirror, Queue
from typing import TYPE_CHECKING

# TODO deprecate properly?
InteractiveView = Queue
from .org_view import Mirror, OrgWithKey, Queue, StaticView

if not TYPE_CHECKING:
# TODO deprecate properly?
InteractiveView = Queue
16 changes: 8 additions & 8 deletions src/orger/atomic_append.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from pathlib import Path
from os.path import lexists
import logging
from os.path import lexists
from pathlib import Path
from typing import Union

PathIsh = Union[str, Path]
Expand All @@ -26,7 +26,7 @@ def assert_not_edited(path: Path) -> None:
for x in [vim, emacs]:
lf = path.parent / x
if lexists(lf): # lexist is necessary because emacs uses symlink for lock file
raise RuntimeError('File is being edited: {}'.format(lf))
raise RuntimeError(f'File is being edited: {lf}')


def atomic_append_check(
Expand All @@ -45,19 +45,19 @@ def atomic_append_check(


def test_atomic_append_check(tmp_path: Path) -> None:
import pytest
import platform

import pytest

if platform.system() == 'Windows':
pytest.skip("this test doesn't work on windows for now")

of = tmp_path / 'test.org'
of.touch()

from subprocess import Popen, PIPE, check_call
from time import sleep

from contextlib import contextmanager
from subprocess import PIPE, Popen, check_call
from time import sleep
@contextmanager
def tmp_popen(*args, **kwargs):
with Popen(*args, **kwargs) as p:
Expand All @@ -71,7 +71,7 @@ def tmp_popen(*args, **kwargs):
assert of.read_text() == 'data1data2'

with tmp_popen(['vi', '-c', 'startinsert', str(of)], stdin=PIPE, stdout=PIPE, stderr=PIPE) as p: # enter insert mode
for attempt in range(10):
for _attempt in range(10):
# ugh, needs long pause for some reason
sleep(1)
swapfiles = list(tmp_path.glob('.*.swp'))
Expand Down
12 changes: 7 additions & 5 deletions src/orger/common.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import traceback
import warnings
from datetime import datetime
from typing import Optional
from pathlib import Path
from typing import TYPE_CHECKING, Optional

from .inorganic import OrgNode, timestamp, timestamp_with_style, TimestampStyle
from .inorganic import OrgNode, TimestampStyle, timestamp, timestamp_with_style


# todo add error policy here?
Expand All @@ -23,15 +25,13 @@ def dt_heading(dt: Optional[datetime], heading: str) -> str:
tz = dt.tzinfo
# todo come up with a better way of reporting this..
if tz not in _timezones and len(_timezones) > 0:
import warnings
warnings.warn(f"Seems that a mixture of timezones is used. Org-mode doesn't support timezones, so this might end up confusing: {_timezones} {tz} {heading}")
_timezones.add(tz)

return timestamp_with_style(dt=dt, style=settings.DEFAULT_TIMESTAMP_STYLE) + ' ' + heading


def error(e: Exception) -> OrgNode:
import traceback
return OrgNode(
heading="ERROR!",
body='\n'.join(traceback.format_exception(Exception, e, None)),
Expand All @@ -58,4 +58,6 @@ def orger_user_dir() -> Path:
return Path(appdirs.user_config_dir('orger'))


from .logging_helper import LazyLogger, setup_logger # legacy imports for bwd compatibility
if not TYPE_CHECKING:
# legacy imports for bwd compatibility
from .logging_helper import LazyLogger, setup_logger
Loading

0 comments on commit 6ddc810

Please sign in to comment.