Skip to content

Commit

Permalink
Upgrade tooling to use ruff+black over isort/black (#59)
Browse files Browse the repository at this point in the history
* Add recommended extensions for tooling

* update deps for ruff

* run ruff

* add git blame ignore revs

* fix gh action to use ruff
  • Loading branch information
AbstractUmbra authored Oct 21, 2023
1 parent 8d3b308 commit 8a527d9
Show file tree
Hide file tree
Showing 32 changed files with 416 additions and 375 deletions.
2 changes: 2 additions & 0 deletions .git-blame-ignore-revs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# run ruff
174ab9e3d7bc643805ac97acf71a225dd9523977
12 changes: 2 additions & 10 deletions .github/workflows/coverage_and_lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,5 @@ jobs:
no-comments: ${{ matrix.python-version != '3.x' }}

- name: Lint
uses: github/super-linter/slim@v4
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
DEFAULT_BRANCH: main
VALIDATE_ALL_CODEBASE: false
VALIDATE_PYTHON_BLACK: true
VALIDATE_PYTHON_ISORT: true
LINTER_RULES_PATH: /
PYTHON_ISORT_CONFIG_FILE: pyproject.toml
PYTHON_BLACK_CONFIG_FILE: pyproject.toml
if: ${{ always() && steps.install-deps.outcome == 'success' }}
uses: chartboost/ruff-action@v1
8 changes: 8 additions & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"recommendations": [
"ms-python.python",
"ms-python.vscode-pylance",
"charliermarsh.ruff",
"ms-python.black-formatter"
]
}
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ which will enable all services and snekbox.

This also means that it will use internal docker networking to resolve the database and snekbox names. By default these will be `database` and `snekbox`, but these will be the **service names** in `docker-compose.yml` if you change them. Please keep this in mind when editing your config file.

We also provide a file for ignoring git blame references. You can enable this with:-
```sh
git config blame.ignoreRevsFile .git-blame-ignore-revs
```

### Support

As this bot is not really designed for use outside of our Guild, support provided will be **very** limited.
Expand Down
1 change: 0 additions & 1 deletion constants/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,4 @@
"""
from .constants import *


GUILD_ID: int = 490948346773635102
1 change: 0 additions & 1 deletion constants/_meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@

import toml


if TYPE_CHECKING:
from typing_extensions import Self

Expand Down
1 change: 0 additions & 1 deletion constants/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
"""
from ._meta import CONSTANTS


__all__ = (
"Roles",
"Colours",
Expand Down
12 changes: 6 additions & 6 deletions core/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,24 +31,24 @@
from collections import deque
from typing import TYPE_CHECKING, Any

import aiohttp
import asyncpg
import discord
from discord.ext import commands
from discord.ext.commands.cog import Cog # type: ignore # stubs

from constants import GUILD_ID

from .context import Context
from .core import CONFIG
from .utils import LogHandler


if TYPE_CHECKING:
from asyncio import Queue
from logging import LogRecord

import aiohttp
import asyncpg
import mystbin
from discord.ext.commands.cog import Cog # type: ignore # stubs

from .utils import LogHandler


class Bot(commands.Bot):
Expand All @@ -67,7 +67,7 @@ class Bot(commands.Bot):
"_previous_websocket_events",
)

