Skip to content

Commit

Permalink
Updating pre-commit and running pylint/pyright
Browse files Browse the repository at this point in the history
  • Loading branch information
JanEricNitschke committed Jun 23, 2024
1 parent 3aedb12 commit cdc3ed9
Show file tree
Hide file tree
Showing 16 changed files with 184 additions and 146 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ jobs:
- name: Install Poetry
uses: abatilo/actions-poetry@v2

- name: Setup a local virtual environment for poetry
shell: bash
run: |
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ jobs:
- name: Install awpy
run: |
poetry install --no-interaction
- name: Publish to PyPI
run: |
poetry publish --build --username __token__ --password ${{ secrets.PYPI_API_TOKEN }} -vvv
poetry publish --build --username __token__ --password ${{ secrets.PYPI_API_TOKEN }} -vvv
20 changes: 11 additions & 9 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
exclude: docs/
repos:
# - repo: https://github.com/JanEricNitschke/pymend
# rev: "v1.0.10"
# hooks:
# - id: pymend
# language: python
# args: ["--write", "--check"]
- repo: 'https://github.com/pre-commit/pre-commit-hooks'
rev: v4.4.0
hooks:
Expand All @@ -25,18 +31,14 @@ repos:
language: python
- id: check-builtin-literals
language: python
- repo: 'https://github.com/charliermarsh/ruff-pre-commit'
rev: v0.0.291
- repo: "https://github.com/charliermarsh/ruff-pre-commit"
rev: v0.4.9
hooks:
- id: ruff
args:
- '--fix'
- '--exit-non-zero-on-fix'
- repo: 'https://github.com/psf/black'
rev: 23.9.1
hooks:
- id: black
language: python
- "--fix"
- "--exit-non-zero-on-fix"
- id: ruff-format
- repo: https://github.com/crate-ci/typos
rev: v1.16.13
hooks:
Expand Down
2 changes: 1 addition & 1 deletion .readthedocs.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,4 @@ build:
- VIRTUAL_ENV=$READTHEDOCS_VIRTUALENV_PATH poetry install

sphinx:
configuration: docs/conf.py
configuration: docs/conf.py
13 changes: 8 additions & 5 deletions awpy/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,12 @@ def get(resource_type: Literal["usd"], resource_name: str) -> None:


