Skip to content

Commit

Permalink
fix ruff errors
Browse files Browse the repository at this point in the history
  • Loading branch information
gilesknap committed Feb 10, 2024
1 parent 111ec15 commit 74119ac
Show file tree
Hide file tree
Showing 13 changed files with 51 additions and 54 deletions.
11 changes: 5 additions & 6 deletions .github/pages/make_switcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,27 @@
from argparse import ArgumentParser
from pathlib import Path
from subprocess import CalledProcessError, check_output
from typing import List, Optional


def report_output(stdout: bytes, label: str) -> List[str]:
def report_output(stdout: bytes, label: str) -> list[str]:
ret = stdout.decode().strip().split("\n")
print(f"{label}: {ret}")
return ret


def get_branch_contents(ref: str) -> List[str]:
def get_branch_contents(ref: str) -> list[str]:
"""Get the list of directories in a branch."""
stdout = check_output(["git", "ls-tree", "-d", "--name-only", ref])
return report_output(stdout, "Branch contents")


def get_sorted_tags_list() -> List[str]:
def get_sorted_tags_list() -> list[str]:
"""Get a list of sorted tags in descending order from the repository."""
stdout = check_output(["git", "tag", "-l", "--sort=-v:refname"])
return report_output(stdout, "Tags list")


def get_versions(ref: str, add: Optional[str]) -> List[str]:
def get_versions(ref: str, add: str | None) -> list[str]:
"""Generate the file containing the list of all GitHub Pages builds."""
# Get the directories (i.e. builds) from the GitHub Pages branch
try:
Expand All @@ -41,7 +40,7 @@ def get_versions(ref: str, add: Optional[str]) -> List[str]:
tags = get_sorted_tags_list()

# Make the sorted versions list from main branches and tags
versions: List[str] = []
versions: list[str] = []
for version in ["master", "main"] + tags:
if version in builds:
versions.append(version)
Expand Down
6 changes: 3 additions & 3 deletions src/demo/example2player.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

def get_player_pos(name: str, wait: float):
with Client("nuc2", port=30555, passwd="spider") as client:
for i in range(100):
for _i in range(100):
x = client.data.get(entity="@p", path="Pos")
print(name, parse_nbt(x))
sleep(wait)
Expand All @@ -17,7 +17,7 @@ def get_player_pos(name: str, wait: float):
def get_player_pos2(name: str, wait: float):
client = Client("nuc2", port=30555, passwd="spider")
client.connect(True)
for i in range(100):
for _i in range(100):
x = client.data.get(entity="@p", path="Pos")
print(name, parse_nbt(x))
sleep(wait)
Expand All @@ -29,7 +29,7 @@ def get_player_pos2(name: str, wait: float):

def get_player_pos3(name: str, wait: float):
# share the connection between threads
for i in range(100):
for _i in range(100):
x = client.data.get(entity="@p", path="Pos")
print(name, parse_nbt(x))
sleep(wait)
Expand Down
3 changes: 2 additions & 1 deletion src/demo/gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,11 @@ def portcullis(position, close, width=4, height=6):
sleep(0.5)


def make_gate(position=Vec3(x=623, y=73, z=-1660)):
def make_gate(position=None):
"""
Create a castle gate with working portcullis
"""
position = position or Vec3(x=623, y=73, z=-1660)

def open_close(switch):
portcullis(position, switch.powered)
Expand Down
4 changes: 3 additions & 1 deletion src/demo/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@ def gateway(position, width, height):
c.fill(w_front, e_back_top, Item.AIR)


def make_gate(position=Vec3(x=621, y=72, z=-1662), width=4, height=6, length=25):
def make_gate(position=None, width=4, height=6, length=25):
position = position or Vec3(x=621, y=72, z=-1662)

def open_close(switch):
o = switch.powered
Monitor(func=portcullis, params=(position, o, width, height), once=True)
Expand Down
2 changes: 1 addition & 1 deletion src/demo/snowball.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def track_snowball(entity: str, result: str):
c = get_client()

# track for 20 secs only
for i in range(200):
for _i in range(200):
sleep(0.1)
last_result = result
result = c.data.get(entity=entity)
Expand Down
3 changes: 1 addition & 2 deletions src/mciwb/__main__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import sys
from pathlib import Path
from typing import Optional

import traitlets
import typer
Expand Down Expand Up @@ -36,7 +35,7 @@ def version_callback(value: bool):

