Skip to content

Commit

Permalink
Use ruff (#244)
Browse files Browse the repository at this point in the history
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
gaborbernat and pre-commit-ci[bot] authored Jun 10, 2023
1 parent b445623 commit 34ff501
Show file tree
Hide file tree
Showing 14 changed files with 126 additions and 172 deletions.
8 changes: 0 additions & 8 deletions .markdownlint.yaml

This file was deleted.

58 changes: 6 additions & 52 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,77 +2,31 @@ repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: check-ast
- id: check-builtin-literals
- id: check-docstring-first
- id: check-merge-conflict
- id: check-yaml
- id: check-toml
- id: debug-statements
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/asottile/add-trailing-comma
rev: v2.4.0
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: "v0.0.272"
hooks:
- id: add-trailing-comma
args: [--py36-plus]
- repo: https://github.com/asottile/pyupgrade
rev: v3.3.1
hooks:
- id: pyupgrade
args: ["--py37-plus"]
- repo: https://github.com/PyCQA/isort
rev: 5.12.0
hooks:
- id: isort
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
- repo: https://github.com/psf/black
rev: 23.3.0
hooks:
- id: black
args: [--safe]
- repo: https://github.com/asottile/blacken-docs
rev: 1.13.0
hooks:
- id: blacken-docs
additional_dependencies: [black==23.3]
- repo: https://github.com/pre-commit/pygrep-hooks
rev: v1.10.0
hooks:
- id: rst-backticks
- repo: https://github.com/tox-dev/tox-ini-fmt
rev: "1.3.0"
hooks:
- id: tox-ini-fmt
args: ["-p", "fix"]
- repo: https://github.com/tox-dev/pyproject-fmt
rev: "0.9.2"
rev: "0.11.2"
hooks:
- id: pyproject-fmt
- repo: https://github.com/PyCQA/flake8
rev: 6.0.0
hooks:
- id: flake8
additional_dependencies:
- flake8-bugbear==23.3.23
- flake8-comprehensions==3.12
- flake8-pytest-style==1.7.2
- flake8-spellcheck==0.28
- flake8-unused-arguments==0.0.13
- flake8-noqa==1.3.1
- pep8-naming==0.13.3
- flake8-pyproject==1.2.3
- repo: https://github.com/pre-commit/mirrors-prettier
rev: "v2.7.1"
rev: "v3.0.0-alpha.9-for-vscode"
hooks:
- id: prettier
additional_dependencies:
- prettier@2.7.1
- "@prettier/plugin-xml@2.2"
args: ["--print-width=120", "--prose-wrap=always"]
- repo: https://github.com/igorshubovych/markdownlint-cli
rev: v0.33.0
hooks:
- id: markdownlint
- repo: meta
hooks:
- id: check-hooks-apply
Expand Down
31 changes: 21 additions & 10 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,24 @@
# noqa: INP001
"""Configuration for Sphinx."""
from __future__ import annotations

from datetime import date, datetime
from datetime import datetime, timezone
from typing import TYPE_CHECKING

from docutils.nodes import Element, Text
from sphinx.addnodes import pending_xref
from sphinx.application import Sphinx
from sphinx.builders import Builder
from filelock import __version__
from sphinx.domains.python import PythonDomain
from sphinx.environment import BuildEnvironment

from filelock import __version__
if TYPE_CHECKING:
from sphinx.addnodes import pending_xref
from sphinx.application import Sphinx
from sphinx.builders import Builder
from sphinx.environment import BuildEnvironment

name, company = "filelock", "tox-dev"
now = datetime.now(tz=timezone.utc)
version, release = ".".join(__version__.split(".")[:2]), __version__
copyright = f"2014-{date.today().year}, {company}"
copyright = f"2014-{now.date().year}, {company}" # noqa: A001
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.autosectionlabel",
Expand All @@ -23,7 +28,7 @@
"sphinx_autodoc_typehints",
]
html_theme = "furo"
html_title, html_last_updated_fmt = name, datetime.now().isoformat()
html_title, html_last_updated_fmt = name, now.isoformat()
pygments_style, pygments_dark_style = "sphinx", "monokai"
autoclass_content, autodoc_member_order, autodoc_typehints = "class", "bysource", "none"
autodoc_default_options = {"member-order": "bysource", "undoc-members": True, "show-inheritance": True}
Expand All @@ -40,13 +45,19 @@


