Skip to content

Commit

Permalink
Merge pull request #2438 from dbluhm/feature/ruff
Browse files Browse the repository at this point in the history
Swap out flake8 in favor of Ruff
  • Loading branch information
swcurran authored Aug 31, 2023
2 parents 981a3f0 + a76fb2d commit fa28560
Show file tree
Hide file tree
Showing 461 changed files with 1,475 additions and 2,894 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -189,4 +189,4 @@ _build/
**/*.iml

# Open API build
open-api/.build
open-api/.build
8 changes: 5 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ repos:
hooks:
- id: black
stages: [commit]
- repo: https://github.com/pycqa/flake8.git
rev: 4.0.1
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.0.285
hooks:
- id: flake8
- id: ruff
stages: [commit]
args: [--fix, --exit-non-zero-on-fix]
3 changes: 1 addition & 2 deletions aries_cloudagent/admin/base_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ class BaseAdminServer(ABC):

@abstractmethod
async def start(self) -> None:
"""
Start the webserver.
"""Start the webserver.
Raises:
AdminSetupError: If there was an error starting the webserver
Expand Down
19 changes: 6 additions & 13 deletions aries_cloudagent/admin/request_context.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""
Admin request context class.
"""Admin request context class.
A request context provided by the admin server to admin route handlers.
"""
Expand Down Expand Up @@ -63,8 +62,7 @@ def session(self) -> ProfileSession:
return self.profile.session(self._context)

def transaction(self) -> ProfileSession:
"""
Start a new interactive session with commit and rollback support.
"""Start a new interactive session with commit and rollback support.
If the current backend does not support transactions, then commit
and rollback operations of the session will not have any effect.
Expand All @@ -76,8 +74,7 @@ def inject(
base_cls: Type[InjectType],
settings: Mapping[str, object] = None,
) -> InjectType:
"""
Get the provided instance of a given class identifier.
"""Get the provided instance of a given class identifier.
Args:
cls: The base class to retrieve an instance of
Expand All @@ -95,8 +92,7 @@ def inject_or(
settings: Mapping[str, object] = None,
default: Optional[InjectType] = None,
) -> Optional[InjectType]:
"""
Get the provided instance of a given class identifier or default if not found.
"""Get the provided instance of a given class identifier or default if not found.
Args:
base_cls: The base class to retrieve an instance of
Expand All @@ -119,9 +115,7 @@ def test_context(
) -> "AdminRequestContext":
"""Quickly set up a new admin request context for tests."""
ctx = AdminRequestContext(profile or IN_MEM.resolved.test_profile())
setattr(
ctx, "session_inject", dict() if session_inject is None else session_inject
)
setattr(ctx, "session_inject", {} if session_inject is None else session_inject)
setattr(ctx, "session", ctx._test_session)
return ctx

Expand Down Expand Up @@ -151,8 +145,7 @@ def _inject_or(base_cls, default=None):
return session

def __repr__(self) -> str:
"""
Provide a human readable representation of this object.
"""Provide a human readable representation of this object.
Returns:
A human readable representation of this object
Expand Down
40 changes: 14 additions & 26 deletions aries_cloudagent/admin/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,7 @@ def __init__(
send: Coroutine,
**kwargs,
):
"""
Initialize an instance of `AdminResponder`.
"""Initialize an instance of `AdminResponder`.
Args:
send: Function to send outbound message
Expand All @@ -135,8 +134,7 @@ def __init__(
async def send_outbound(
self, message: OutboundMessage, **kwargs
) -> OutboundSendStatus:
"""
Send outbound message.
"""Send outbound message.
Args:
message: The `OutboundMessage` to be sent
Expand All @@ -147,8 +145,7 @@ async def send_outbound(
return await self._send(profile, message)

async def send_webhook(self, topic: str, payload: dict):
"""
Dispatch a webhook. DEPRECATED: use the event bus instead.
"""Dispatch a webhook. DEPRECATED: use the event bus instead.
Args:
topic: the webhook topic identifier
Expand Down Expand Up @@ -240,8 +237,7 @@ def __init__(
task_queue: TaskQueue = None,
conductor_stats: Coroutine = None,
):
"""
Initialize an AdminServer instance.
"""Initialize an AdminServer instance.
Args:
host: Host to listen on
Expand Down Expand Up @@ -510,8 +506,7 @@ async def setup_context(request: web.Request, handler):
return app

async def start(self) -> None:
"""
Start the webserver.
"""Start the webserver.
Raises:
AdminSetupError: If there was an error starting the webserver
Expand All @@ -523,7 +518,7 @@ def sort_dict(raw: dict) -> dict:
for k, v in raw.items():
if isinstance(v, dict):
raw[k] = sort_dict(v)
return dict(sorted([item for item in raw.items()], key=lambda x: x[0]))
return dict(sorted(raw.items(), key=lambda x: x[0]))

self.app = await self.make_application()
runner = web.AppRunner(self.app)
Expand Down Expand Up @@ -560,7 +555,7 @@ def sort_dict(raw: dict) -> dict:
method_spec["parameters"].sort(
key=lambda p: (p["in"], not p["required"], p["name"])
)
for path in sorted([p for p in swagger_dict["paths"]]):
for path in sorted(swagger_dict["paths"]):
swagger_dict["paths"][path] = swagger_dict["paths"].pop(path)

# order definitions alphabetically by dict key
Expand Down Expand Up @@ -622,8 +617,7 @@ async def on_startup(self, app: web.Application):
@docs(tags=["server"], summary="Fetch the list of loaded plugins")
@response_schema(AdminModulesSchema(), 200, description="")
async def plugins_handler(self, request: web.BaseRequest):
"""
Request handler for the loaded plugins list.
"""Request handler for the loaded plugins list.
Args:
request: aiohttp request object
Expand All @@ -639,8 +633,7 @@ async def plugins_handler(self, request: web.BaseRequest):
@docs(tags=["server"], summary="Fetch the server configuration")
@response_schema(AdminConfigSchema(), 200, description="")
async def config_handler(self, request: web.BaseRequest):
"""
Request handler for the server configuration.
"""Request handler for the server configuration.
Args:
request: aiohttp request object
Expand Down Expand Up @@ -678,8 +671,7 @@ async def config_handler(self, request: web.BaseRequest):
@docs(tags=["server"], summary="Fetch the server status")
@response_schema(AdminStatusSchema(), 200, description="")
async def status_handler(self, request: web.BaseRequest):
"""
Request handler for the server status information.
"""Request handler for the server status information.
Args:
request: aiohttp request object
Expand All @@ -700,8 +692,7 @@ async def status_handler(self, request: web.BaseRequest):
@docs(tags=["server"], summary="Reset statistics")
@response_schema(AdminResetSchema(), 200, description="")
async def status_reset_handler(self, request: web.BaseRequest):
"""
Request handler for resetting the timing statistics.
"""Request handler for resetting the timing statistics.
Args:
request: aiohttp request object
Expand All @@ -722,8 +713,7 @@ async def redirect_handler(self, request: web.BaseRequest):
@docs(tags=["server"], summary="Liveliness check")
@response_schema(AdminStatusLivelinessSchema(), 200, description="")
async def liveliness_handler(self, request: web.BaseRequest):
"""
Request handler for liveliness check.
"""Request handler for liveliness check.
Args:
request: aiohttp request object
Expand All @@ -741,8 +731,7 @@ async def liveliness_handler(self, request: web.BaseRequest):
@docs(tags=["server"], summary="Readiness check")
@response_schema(AdminStatusReadinessSchema(), 200, description="")
async def readiness_handler(self, request: web.BaseRequest):
"""
Request handler for liveliness check.
"""Request handler for liveliness check.
Args:
request: aiohttp request object
Expand All @@ -760,8 +749,7 @@ async def readiness_handler(self, request: web.BaseRequest):
@docs(tags=["server"], summary="Shut down server")
@response_schema(AdminShutdownSchema(), description="")
async def shutdown_handler(self, request: web.BaseRequest):
"""
Request handler for server shutdown.
"""Request handler for server shutdown.
Args:
request: aiohttp request object
Expand Down
2 changes: 1 addition & 1 deletion aries_cloudagent/admin/tests/test_request_context.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from asynctest import mock as asyn_mock, TestCase as AsyncTestCase
from asynctest import TestCase as AsyncTestCase

from ...core.in_memory import InMemoryProfile
from ...core.profile import ProfileSession
Expand Down
3 changes: 1 addition & 2 deletions aries_cloudagent/askar/didcomm/v1.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,7 @@ async def unpack_message(session: Session, enc_message: bytes) -> Tuple[str, str


def _extract_payload_key(sender_cek: dict, recip_secret: Key) -> Tuple[bytes, str]:
"""
Extract the payload key from pack recipient details.
"""Extract the payload key from pack recipient details.
Returns: A tuple of the CEK and sender verkey
"""
Expand Down
3 changes: 1 addition & 2 deletions aries_cloudagent/askar/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,8 +176,7 @@ def session(self, context: InjectionContext = None) -> ProfileSession:
return AskarProfileSession(self, False, context=context)

def transaction(self, context: InjectionContext = None) -> ProfileSession:
"""
Start a new interactive session with commit and rollback support.
"""Start a new interactive session with commit and rollback support.
If the current backend does not support transactions, then commit
and rollback operations of the session will not have any effect.
Expand Down
9 changes: 3 additions & 6 deletions aries_cloudagent/askar/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@ class AskarStoreConfig:
KEY_DERIVATION_ARGON2I_MOD = "kdf:argon2i:mod"

def __init__(self, config: dict = None):
"""
Initialize a `AskarWallet` instance.
"""Initialize a `AskarWallet` instance.
Args:
config: {name, key, seed, did, auto_recreate, auto_remove,
Expand Down Expand Up @@ -118,8 +117,7 @@ def get_uri(self, create: bool = False) -> str:
return uri

async def remove_store(self):
"""
Remove an existing store.
"""Remove an existing store.
Raises:
ProfileNotFoundError: If the wallet could not be found
Expand All @@ -136,8 +134,7 @@ async def remove_store(self):
raise ProfileError("Error removing store") from err

async def open_store(self, provision: bool = False) -> "AskarOpenStore":
"""
Open a store, removing and/or creating it if so configured.
"""Open a store, removing and/or creating it if so configured.
Raises:
ProfileNotFoundError: If the store is not found
Expand Down
1 change: 0 additions & 1 deletion aries_cloudagent/askar/tests/test_profile.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import asyncio
import logging
import pytest

from asynctest import mock
Expand Down
15 changes: 5 additions & 10 deletions aries_cloudagent/cache/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ def __init__(self):

@abstractmethod
async def get(self, key: Text):
"""
Get an item from the cache.
"""Get an item from the cache.
Args:
key: the key to retrieve an item for
Expand All @@ -35,8 +34,7 @@ async def get(self, key: Text):
async def set(
self, keys: Union[Text, Sequence[Text]], value: Any, ttl: Optional[int] = None
):
"""
Add an item to the cache with an optional ttl.
"""Add an item to the cache with an optional ttl.
Args:
keys: the key or keys for which to set an item
Expand All @@ -47,8 +45,7 @@ async def set(

@abstractmethod
async def clear(self, key: Text):
"""
Remove an item from the cache, if present.
"""Remove an item from the cache, if present.
Args:
key: the key to remove
Expand Down Expand Up @@ -78,8 +75,7 @@ def __repr__(self) -> str:


class CacheKeyLock:
"""
A lock on a particular cache key.
"""A lock on a particular cache key.
Used to prevent multiple async threads from generating
or querying the same semi-expensive data. Not thread safe.
Expand Down Expand Up @@ -159,8 +155,7 @@ def release(self):
self.released = True

async def __aexit__(self, exc_type, exc_val, exc_tb):
"""
Async context manager exit.
"""Async context manager exit.
`None` is returned to any waiters if no value is produced.
"""
Expand Down
9 changes: 3 additions & 6 deletions aries_cloudagent/cache/in_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ def _remove_expired_cache_items(self):
del self._cache[key]

async def get(self, key: Text):
"""
Get an item from the cache.
"""Get an item from the cache.
Args:
key: the key to retrieve an item for
Expand All @@ -40,8 +39,7 @@ async def get(self, key: Text):
return self._cache.get(key)["value"] if self._cache.get(key) else None

async def set(self, keys: Union[Text, Sequence[Text]], value: Any, ttl: int = None):
"""
Add an item to the cache with an optional ttl.
"""Add an item to the cache with an optional ttl.
Overwrites existing cache entries.
Expand All @@ -57,8 +55,7 @@ async def set(self, keys: Union[Text, Sequence[Text]], value: Any, ttl: int = No
self._cache[key] = {"expires": expires_ts, "value": value}

async def clear(self, key: Text):
"""
Remove an item from the cache, if present.
"""Remove an item from the cache, if present.
Args:
key: the key to remove
Expand Down
2 changes: 1 addition & 1 deletion aries_cloudagent/cache/tests/test_in_memory_cache.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import pytest

from asyncio import ensure_future, sleep, wait_for
from asyncio import sleep, wait_for

from ..base import CacheError
from ..in_memory import InMemoryCache
Expand Down
1 change: 0 additions & 1 deletion aries_cloudagent/commands/tests/test_upgrade.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from asynctest import mock as async_mock, TestCase as AsyncTestCase

from ...core.in_memory import InMemoryProfile
from ...config.error import ArgsParseError
from ...connections.models.conn_record import ConnRecord
from ...storage.base import BaseStorage
from ...storage.record import StorageRecord
Expand Down
3 changes: 1 addition & 2 deletions aries_cloudagent/commands/upgrade.py
Original file line number Diff line number Diff line change
Expand Up @@ -385,8 +385,7 @@ async def upgrade(


async def update_existing_records(profile: Profile):
"""
Update existing records.
"""Update existing records.
Args:
profile: Root profile
Expand Down
Loading

0 comments on commit fa28560

Please sign in to comment.