Skip to content

Commit

Permalink
Fixed ruff linting issues
Browse files Browse the repository at this point in the history
  • Loading branch information
justalemon committed Mar 5, 2024
1 parent 3aa173e commit ce4b24d
Show file tree
Hide file tree
Showing 6 changed files with 164 additions and 81 deletions.
16 changes: 8 additions & 8 deletions leek/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def _get_int_safe(key: str, default: Optional[int] = None) -> Optional[int]:
except KeyError:
return None
except ValueError:
LOGGER.error(f"Environment variable {key} is not a valid number!")
LOGGER.exception("Environment variable %s is not a valid number!", key)
return None


Expand Down Expand Up @@ -76,32 +76,32 @@ def main() -> None:
split = name.split(":")

if len(split) != 2:
LOGGER.error(f"Cog name '{name}' is not in the right format")
LOGGER.error("Cog name '%s' is not in the right format", name)
continue

try:
imported = importlib.import_module(split[0])
except ModuleNotFoundError:
LOGGER.error(f"Unable to import '{name}' because it couldn't be found")
LOGGER.exception("Unable to import '%s' because it couldn't be found", name)
continue

if not hasattr(imported, split[1]):
LOGGER.error(f"Unable to load '{split[1]}' from '{split[1]} because the class does not exists")
LOGGER.error("Unable to load '%s' from '%s' because the class does not exists", split[1], split[1])
continue

cog = getattr(imported, split[1])

if not issubclass(cog, Cog):
LOGGER.error(f"Class '{name}' does not inherits from a Cog")
LOGGER.error("Class '%s' does not inherits from a Cog", name)
continue

try:
bot.add_cog(cog(bot))
except Exception: # noqa: BLE001
except Exception:
# We catch everything because we don't know what exception might be triggered
LOGGER.exception(f"Unable to start '{name}'")
LOGGER.exception("Unable to start '%s'", name)
finally:
LOGGER.info(f"Added cog {name}")
LOGGER.info("Added cog %s", name)

bot.run(os.environ["DISCORD_TOKEN"])

Expand Down
4 changes: 2 additions & 2 deletions leek/localization.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,10 @@ def __ensure_lang_file(path: Path, lang: str, log: bool) -> None:
lines: dict[str, str] = json.load(file)
except FileNotFoundError:
if log:
LOGGER.warning(f"Couldn't find {lang_path} for lang {lang}")
LOGGER.warning("Couldn't find %s for lang %s", lang_path, lang)
lines = {}
except json.JSONDecodeError:
LOGGER.exception(f"Unable to load {lang_path}")
LOGGER.exception("Unable to load %s", lang_path)
lines = {}

langs = PATHS.get(path, {})
Expand Down
108 changes: 65 additions & 43 deletions leek/modding/diagnoser.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
"""
Tool used to diagnose the SHVDN Log Files.
"""

import re

from discord import Cog, ApplicationContext, message_command, Message, Embed
from leek import LeekBot, get_default
from discord import ApplicationContext, Cog, Embed, Message, message_command

from leek import LeekBot, get_default