def setup(app: Sphinx) -> None:
"""
Setup app.
:param app: the app
"""

class PatchedPythonDomain(PythonDomain):
def resolve_xref(
def resolve_xref( # noqa: PLR0913
self,
env: BuildEnvironment,
fromdocname: str,
builder: Builder,
type: str,
type: str, # noqa: A002
target: str,
node: pending_xref,
contnode: Element,
Expand Down
53 changes: 33 additions & 20 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
build-backend = "hatchling.build"
requires = [
"hatch-vcs>=0.3",
"hatchling>=1.14",
"hatchling>=1.17",
]

[project]
Expand All @@ -25,8 +25,12 @@ classifiers = [
"License :: OSI Approved :: The Unlicense (Unlicense)",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Topic :: Internet",
"Topic :: Software Development :: Libraries",
"Topic :: System",
Expand All @@ -35,16 +39,16 @@ dynamic = [
"version",
]
optional-dependencies.docs = [
"furo>=2023.3.27",
"sphinx>=6.1.3",
"furo>=2023.5.20",
"sphinx>=7.0.1",
"sphinx-autodoc-typehints!=1.23.4,>=1.23",
]
optional-dependencies.testing = [
"covdefaults>=2.3",
"coverage>=7.2.3",
"coverage>=7.2.7",
"diff-cover>=7.5",
"pytest>=7.3.1",
"pytest-cov>=4",
"pytest-cov>=4.1",
"pytest-mock>=3.10",
"pytest-timeout>=2.1",
]
Expand All @@ -61,18 +65,6 @@ version.source = "vcs"
[tool.black]
line-length = 120

[tool.isort]
profile = "black"
known_first_party = ["filelock"]
add_imports = ["from __future__ import annotations"]

[tool.flake8]
max-complexity = 22
max-line-length = 120
unused-arguments-ignore-abstract-functions = true
noqa-require-code = true
dictionaries = ["en_US", "python", "technical", "django"]

[tool.coverage]
html.show_contexts = true
html.skip_covered = false
Expand All @@ -88,5 +80,26 @@ show_error_codes = true
strict = true
overrides = [{ module = ["appdirs.*", "jnius.*"], ignore_missing_imports = true }]

[tool.pep8]
max-line-length = "120"
[tool.ruff]
select = ["ALL"]
line-length = 120
target-version = "py37"
isort = {known-first-party = ["platformdirs", "tests"], required-imports = ["from __future__ import annotations"]}
ignore = [
"ANN101", # Missing type annotation for `self` in method
"D301", # Use `r"""` if any backslashes in a docstring
"D205", # 1 blank line required between summary line and description
"D401", # First line of docstring should be in imperative mood
"D203", # `one-blank-line-before-class` (D203) and `no-blank-line-before-class` (D211) are incompatible
"D212", # `multi-line-summary-first-line` (D212) and `multi-line-summary-second-line` (D213) are incompatible
"S104", # Possible binding to all interface
]
[tool.ruff.per-file-ignores]
"tests/**/*.py" = [
"S101", # asserts allowed in tests...
"FBT", # don"t care about booleans as positional arguments in tests
"INP001", # no implicit namespace
"D", # don"t care about documentation in tests
"S603", # `subprocess` call: check for execution of untrusted input
"PLR2004", # Magic value used in comparison, consider replacing with a constant variable
]
10 changes: 4 additions & 6 deletions src/filelock/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,16 @@
if sys.platform == "win32": # pragma: win32 cover
_FileLock: type[BaseFileLock] = WindowsFileLock
else: # pragma: win32 no cover
if has_fcntl:
if has_fcntl: # noqa: PLR5501
_FileLock: type[BaseFileLock] = UnixFileLock
else:
_FileLock = SoftFileLock
if warnings is not None:
warnings.warn("only soft file lock is available", stacklevel=2)

if TYPE_CHECKING:
FileLock = SoftFileLock
else:
#: Alias for the lock, which should be used for the current platform.
FileLock = _FileLock

#: Alias for the lock, which should be used for the current platform.
FileLock: type[BaseFileLock] = SoftFileLock if TYPE_CHECKING else _FileLock # type: ignore[assignment]


__all__ = [
Expand Down
49 changes: 22 additions & 27 deletions src/filelock/_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@
from abc import ABC, abstractmethod
from dataclasses import dataclass
from threading import local
from types import TracebackType
from typing import Any
from typing import TYPE_CHECKING, Any

from ._error import Timeout

if TYPE_CHECKING:
from types import TracebackType

_LOGGER = logging.getLogger("filelock")


Expand All @@ -30,18 +32,16 @@ def __enter__(self) -> BaseFileLock:

def __exit__(
self,
exc_type: type[BaseException] | None, # noqa: U100
exc_value: BaseException | None, # noqa: U100
traceback: TracebackType | None, # noqa: U100
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: TracebackType | None,
) -> None:
self.lock.release()


@dataclass
class FileLockContext:
"""
A dataclass which holds the context for a ``BaseFileLock`` object.
"""
"""A dataclass which holds the context for a ``BaseFileLock`` object."""

# The context is held in a separate class to allow optional use of thread local storage via the
# ThreadLocalFileContext class.
Expand All @@ -63,9 +63,7 @@ class FileLockContext:


class ThreadLocalFileContext(FileLockContext, local):
"""
A thread local version of the ``FileLockContext`` class.
"""
"""A thread local version of the ``FileLockContext`` class."""


class BaseFileLock(ABC, contextlib.ContextDecorator):
Expand All @@ -76,7 +74,7 @@ def __init__(
lock_file: str | os.PathLike[Any],
timeout: float = -1,
mode: int = 0o644,
thread_local: bool = True,
thread_local: bool = True, # noqa: FBT001, FBT002
) -> None:
"""
Create a new lock object.
Expand Down Expand Up @@ -151,9 +149,7 @@ def is_locked(self) -> bool:

@property
def lock_counter(self) -> int:
"""
:return: The number of times this lock has been acquired (but not yet released).
"""
""":return: The number of times this lock has been acquired (but not yet released)."""
return self._context.lock_counter

def acquire(
Expand Down Expand Up @@ -218,22 +214,21 @@ def acquire(
if self.is_locked:
_LOGGER.debug("Lock %s acquired on %s", lock_id, lock_filename)
break
elif blocking is False:
if blocking is False:
_LOGGER.debug("Failed to immediately acquire lock %s on %s", lock_id, lock_filename)
raise Timeout(lock_filename)
elif 0 <= timeout < time.perf_counter() - start_time:
raise Timeout(lock_filename) # noqa: TRY301
if 0 <= timeout < time.perf_counter() - start_time:
_LOGGER.debug("Timeout on acquiring lock %s on %s", lock_id, lock_filename)
raise Timeout(lock_filename)
else:
msg = "Lock %s not acquired on %s, waiting %s seconds ..."
_LOGGER.debug(msg, lock_id, lock_filename, poll_interval)
time.sleep(poll_interval)
raise Timeout(lock_filename) # noqa: TRY301
msg = "Lock %s not acquired on %s, waiting %s seconds ..."
_LOGGER.debug(msg, lock_id, lock_filename, poll_interval)
time.sleep(poll_interval)
except BaseException: # Something did go wrong, so decrement the counter.
self._context.lock_counter = max(0, self._context.lock_counter - 1)
raise
return AcquireReturnProxy(lock=self)

def release(self, force: bool = False) -> None:
def release(self, force: bool = False) -> None: # noqa: FBT001, FBT002
"""
Releases the file lock. Please note, that the lock is only completely released, if the lock counter is 0. Also
note, that the lock file itself is not automatically deleted.
Expand Down Expand Up @@ -262,9 +257,9 @@ def __enter__(self) -> BaseFileLock:

def __exit__(
self,
exc_type: type[BaseException] | None, # noqa: U100
exc_value: BaseException | None, # noqa: U100
traceback: TracebackType | None, # noqa: U100
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: TracebackType | None,
) -> None:
"""
Release the lock.
Expand Down
2 changes: 1 addition & 1 deletion src/filelock/_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from typing import Any


class Timeout(TimeoutError):
class Timeout(TimeoutError): # noqa: N818
"""Raised when the lock could not be acquired in *timeout* seconds."""

def __init__(self, lock_file: str) -> None:
Expand Down
Loading

0 comments on commit 34ff501

Please sign in to comment.