Skip to content

Commit

Permalink
gh-11: Initial ruff linting/formatting and uv support
Browse files Browse the repository at this point in the history
  • Loading branch information
monkeyman192 committed Oct 10, 2024
1 parent e273461 commit e5a4e0f
Show file tree
Hide file tree
Showing 25 changed files with 3,647 additions and 336 deletions.
26 changes: 14 additions & 12 deletions pymhf/__init__.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
from importlib.metadata import version, PackageNotFoundError, entry_points
import configparser
import argparse
import configparser
import os
import os.path as op
import shutil
from importlib.metadata import PackageNotFoundError, entry_points, version

from .main import load_module # noqa
import questionary

from .core._types import FUNCDEF # noqa
from .core.hooking import FuncHook # noqa
from .core.mod_loader import Mod, ModState # noqa
from .core._types import FUNCDEF # noqa

import questionary
from .main import load_module # noqa

try:
__version__ = version("pymhf")
Expand All @@ -21,7 +21,7 @@
def _is_int(val: str) -> bool:
try:
int(val)
except:
except (ValueError, TypeError):
return False
return True

Expand Down Expand Up @@ -53,12 +53,12 @@ def _is_int(val: str) -> bool:
# Need to support the following commands:
# --config -> will configure the library
def run():
""" Main entrypoint which can be used to run programs with pymhf.
"""Main entrypoint which can be used to run programs with pymhf.
This will take the first argument as the name of a module which has been installed."""

parser = argparse.ArgumentParser(
prog="pyMHF program runner",
description='Run the registered plugin',
description="Run the registered plugin",
)
parser.add_argument("plugin_name")
parser.add_argument(
Expand Down Expand Up @@ -105,10 +105,12 @@ def run():
required_lib = lib

if required_lib is None:
print(f"Cannot find {plugin_name} as an installed plugin. "
"Please ensure it has been installed and try again")
print(
f"Cannot find {plugin_name} as an installed plugin. "
"Please ensure it has been installed and try again"
)
return

loaded_lib = required_lib.load()
initial_config = False

Expand Down
2 changes: 1 addition & 1 deletion pymhf/_preinject.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
# injected.
# For the most part this imports stuff so that the import cache is primed so
# that any subsequent imports do not overwrite the existing data.
import pymhf.core._internal
import pymhf.core._internal # noqa
2 changes: 1 addition & 1 deletion pymhf/core/_internal.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def __init__(self):
@property
def game_loaded(self):
return self._game_loaded

@game_loaded.setter
def game_loaded(self, val: bool):
# The game can become loaded, but it can't become unloaded...
Expand Down
6 changes: 2 additions & 4 deletions pymhf/core/_types.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from collections import namedtuple
from enum import Enum
from typing import Any, Callable, Optional, Protocol

from typing import Any, Optional, Protocol

FUNCDEF = namedtuple("FUNCDEF", ["restype", "argtypes"])

Expand All @@ -26,8 +25,7 @@ class HookProtocol(Protocol):
_custom_trigger: Optional[str]
_func_overload: Optional[str]

def __call__(self, *args: Any, **kwargs: Any) -> Any:
...
def __call__(self, *args: Any, **kwargs: Any) -> Any: ...


class ManualHookProtocol(HookProtocol):
Expand Down
23 changes: 9 additions & 14 deletions pymhf/core/caching.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
# A collection of functions which will hash and cache things.

import hashlib
from io import BufferedReader
import json
import os
import os.path as op
from io import BufferedReader
from typing import Optional

from pymem.ressources.structure import MODULEINFO

import pymhf.core._internal as _internal


CACHE_DIR = ".cache"


def hash_bytes(fileobj: BufferedReader, _bufsize: int = 2 ** 18) -> str:
def hash_bytes(fileobj: BufferedReader, _bufsize: int = 2**18) -> str:
# Essentially implement hashlib.file_digest since it's python 3.11+
# cf. https://github.com/python/cpython/blob/main/Lib/hashlib.py#L195
digestobj = hashlib.sha1()
Expand All @@ -29,38 +28,34 @@ def hash_bytes(fileobj: BufferedReader, _bufsize: int = 2 ** 18) -> str:
return digestobj.hexdigest()


class OffsetCache():
class OffsetCache:
def __init__(self, path: str):
self._path = path
self._binary_hash: Optional[str] = None
self._lookup: dict[str, int] = {}

@property
def path(self) -> str:
return op.join(
_internal.CWD,
CACHE_DIR,
f"{self._binary_hash}_{self._path}.json"
)
return op.join(_internal.CWD, CACHE_DIR, f"{self._binary_hash}_{self._path}.json")

def load(self, binary_hash: str):
""" Load the data. """
"""Load the data."""
self._binary_hash = binary_hash
if op.exists(self.path):
with open(self.path, "r") as f:
self._lookup = json.load(f)
self._lookup = json.load(f)

def save(self):
""" Persist the cache to disk. """
"""Persist the cache to disk."""
with open(self.path, "w") as f:
json.dump(self._lookup, f)

def get(self, name: str) -> Optional[int]:
""" Get the offset based on the key provided. """
"""Get the offset based on the key provided."""
return self._lookup.get(name)

def set(self, key: str, value: int, save: bool = True):
""" Set the key with the given value and optionally save."""
"""Set the key with the given value and optionally save."""
self._lookup[key] = value
if save:
self.save()
Expand Down
28 changes: 9 additions & 19 deletions pymhf/core/calling.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
from ctypes import CFUNCTYPE
from logging import getLogger
from typing import Optional, Any
from typing import Any, Optional

import pymhf.core._internal as _internal
from pymhf.core.module_data import module_data
from pymhf.core._types import FUNCDEF
from pymhf.core.memutils import find_pattern_in_binary

from pymhf.core.module_data import module_data

calling_logger = getLogger("CallingManager")

Expand All @@ -18,7 +17,7 @@ def call_function(
pattern: Optional[str] = None,
func_def: Optional[FUNCDEF] = None,
) -> Any:
""" Call a named function.
"""Call a named function.
Parameters
----------
Expand Down Expand Up @@ -48,11 +47,8 @@ def call_function(
offset = find_pattern_in_binary(opattern, False)
else:
first = list(_pattern.items())[0]
calling_logger.warning(
f"No pattern overload was provided for {name}. "
)
calling_logger.warning(
f"Falling back to the first overload ({first[0]})")
calling_logger.warning(f"No pattern overload was provided for {name}. ")
calling_logger.warning(f"Falling back to the first overload ({first[0]})")
offset = find_pattern_in_binary(first[1], False)
else:
offset = module_data.FUNC_OFFSETS.get(name)
Expand All @@ -69,23 +65,17 @@ def call_function(
# overload was defined and that it will fallback to the
# first entry in the dict.
first = list(_sig.items())[0]
calling_logger.warning(
f"No function arguments overload was provided for {name}. "
)
calling_logger.warning(
f"Falling back to the first overload ({first[0]})")
calling_logger.warning(f"No function arguments overload was provided for {name}. ")
calling_logger.warning(f"Falling back to the first overload ({first[0]})")
sig = CFUNCTYPE(first[1].restype, *first[1].argtypes)
if isinstance(offset, dict):
# Handle overloads
if (_offset := offset.get(overload)) is not None: # type: ignore
offset = _offset
else:
_offset = list(offset.items())[0]
calling_logger.warning(
f"No function arguments overload was provided for {name}. "
)
calling_logger.warning(
f"Falling back to the first overload ({_offset[0]})")
calling_logger.warning(f"No function arguments overload was provided for {name}. ")
calling_logger.warning(f"Falling back to the first overload ({_offset[0]})")
offset = _offset[1]

cfunc = sig(_internal.BASE_ADDRESS + offset)
Expand Down
2 changes: 1 addition & 1 deletion pymhf/core/common.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from concurrent.futures import ThreadPoolExecutor
import os
import os.path as op
from concurrent.futures import ThreadPoolExecutor

import pymhf.core._internal as _internal

Expand Down
Loading

0 comments on commit e5a4e0f

Please sign in to comment.