@cli.callback()
def main(
version: Optional[bool] = typer.Option(
version: bool | None = typer.Option(
None,
"--version",
callback=version_callback,
Expand Down
17 changes: 8 additions & 9 deletions src/mciwb/iwb.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from pathlib import Path
from typing import Dict, List, Optional

from mcipc.rcon.exceptions import NoPlayerFound
from mcipc.rcon.item import Item
Expand Down Expand Up @@ -62,13 +61,13 @@ def __init__(self, server: str, port: int, passwd: str) -> None:
self.copier: CopyPaste = None # type: ignore
self.signs: Signs = None # type: ignore

self._players: Dict[str, Player] = {}
self._copiers: Dict[str, CopyPaste] = {}
self._players: dict[str, Player] = {}
self._copiers: dict[str, CopyPaste] = {}

# if we are using the default server created by mciwb then we know
# where the folders are for doing backups
if server == HOST and port == def_port:
self._backup: Optional[Backup] = Backup()
self._backup: Backup | None = Backup()
else:
self._backup = None

Expand Down Expand Up @@ -120,7 +119,7 @@ def get_player(self, name: str) -> Player:
return self._players[name]

@property
def players(self) -> List[str]:
def players(self) -> list[str]:
"""
Get a list of the names of players being monitored.
"""
Expand Down Expand Up @@ -169,8 +168,8 @@ def set_block(
self,
pos: Vec3,
block: Item,
facing: Optional[Vec3] = None,
nbt: Optional[List[str]] = None,
facing: Vec3 | None = None,
nbt: list[str] | None = None,
):
"""
Places a block in the world
Expand Down Expand Up @@ -244,7 +243,7 @@ def __repr__(self) -> str:

return report.format(o=self)

def save(self, filename: str, vol: Optional[Volume] = None):
def save(self, filename: str, vol: Volume | None = None):
"""
Save a Volume of blocks to a file. The volume can be specified in
the *vol* parameter or alternatively defaults to the current copy buffer.
Expand All @@ -266,7 +265,7 @@ def save(self, filename: str, vol: Optional[Volume] = None):
def load(
self,
filename: str,
position: Optional[Vec3] = None,
position: Vec3 | None = None,
anchor: Anchor3 = Anchor3.BOTTOM_SW,
):
"""
Expand Down
15 changes: 8 additions & 7 deletions src/mciwb/monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
monitoring the state of objects in Minecraft.
"""

from collections.abc import Callable
from time import sleep
from typing import Any, Callable, List, Tuple, Union
from typing import Any

from rcon.exceptions import SessionTimeout

Expand Down Expand Up @@ -36,12 +37,12 @@ class Monitor:
"""

monitor_num = 0
monitors: List["Monitor"] = []
monitors: list["Monitor"] = []

def __init__(
self,
func: Union[None, CallbackFunction] = None,
params: Tuple[Any, ...] = (),
func: None | CallbackFunction = None,
params: tuple[Any, ...] = (),
once=False,
name=None,
poll_rate=0.2,
Expand All @@ -53,7 +54,7 @@ def __init__(

# pollers is a list of functions, param tuples. It may be initialized
# with a single function passed in func, params
self.pollers: List[Tuple[CallbackFunction, Tuple[Any, ...]]] = (
self.pollers: list[tuple[CallbackFunction, tuple[Any, ...]]] = (
[] if func is None else [(func, params)]
)

Expand Down Expand Up @@ -111,7 +112,7 @@ def _poller(self):
if not self.once:
log.info(f"Monitor {self.name} stopped")

def add_poller_func(self, func: CallbackFunction, params: Tuple[Any, ...] = ()):
def add_poller_func(self, func: CallbackFunction, params: tuple[Any, ...] = ()):
"""
Add a function to the pollers list
Expand All @@ -128,7 +129,7 @@ def remove_poller_func(self, func: CallbackFunction):
:param func: function to remove
"""
for i, t in enumerate(self.pollers):
for _i, t in enumerate(self.pollers):
f, params = t
if f == func:
self.pollers.remove(t)
Expand Down
8 changes: 4 additions & 4 deletions src/mciwb/player.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@

import math
import re
from re import Match, Pattern
from time import sleep
from typing import List, Match, Pattern, Tuple

from mcwb.types import Direction, Vec3
from mcwb.volume import Volume
Expand Down Expand Up @@ -57,7 +57,7 @@ def _get_entity_data(self, path: str, regex: Pattern[str]) -> Match[str]:
raise PlayerNotInWorld(f"player {self.name} left")

@property
def inventory(self) -> List[str]:
def inventory(self) -> list[str]:
"""
Get the player's inventory
"""
Expand Down Expand Up @@ -98,7 +98,7 @@ def facing(self) -> Vec3:
return Direction.cardinals[index]

@property
def rotation(self) -> Tuple[float, float]:
def rotation(self) -> tuple[float, float]:
"""
Get the player's rotation in degrees
"""
Expand All @@ -114,7 +114,7 @@ def player_in(self, volume: Volume) -> bool:
return volume.inside(self.pos)

@classmethod
def players_in(cls, volume: Volume) -> List["Player"]:
def players_in(cls, volume: Volume) -> list["Player"]:
"""
return a list of player names whose position is inside the Volume
"""
Expand Down
6 changes: 3 additions & 3 deletions src/mciwb/signs.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
"""

import re
from collections.abc import Callable
from time import sleep
from typing import Callable, Dict

from mcwb.types import Item, Vec3

Expand Down Expand Up @@ -47,7 +47,7 @@ class Signs:
def __init__(self, player: Player):
self.player = player
self.copy = CopyPaste()
self.signs: Dict[str, CallbackPosFunction] = self.copy.get_commands()
self.signs: dict[str, CallbackPosFunction] = self.copy.get_commands()

def _get_target_block(self, pos: Vec3, facing: Vec3) -> Vec3:
"""
Expand Down Expand Up @@ -134,5 +134,5 @@ def give_signs(self):
client = get_client()
inventory = self.player.inventory
for command in self.signs:
if not self._sign_match.format(command) in inventory:
if self._sign_match.format(command) not in inventory:
client.give(self.player.name, self._re_sign_entity.format(command))
4 changes: 2 additions & 2 deletions src/mciwb/switch.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Callable, List
from collections.abc import Callable

from mcipc.rcon.enumerations import Item, SetblockMode
from mcwb.types import Vec3
Expand Down Expand Up @@ -44,7 +44,7 @@ class Switch:
:ivar monitor: the `Monitor` object for the switch
"""

switches: List["Switch"] = []
switches: list["Switch"] = []

next_id: int = 0

Expand Down
22 changes: 10 additions & 12 deletions src/mciwb/wall.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, List, Optional
from typing import Any

import numpy as np
from mcipc.rcon.enumerations import SetblockMode
Expand All @@ -12,12 +12,10 @@


class Wall:
def __init__(
self, height=None, item=Item.STONE, profile: Optional[List[Any]] = None
):
def __init__(self, height=None, item=Item.STONE, profile: list[Any] | None = None):
self._start: Vec3 = None # type: ignore
self._end: Vec3 = None # type: ignore
self.height: Optional[int] = height
self.height: int | None = height

if profile is None:
# default profile is just a single column of stone
Expand All @@ -36,7 +34,7 @@ def set_start(self, pos: Vec3):
def set_end(self, pos: Vec3):
self._end = pos + Direction.UP

def draw(self, end: Optional[Vec3] = None):
def draw(self, end: Vec3 | None = None):
self._end = end + Direction.UP if end else self._end
# start at the same height as the new end
self._start = Vec3(self._start.x, self._end.y, self._start.z)
Expand Down Expand Up @@ -67,7 +65,7 @@ def _render(self):
"wall_dir {wall_dir} step_dir {step_dir}"
)

for section in range(sections):
for _section in range(sections):
end = begin + wall_dir * wall_section_len
self._render_section(begin, wall_section_len, wall_dir)
begin = end + step_dir
Expand All @@ -81,21 +79,21 @@ def _render_section(self, begin: Vec3, length: float, wall_dir: Vec3):
f" to {begin + wall_dir * length}"
)

for column in range(int(length) + 1):
for _column in range(int(length) + 1):
profile = self.profile[self.profile_idx]
self._render_column(base, profile, col_dir)

base = base + wall_dir
self.profile_idx = (self.profile_idx + 1) % self.profile_idx_limit

def _render_column(self, base: Vec3, profile: List[Any], direction: Vec3):
def _render_column(self, base: Vec3, profile: list[Any], direction: Vec3):
c = get_client()
height = self.height or len(profile)
for level in range(height):
level_profile = profile[(height - level - 1) % len(profile)]
if not isinstance(level_profile, List):
if not isinstance(level_profile, list):
level_profile = [level_profile]
for i, item in enumerate(level_profile):
for i, _item in enumerate(level_profile):
pos = base.with_ints() + Direction.UP * level + direction * i
c.setblock(pos, level_profile[i], mode=SetblockMode.REPLACE)

Expand All @@ -114,7 +112,7 @@ class WallMaker:
start = "start_wall"
end = "end_wall"

def __init__(self, wall: Optional[Wall] = None):
def __init__(self, wall: Wall | None = None):
self.wall = wall or Wall()
signs = get_world().signs
signs.add_sign(self.start, self.wall.set_start)
Expand Down
4 changes: 1 addition & 3 deletions tests/mockplayer.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from typing import List

from mciwb.imports import Direction, Vec3, Volume
from tests.conftest import ENTITY_NAME
from tests.mockclient import MockClient
Expand All @@ -24,7 +22,7 @@ def player_in(self, volume: Volume) -> bool:
return volume.inside(self.pos)

@classmethod
def players_in(cls, volume: Volume) -> List["MockPlayer"]:
def players_in(cls, volume: Volume) -> list["MockPlayer"]:
"""
return a list of player names whose position is inside the volume
"""
Expand Down

0 comments on commit 74119ac

Please sign in to comment.