@awpy.command(help="Parse a Counter-Strike 2 demo file.")
@click.argument("demo", type=click.Path(exists=True))
@click.option("--outpath", type=click.Path(), help="Path to save the compressed demo.")
@click.argument("demo_path", type=click.Path(exists=True, path_type=Path))
@click.option(
"--outpath",
type=click.Path(path_type=Path),
help="Path to save the compressed demo.",
)
@click.option("--verbose", is_flag=True, default=False, help="Enable verbose mode.")
@click.option("--noticks", is_flag=True, default=False, help="Disable tick parsing.")
@click.option(
Expand All @@ -45,7 +49,7 @@ def get(resource_type: Literal["usd"], resource_name: str) -> None:
"--other-props", multiple=True, help="List of other properties to include."
)
def parse(
demo: Path,
demo_path: Path,
*,
outpath: Optional[Path] = None,
verbose: bool = False,
Expand All @@ -54,8 +58,7 @@ def parse(
player_props: Optional[tuple[str]] = None,
other_props: Optional[tuple[str]] = None,
) -> None:
"""Parse a file given its path."""
demo_path = Path(demo) # Pathify
"""Parse a file given its path.""" # Pathify
demo = Demo(
path=demo_path,
verbose=verbose,
Expand Down
26 changes: 25 additions & 1 deletion awpy/data/map_data.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,31 @@
"""Dictionary that holds map data for Counter-Strike 2."""

from typing import Optional, TypedDict, Union

Number = Union[int, float]


class Selection(TypedDict):
"""Structure of selections data."""

name: str
altitude_max: Number
altitude_min: Number


class MapData(TypedDict):
"""Structure of map data."""

pos_x: Number
pos_y: Number
scale: Number
rotate: Optional[Number]
zoom: Optional[Number]
selections: list[Selection]


# pos_x is upper left world coordinate
MAP_DATA = {
MAP_DATA: dict[str, MapData] = {
"ar_baggage": {
"pos_x": -1316,
"pos_y": 1288,
Expand Down
8 changes: 5 additions & 3 deletions awpy/demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from pathlib import Path
from typing import Optional

from demoparser2 import DemoParser # pylint: disable=E0611
from demoparser2 import DemoParser
from loguru import logger

from awpy.parsers.clock import parse_times
Expand Down Expand Up @@ -62,7 +62,7 @@
]


class Demo:
class Demo: # pylint: disable=R0902
"""Class to store a demo's data. Called with `Demo(file="...")`."""

def __init__(
Expand Down Expand Up @@ -265,7 +265,7 @@ def compress(self, outpath: Optional[Path] = None) -> None:
Args:
outpath (Path): Path to save the zip file. Defaults to cwd.
"""
outpath = Path.cwd() if outpath is None else Path(outpath)
outpath = Path.cwd() if outpath is None else outpath
zip_name = outpath / Path(self.path.stem + ".zip")

with (
Expand All @@ -284,6 +284,8 @@ def compress(self, outpath: Optional[Path] = None) -> None:
("rounds", self.rounds),
("grenades", self.grenades),
]:
if df is None:
continue
df_filename = os.path.join(tmpdirname, f"{df_name}.data")
df.to_parquet(df_filename, index=False)
zipf.write(df_filename, f"{df_name}.data")
Expand Down
4 changes: 2 additions & 2 deletions awpy/parsers/clock.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ def _find_clock_time(row: pd.Series) -> str:
"bomb": row["ticks_since_bomb_plant"],
}
# Filter out NA values and find the key with the minimum value
min_key = min((k for k in times if pd.notna(times[k])), key=lambda k: times[k])
return parse_clock(times[min_key], min_key)
min_key = min((k for k in times if pd.notna(times[k])), key=lambda k: times[k]) # pylint: disable=C0206
return parse_clock(times[min_key], min_key) # pyright: ignore[reportArgumentType]


def parse_times(
Expand Down
2 changes: 1 addition & 1 deletion awpy/parsers/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import numpy as np
import pandas as pd
from demoparser2 import DemoParser # pylint: disable=E0611
from demoparser2 import DemoParser
from loguru import logger

from awpy.converters import (
Expand Down
4 changes: 2 additions & 2 deletions awpy/parsers/rounds.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import numpy as np
import pandas as pd
from demoparser2 import DemoParser # pylint: disable=E0611
from demoparser2 import DemoParser


def _find_bomb_plant_tick(row: pd.Series, bomb_ticks: pd.Series) -> Union[int, float]:
Expand Down Expand Up @@ -143,7 +143,7 @@ def parse_rounds(parser: DemoParser, events: dict[str, pd.DataFrame]) -> pd.Data

# Find the bomb plant ticks
bomb_planted = events.get("bomb_planted")
if bomb_planted.shape[0] == 0:
if not bomb_planted or bomb_planted.shape[0] == 0:
return rounds_df

rounds_df["bomb_plant"] = rounds_df.apply(
Expand Down
2 changes: 1 addition & 1 deletion awpy/parsers/ticks.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Module for tick parsing functions."""

import pandas as pd
from demoparser2 import DemoParser # pylint: disable=E0611
from demoparser2 import DemoParser

from awpy.parsers.utils import parse_col_types

Expand Down
5 changes: 3 additions & 2 deletions awpy/stats/adr.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@

def adr(
demo: Demo,
team_dmg: bool = False, # noqa: FBT001, FBT002
self_dmg: bool = True, # noqa: FBT001, FBT002
*,
team_dmg: bool = False,
self_dmg: bool = True,
) -> pd.DataFrame:
"""Calculates Average Damage Per Round. Does not include team damage.
Expand Down
2 changes: 1 addition & 1 deletion awpy/stats/kast.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def calculate_trades(kills: pd.DataFrame, trade_ticks: int = 128 * 5) -> pd.Data
return kills


def kast(demo: Demo, trade_ticks: int = 128 * 5) -> pd.DataFrame:
def kast(demo: Demo, trade_ticks: int = 128 * 5) -> pd.DataFrame: # pylint: disable=R0914
"""Calculates Kill-Assist-Survival-Trade %.
Args:
Expand Down
16 changes: 13 additions & 3 deletions awpy/vis/plot.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,25 @@
"""Module for plotting Counter-Strike data."""

import importlib.resources
from typing import Optional
from typing import Optional, Union, overload

import matplotlib.image as mpimg
import matplotlib.pyplot as plt
from matplotlib.axes import Axes
from matplotlib.figure import Figure


def plot_map(map_name: str, *, lower: Optional[bool] = None) -> tuple[Figure, Axes]:
@overload
def plot_map(map_name: str, *, lower: None = ...) -> tuple[Figure, list[Axes]]: ...


@overload
def plot_map(map_name: str, *, lower: bool = ...) -> tuple[Figure, Axes]: ...


def plot_map(
map_name: str, *, lower: Optional[bool] = None
) -> tuple[Figure, Union[Axes, list[Axes]]]:
"""Plot a Counter-Strike map.
Args:
Expand Down Expand Up @@ -60,7 +70,7 @@ def plot_upper_and_lower(map_name: str) -> tuple[Figure, list[Axes]]:
map_names = [map_name, f"{map_name}_lower"]
figure, axes = plt.subplots(1, 2) # , figsize=(2 * 5, 5)

for ax, map_layer_name in zip(axes, map_names, strict=True):
for ax, map_layer_name in zip(axes, map_names):
with importlib.resources.path(
"awpy.data.maps", f"{map_layer_name}.png"
) as map_img_path:
Expand Down
2 changes: 1 addition & 1 deletion awpy/vis/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def position_transform_axis(
Raises:
ValueError: Raises a ValueError if axis not 'x' or 'y'
"""
axis = axis.lower()
axis = axis.lower() # pyright: ignore[reportAssignmentType]
if axis not in ["x", "y"]:
msg = f"'axis' has to be 'x' or 'y', not {axis}"
raise ValueError(msg)
Expand Down
Loading

0 comments on commit cdc3ed9

Please sign in to comment.