RE_SHVDN = re.compile("\\[[0-9]{2}:[0-9]{2}:[0-9]{2}] \\[(WARNING|ERROR)] (.*)")
RE_INSTANCE = re.compile("A script tried to use a custom script instance of type ([A-Za-z0-9_.]*) that was not "
Expand Down Expand Up @@ -30,12 +34,69 @@
ABORTED_SCRIPT = "Aborted script "


def get_problems(lines: list[str]) -> list[str]: # noqa: C901
"""
Gets the problems in the lines of a file.
"""
problems = []

for line in lines:
match = RE_SHVDN.search(line)

if match is None:
continue

level, details = match.groups()

if level not in LEVELS or details == FATAL_EXCEPTION or details.startswith(ABORTED_SCRIPT):
continue

emoji = LEVELS[level]
matched = False

for match, text in MATCHES.items():
if isinstance(match, re.Pattern):
matches = match.match(details)

if matches is None:
continue

message = f"{emoji} " + text.format(*matches.groups())
elif isinstance(match, str):
if not details.startswith(match):
continue

message = f"{emoji} {text}"
else:
continue

if message not in problems:
problems.append(message)

matched = True
break

if not matched:
problems.append(f"{emoji} Unknown ({details})")

return problems


class Diagnoser(Cog):
"""
A Cog used to diagnose log files of ScriptHookVDotNet.
"""
def __init__(self, bot: LeekBot):
"""
Creates a new diagnoser.
"""
self.bot = bot

@message_command(name=get_default("MODDING_MESSAGE_DIAGNOSE_NAME"))
async def diagnose(self, ctx: ApplicationContext, message: Message):
async def diagnose(self, ctx: ApplicationContext, message: Message) -> None:
"""
Tries to make a partial diagnostic of a SHVDN Log File.
"""
if not message.attachments:
await ctx.respond("There are no log files attached to this message.")
return
Expand All @@ -54,46 +115,7 @@ async def diagnose(self, ctx: ApplicationContext, message: Message):
content = await response.text()
lines = content.splitlines()

problems = []

for line in lines:
match = RE_SHVDN.search(line)

if match is None:
continue

level, details = match.groups()

if level not in LEVELS or details == FATAL_EXCEPTION or details.startswith(ABORTED_SCRIPT):
continue

emoji = LEVELS[level]
matched = False

for match, text in MATCHES.items():
if isinstance(match, re.Pattern):
matches = match.match(details)

if matches is None:
continue

message = f"{emoji} " + text.format(*matches.groups())
elif isinstance(match, str):
if not details.startswith(match):
continue

message = f"{emoji} {text}"
else:
continue

if message not in problems:
problems.append(message)

matched = True
break

if not matched:
problems.append(f"{emoji} Unknown ({details})")
problems = get_problems(lines)

if not problems:
await ctx.respond("Couldn't detect any issues with the log file.")
Expand Down
69 changes: 49 additions & 20 deletions leek/modding/rage.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
"""
Tools for helping with the modding of RAGE Games.
"""

import logging
import string

from aiohttp import ClientResponseError
from discord import Cog, ApplicationContext, slash_command, Option, AutocompleteContext, Embed
from leek import LeekBot, get_localizations, get_default
from discord import ApplicationContext, AutocompleteContext, Cog, Embed, Option, slash_command

from leek import LeekBot, get_default, get_localizations

LOGGER = logging.getLogger("leek_modding")
NATIVE_LINKS = {
Expand All @@ -15,22 +20,28 @@
CACHE = []


def format_lua_name(name: str):
def format_lua_name(name: str) -> str:
"""
Formats the name of a native to it's Lua compatible name.
"""
return string.capwords(name.lower().replace("0x", "N_0x").replace("_", " ")).replace(" ", "")


def format_params(params: dict):
def format_params(params: dict) -> str:
"""
Formats the parameters as a string.
"""
if params is None:
return ""

formatted = "\n "

for param in params:
type = param["type"]
name = param["name"]
p_type = param["type"]
p_name = param["name"]
description = param.get("description", None)

formatted += "`{0}: {1}`".format(name, type)
formatted += "`{0}: {1}`".format(p_name, p_type)

if description:
formatted += " {0}\n".format(description)
Expand All @@ -40,21 +51,30 @@ def format_params(params: dict):
return formatted


def find_native(name: str, game: str):
natives = NATIVES.get(game, None)
def find_native(name: str, game: str) -> dict | None:
"""
Finds a native by its partial name.
"""
natives = NATIVES.get(game)

if natives is None:
return None

return next((x for x in natives if x["hash"] == name or x["name"] == name), None)
return next((x for x in natives if name in (x["hash"], x["name"])), None)


async def get_natives(ctx: AutocompleteContext):
async def get_natives(ctx: AutocompleteContext) -> list[str]:
"""
Gets the native that match the partial lookup.
"""
query = ctx.value.upper()
return list(x for x in CACHE if query in x)
return [x for x in CACHE if query in x]


async def get_games(ctx: AutocompleteContext):
async def get_games(ctx: AutocompleteContext) -> list[str]: # noqa: ARG001
"""
Gets the list of available games.
"""
return list(NATIVES.keys())


Expand All @@ -63,10 +83,16 @@ class Rage(Cog):
Tools for Rockstar Advanced Game Engine modders.
"""
def __init__(self, bot: LeekBot):
"""
Creates a new RAGE Cog.
"""
self.bot: LeekBot = bot

@Cog.listener()
async def on_connect(self):
async def on_connect(self) -> None:
"""
Downloads the list of natives when connecting to Discord.
"""
for game, url in NATIVE_LINKS.items():
try:
async with await self.bot.get(url) as resp:
Expand All @@ -92,26 +118,29 @@ async def on_connect(self):
CACHE.append(n_hash)

if n_hash in NATIVES:
LOGGER.warning(f"Found Duplicated Native: {n_hash}/{name}")
LOGGER.warning("Found Duplicated Native: %s/%s", n_hash, name)

ready.append(native)

NATIVES[game] = ready

CACHE.sort(reverse=True)
except ClientResponseError as e:
LOGGER.exception(f"Can't request {url}: Code {e.status}")
LOGGER.exception("Can't request %s: Code %s", url, e.status)
except BaseException:
LOGGER.exception(f"Unable to get {game} natives from {url}")
LOGGER.exception("Unable to get %s natives from %s", game, url)

LOGGER.info("Finished fetching the natives")

@slash_command(name_localizations=get_localizations("MODDING_COMMAND_NATIVE_NAME"),
description=get_default("MODDING_COMMAND_NATIVE_DESC"),
description_localizations=get_localizations("MODDING_COMMAND_NATIVE_DESC"),)
description_localizations=get_localizations("MODDING_COMMAND_NATIVE_DESC"))
async def native(self, ctx: ApplicationContext, name: Option(str, "The name to search", autocomplete=get_natives),
game: Option(str, "The game for this native", default="gtav", # noqa: F821
autocomplete=get_games)):
game: Option(str, "The game for this native", default="gtav",
autocomplete=get_games)) -> None:
"""
Searches for the documentation of a native.
"""
found = find_native(name, game)

if found is None:
Expand Down
1 change: 1 addition & 0 deletions leek/moderation/moderation.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from typing import Optional

from discord import ApplicationContext, Cog, Forbidden, HTTPException, Message, NotFound, Permissions, slash_command

from leek import LeekBot, get_default, get_localizations, localize

LOGGER = logging.getLogger("leek_moderation")
Expand Down
Loading

0 comments on commit ce4b24d

Please sign in to comment.