def __init__(self):
def __init__(self) -> None:
super().__init__(
command_prefix=commands.when_mentioned_or(CONFIG["prefix"]),
intents=discord.Intents.all(),
Expand Down
4 changes: 2 additions & 2 deletions core/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,12 @@
from discord.ext import commands

import constants
from core.context import GuildContext


if TYPE_CHECKING:
from discord.ext.commands._types import Check # type: ignore # why would this need stubs

from core.context import GuildContext


def is_role_or_higher(role_id: int) -> Check[Any]:
def predicate(ctx: GuildContext) -> bool:
Expand Down
1 change: 0 additions & 1 deletion core/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

from constants import GUILD_ID, Roles


if TYPE_CHECKING:
from .bot import Bot

Expand Down
1 change: 0 additions & 1 deletion core/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@

from core.context import Context


__all__ = ("Codeblock", "CodeblockConverter")


Expand Down
1 change: 0 additions & 1 deletion core/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
import toml
from discord.ext import commands


if TYPE_CHECKING:
from types_.config import Config

Expand Down
1 change: 0 additions & 1 deletion core/enums.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from discord.enums import Enum


__all__ = ("DiscordPyModerationEvent",)


Expand Down
1 change: 0 additions & 1 deletion core/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
"""
from discord.ext import commands


__all__ = ("InvalidEval",)


Expand Down
3 changes: 1 addition & 2 deletions core/utils/formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
from discord import Colour
from discord.utils import escape_markdown


__all__ = (
"to_codeblock",
"random_pastel_colour",
Expand All @@ -38,7 +37,7 @@ def to_codeblock(
replace_existing: bool = True,
escape_md: bool = True,
new: str = "'''",
):
) -> str:
"""
Quick function to put our content into a Discord accepted codeblock.
"""
Expand Down
1 change: 0 additions & 1 deletion core/utils/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

import core


if TYPE_CHECKING:
from typing_extensions import Self

Expand Down
21 changes: 10 additions & 11 deletions core/utils/paginator.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,12 @@
from discord.ext.commands import CommandError, Paginator as _Paginator # type: ignore # why does this need a stub file?
from discord.utils import MISSING

from core import Bot, Context


if TYPE_CHECKING:
from discord.abc import MessageableChannel
from typing_extensions import Self

from core import Bot, Context


__all__ = ("CannotPaginate", "Pager", "KVPager", "TextPager")

Expand All @@ -63,7 +62,7 @@ def __init__(
author_url: str | None = None,
stop: bool = False,
reply_author_takes_paginator: bool = False,
):
) -> None:
super().__init__()
self.bot: Bot = ctx.bot
self.stoppable: bool = stop
Expand Down Expand Up @@ -117,7 +116,7 @@ def __init__(
def setup_buttons(self) -> None:
self.clear_items()
for emoji, button in self.reaction_emojis:
btn = ui.Button[Self](emoji=emoji)
btn = ui.Button["Self"](emoji=emoji)
btn.callback = button # type: ignore
self.add_item(btn)

Expand Down Expand Up @@ -175,7 +174,7 @@ async def show_page(

self.message = await self.channel.send(content=content, embed=embed, view=self)

async def checked_show_page(self, page: int):
async def checked_show_page(self, page: int) -> None:
if page != 0 and page <= self.maximum_pages:
await self.show_page(page)

Expand Down Expand Up @@ -226,7 +225,7 @@ def message_check(m: discord.Message) -> bool:
except (AttributeError, discord.HTTPException):
pass

async def stop_pages(self, interaction: discord.Interaction | None = None):
async def stop_pages(self, interaction: discord.Interaction | None = None) -> None:
"""stops the interactive pagination session"""
if self.delete_after and self.message:
await self.message.delete()
Expand All @@ -235,7 +234,7 @@ async def stop_pages(self, interaction: discord.Interaction | None = None):

stop = stop_pages # type: ignore

def _check(self, interaction: discord.Interaction):
def _check(self, interaction: discord.Interaction) -> bool:
if interaction.user.id != self.author.id:
return False

Expand All @@ -249,7 +248,7 @@ async def interaction_check(self, interaction: discord.Interaction) -> bool:

return resp

async def paginate(self, msg_kwargs: dict[str, Any] | None = None):
async def paginate(self, msg_kwargs: dict[str, Any] | None = None) -> None:
if self.maximum_pages > 1:
self.paginating = True

Expand All @@ -276,7 +275,7 @@ def __init__(
title: str | None = None,
embed_color: discord.Colour = discord.Colour.blurple(),
**kwargs: Any,
):
) -> None:
super().__init__(
ctx,
entries=entries,
Expand All @@ -288,7 +287,7 @@ def __init__(
)
self.description = description

def prepare_embed(self, entries: list[Any], page: int, *, first: bool = False):
def prepare_embed(self, entries: list[Any], page: int, *, first: bool = False) -> None:
self.embed.clear_fields()
self.embed.description = self.description or MISSING
self.embed.title = self.title or MISSING
Expand Down
1 change: 0 additions & 1 deletion modules/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import pathlib
from pkgutil import ModuleInfo, iter_modules


_ext: list[ModuleInfo] = []
_ext.extend(
[
Expand Down
1 change: 0 additions & 1 deletion modules/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
from constants import GUILD_ID
from core.context import Context


LOGGER = logging.getLogger(__name__)


Expand Down
19 changes: 9 additions & 10 deletions modules/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
PAPIWebsocketSubscriptions,
)


LOGGER = logging.getLogger(__name__)


Expand Down Expand Up @@ -69,7 +68,7 @@ async def cog_unload(self) -> None:
try:
self.connection_task.cancel()
except Exception as e:
LOGGER.error(f'Unable to cancel Pythonista API connection_task in "cog_unload": {e}')
LOGGER.error('Unable to cancel Pythonista API connection_task in "cog_unload": %s', e)

if self.is_connected():
assert self.websocket
Expand All @@ -79,7 +78,7 @@ async def cog_unload(self) -> None:
try:
self.keep_alive_task.cancel()
except Exception as e:
LOGGER.error(f'Unable to cancel Pythonista API keep_alive_task in "cog_unload": {e}')
LOGGER.error('Unable to cancel Pythonista API keep_alive_task in "cog_unload": %s', e)

def dispatch(self, *, data: dict[str, Any]) -> None:
subscription: str = data["subscription"]
Expand All @@ -99,7 +98,7 @@ async def connect(self) -> None:
try:
self.keep_alive_task.cancel()
except Exception as e:
LOGGER.warning(f"Failed to cancel Pythonista API Websocket keep alive. This is likely not a problem: {e}")
LOGGER.warning("Failed to cancel Pythonista API Websocket keep alive. This is likely not a problem: %s", e)

while True:
try:
Expand All @@ -109,13 +108,13 @@ async def connect(self) -> None:
LOGGER.critical("Unable to connect to Pythonista API Websocket, due to an incorrect token.")
return
else:
LOGGER.error(f"Unable to connect to Pythonista API Websocket: {e}.")
LOGGER.error("Unable to connect to Pythonista API Websocket: %s.", e)

if self.is_connected():
break
else:
delay: float = self.backoff.delay() # type: ignore
LOGGER.warning(f'Retrying Pythonista API Websocket connection in "{delay}" seconds.')
LOGGER.warning("Retrying Pythonista API Websocket connection in '%s' seconds.", delay)

await asyncio.sleep(delay)

Expand Down Expand Up @@ -149,7 +148,7 @@ async def keep_alive(self) -> None:
op: int | None = data.get("op")

if op == PAPIWebsocketOPCodes.HELLO:
LOGGER.debug(f'Received HELLO from Pythonista API: user={data["user_id"]}')
LOGGER.debug("Received HELLO from Pythonista API: user=%s", data["user_id"])

elif op == PAPIWebsocketOPCodes.EVENT:
self.dispatch(data=data)
Expand All @@ -159,12 +158,12 @@ async def keep_alive(self) -> None:

if type_ == PAPIWebsocketNotificationTypes.SUBSCRIPTION_ADDED:
subscribed: str = ", ".join(data["subscriptions"])
LOGGER.info(f"Pythonista API added our subscription, currently subscribed: `{subscribed}`")
LOGGER.info("Pythonista API added our subscription, currently subscribed: `%s`", subscribed)
elif type_ == PAPIWebsocketNotificationTypes.SUBSCRIPTION_REMOVED:
subscribed: str = ", ".join(data["subscriptions"])
LOGGER.info(f"Pythonista API removed our subscription, currently subscribed: `{subscribed}`")
LOGGER.info("Pythonista API removed our subscription, currently subscribed: `%s`", subscribed)
elif type_ == PAPIWebsocketNotificationTypes.UNKNOWN_OP:
LOGGER.info(f'We sent an UNKNOWN OP to Pythonista API: `{data["received"]}`')
LOGGER.info("We sent an UNKNOWN OP to Pythonista API: `%s`", data["received"])

else:
LOGGER.info("Received an UNKNOWN OP from Pythonista API.")
Expand Down
1 change: 0 additions & 1 deletion modules/eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
from core.errors import InvalidEval
from core.utils import formatters


LOGGER = logging.getLogger(__name__)


Expand Down
8 changes: 4 additions & 4 deletions modules/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
import constants
import core


GITHUB_ISSUE_URL = "https://github.com/{}/issues/{}"
LIB_ISSUE_REGEX = re.compile(r"(?P<lib>[a-z]+)?(?P<pounds>#{2,})(?P<number>[0-9]+)", flags=re.IGNORECASE)
GITHUB_CODE_REGION_REGEX = re.compile(
Expand Down Expand Up @@ -166,8 +165,9 @@ async def format_highlight_block(self, url: str, line_adjustment: int = 10) -> d

github_dict = {
"path": file_path,
"min": (_min_boundary if _min_boundary > 0 else highlighted_line - 1)
+ 1, # Do not display negative numbers if <0
"min": (
_min_boundary if _min_boundary > 0 else highlighted_line - 1
) + 1, # Do not display negative numbers if <0
"max": _max_boundary + 1,
"msg": msg,
}
Expand All @@ -182,7 +182,7 @@ def _smart_guess_lib(self, msg: discord.Message) -> LibEnum | None:
return None # there's not much hope here, stay quick

if isinstance(msg.channel, discord.Thread) and msg.channel.parent_id == constants.Channels.HELP_FORUM:
tags = set(x.name for x in msg.channel.applied_tags)
tags = {x.name for x in msg.channel.applied_tags}

if "twitchio-help" in tags:
return LibEnum.twitchio
Expand Down
Loading

0 comments on commit 8a527d9

Please sign in to comment.