Skip to content

Commit 36fbf7f

Browse files
committed
ci: replace flake8 with ruff (#1300)
* ci: define ruff config * refactor: run ruff autofix * ci: add D404 & D203 to excludes * refactor: resolve remaining ruff warnings * ci: replace autoflake and flake8 with ruff
1 parent 3534b23 commit 36fbf7f

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

51 files changed

+343
-304
lines changed

.pre-commit-config.yaml

Lines changed: 10 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -30,44 +30,26 @@ repos:
3030
name: TOML Structure
3131
- id: check-merge-conflict
3232
name: Merge Conflicts
33+
- repo: https://github.com/charliermarsh/ruff-pre-commit
34+
rev: 'v0.0.254'
35+
hooks:
36+
- id: ruff
37+
args: [--fix, --exit-non-zero-on-fix]
3338
- repo: https://github.com/psf/black
3439
rev: 23.1.0
3540
hooks:
36-
- id: black
37-
name: Black Formatting
38-
language: python
39-
types: [file, python]
40-
language_version: python3.10
41-
- repo: https://github.com/PyCQA/flake8
42-
rev: 6.0.0
43-
hooks:
44-
- id: flake8
45-
name: flake8 Formatting
46-
language: python
47-
types: [file, python]
48-
args: [--ignore=E203 E301 E302 E501 E402 E704 W503 W504]
49-
additional_dependencies:
50-
- flake8-annotations
51-
- flake8-bandit
52-
- flake8-docstrings
53-
- flake8-bugbear
54-
- flake8-comprehensions
55-
- flake8-raise
56-
- flake8-deprecated
57-
- flake8-print
58-
- git+https://github.com/python-formate/flake8-dunder-all
59-
language_version: python3.10
41+
- id: black
42+
name: Black Formatting
43+
language: python
44+
types: [ file, python ]
45+
language_version: python3.10
6046
# - repo: https://github.com/pycqa/isort
6147
# rev: 5.11.4
6248
# hooks:
6349
# - id: isort
6450
# name: isort Formatting
6551
# language: python
6652
# types: [file, python]
67-
- repo: https://github.com/PyCQA/autoflake
68-
rev: v2.0.0
69-
hooks:
70-
- id: autoflake
7153
ci:
7254
autoupdate_branch: "unstable"
7355
autofix_prs: true

interactions/api/events/processors/guild_events.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,11 @@ async def _on_raw_guild_create(self, event: "RawGatewayEvent") -> None:
4040

4141
guild = self.cache.place_guild_data(event.data)
4242

43-
self._user._guild_ids.add(to_snowflake(event.data.get("id"))) # noqa : w0212
43+
self._user._guild_ids.add(to_snowflake(event.data.get("id")))
4444

4545
self._guild_event.set()
4646

47-
if self.fetch_members and not guild.chunked.is_set(): # noqa
47+
if self.fetch_members and not guild.chunked.is_set():
4848
# delays events until chunking has completed
4949
await guild.chunk()
5050

interactions/api/gateway/gateway.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
"""This file outlines the interaction between interactions and Discord's Gateway API."""
1+
"""Outlines the interaction between interactions and Discord's Gateway API."""
22
import asyncio
33
import sys
44
import time
@@ -160,7 +160,7 @@ async def run(self) -> None:
160160
self.sequence = seq
161161

162162
if op == OPCODE.DISPATCH:
163-
asyncio.create_task(self.dispatch_event(data, seq, event))
163+
_ = asyncio.create_task(self.dispatch_event(data, seq, event))
164164
continue
165165

166166
# This may try to reconnect the connection so it is best to wait
@@ -215,17 +215,19 @@ async def dispatch_event(self, data, seq, event) -> None:
215215
case "RESUMED":
216216
self.logger.info(f"Successfully resumed connection! Session_ID: {self.session_id}")
217217
self.state.client.dispatch(events.Resume())
218-
return
218+
return None
219219

220220
case "GUILD_MEMBERS_CHUNK":
221-
asyncio.create_task(self._process_member_chunk(data.copy()))
221+
_ = asyncio.create_task(self._process_member_chunk(data.copy()))
222222

223223
case _:
224224
# the above events are "special", and are handled by the gateway itself, the rest can be dispatched
225225
event_name = f"raw_{event.lower()}"
226226
if processor := self.state.client.processors.get(event_name):
227227
try:
228-
asyncio.create_task(processor(events.RawGatewayEvent(data.copy(), override_name=event_name)))
228+
_ = asyncio.create_task(
229+
processor(events.RawGatewayEvent(data.copy(), override_name=event_name))
230+
)
229231
except Exception as ex:
230232
self.logger.error(f"Failed to run event processor for {event_name}: {ex}")
231233
else:

interactions/api/gateway/state.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,9 +117,9 @@ async def _ws_connect(self) -> None:
117117
except WebSocketClosed as ex:
118118
if ex.code == 4011:
119119
raise NaffException("Your bot is too large, you must use shards") from None
120-
elif ex.code == 4013:
120+
if ex.code == 4013:
121121
raise NaffException(f"Invalid Intents have been passed: {self.intents}") from None
122-
elif ex.code == 4014:
122+
if ex.code == 4014:
123123
raise NaffException(
124124
"You have requested privileged intents that have not been enabled or approved. Check the developer dashboard"
125125
) from None

interactions/api/gateway/websocket.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,7 @@ def average_latency(self) -> float:
118118
"""Get the average latency of the connection (seconds)."""
119119
if self._latency:
120120
return sum(self._latency) / len(self._latency)
121-
else:
122-
return float("inf")
121+
return float("inf")
123122

124123
@property
125124
def latency(self) -> float:
@@ -197,7 +196,7 @@ async def receive(self, force: bool = False) -> str:
197196
await self.reconnect(code=resp.data, resume=resp.data != 1000)
198197
continue
199198

200-
elif resp.type is WSMsgType.CLOSED:
199+
if resp.type is WSMsgType.CLOSED:
201200
if force:
202201
raise RuntimeError("Discord unexpectedly closed the underlying socket during force receive!")
203202

interactions/api/http/http_client.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ def set_reset_time(self, delta: float) -> None:
7676
Sets the reset time to the current time + delta.
7777
7878
To be called if a 429 is received.
79+
7980
Args:
8081
delta: The time to wait before resetting the calls.
8182
"""
@@ -373,7 +374,7 @@ async def request(
373374
)
374375
await lock.defer_unlock() # lock this route and wait for unlock
375376
continue
376-
elif lock.remaining == 0:
377+
if lock.remaining == 0:
377378
# Last call available in the bucket, lock until reset
378379
self.log_ratelimit(
379380
self.logger.debug,
@@ -407,12 +408,11 @@ async def _raise_exception(self, response, route, result) -> None:
407408

408409
if response.status == 403:
409410
raise Forbidden(response, response_data=result, route=route)
410-
elif response.status == 404:
411+
if response.status == 404:
411412
raise NotFound(response, response_data=result, route=route)
412-
elif response.status >= 500:
413+
if response.status >= 500:
413414
raise DiscordError(response, response_data=result, route=route)
414-
else:
415-
raise HTTPException(response, response_data=result, route=route)
415+
raise HTTPException(response, response_data=result, route=route)
416416

417417
def log_ratelimit(self, log_func: Callable, message: str) -> None:
418418
"""

interactions/api/http/http_requests/threads.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -198,10 +198,9 @@ async def create_thread(
198198
payload=payload,
199199
reason=reason,
200200
)
201-
else:
202-
payload["type"] = thread_type or ChannelType.GUILD_PUBLIC_THREAD
203-
payload["invitable"] = invitable
204-
return await self.request(Route("POST", f"/channels/{channel_id}/threads"), payload=payload, reason=reason)
201+
payload["type"] = thread_type or ChannelType.GUILD_PUBLIC_THREAD
202+
payload["invitable"] = invitable
203+
return await self.request(Route("POST", f"/channels/{channel_id}/threads"), payload=payload, reason=reason)
205204

206205
async def create_forum_thread(
207206
self,

interactions/api/voice/audio.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import audioop
22
import shutil
3-
import subprocess # noqa: S404
3+
import subprocess
44
import threading
55
import time
66
from abc import ABC, abstractmethod
@@ -88,7 +88,7 @@ def read(self, frame_size: int) -> bytes:
8888
"""
8989
Reads frame_size ms of audio from source.
9090
91-
returns:
91+
Returns:
9292
bytes of audio
9393
"""
9494
...
@@ -199,9 +199,7 @@ def _create_process(self, *, block: bool = True) -> None:
199199
cmd[1:1] = before
200200
cmd.extend(after)
201201

202-
self.process = subprocess.Popen( # noqa: S603
203-
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.DEVNULL
204-
)
202+
self.process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.DEVNULL)
205203
self.read_ahead_task.start()
206204

207205
if block:
@@ -246,7 +244,7 @@ def read(self, frame_size: int) -> bytes:
246244
"""
247245
Reads frame_size bytes of audio from the buffer.
248246
249-
returns:
247+
Returns:
250248
bytes of audio
251249
"""
252250
if not self.process:
@@ -293,7 +291,7 @@ def read(self, frame_size: int) -> bytes:
293291
"""
294292
Reads frame_size ms of audio from source.
295293
296-
returns:
294+
Returns:
297295
bytes of audio
298296
"""
299297
data = super().read(frame_size)

interactions/api/voice/voice_gateway.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ async def receive(self, force=False) -> str:
115115
continue
116116
raise VoiceWebSocketClosed(resp.data)
117117

118-
elif resp.type is WSMsgType.CLOSED:
118+
if resp.type is WSMsgType.CLOSED:
119119
if force:
120120
raise RuntimeError("Discord unexpectedly closed the underlying socket during force receive!")
121121

@@ -216,7 +216,7 @@ async def reconnect(self, *, resume: bool = False, code: int = 1012) -> None:
216216
self._kill_bee_gees.set()
217217
self.close()
218218
self.logger.debug("Terminating VoiceGateway due to disconnection")
219-
return
219+
return None
220220

221221
self._voice_server_update.clear()
222222

interactions/client/auto_shard_client.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,7 @@ def latency(self) -> float:
6060
if len(self._connection_states):
6161
latencies = sum((g.latency for g in self._connection_states))
6262
return latencies / len(self._connection_states)
63-
else:
64-
return float("inf")
63+
return float("inf")
6564

6665
@property
6766
def latencies(self) -> dict[int, float]:

0 commit comments

Comments
 (0)