Skip to content

Commit 05f297b

Browse files
committed
Code cleanups // Python 3.10+
1 parent 0487cfb commit 05f297b

File tree

131 files changed

+899
-948
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

131 files changed

+899
-948
lines changed

core/data/dataobject.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
from configparser import ConfigParser
66
from dataclasses import dataclass, field
7-
from typing import TYPE_CHECKING, Callable, Type, Optional, TypeVar, Generic, ClassVar, Any
7+
from typing import TYPE_CHECKING, Callable, Type, TypeVar, Generic, ClassVar, Any
88

99
if TYPE_CHECKING:
1010
from core import Node
@@ -55,7 +55,7 @@ class DataObjectFactory(Generic[T]):
5555
_instance: The singleton instance of this class
5656
_registry: Dictionary mapping object types to their implementation classes
5757
"""
58-
_instance: Optional[DataObjectFactory[T]] = None
58+
_instance: DataObjectFactory[T] | None = None
5959
# Using class variable storage that's independent of the generic type parameter
6060
_registry: ClassVar[dict[Any, Any]] = {}
6161

@@ -71,7 +71,7 @@ def __new__(cls) -> DataObjectFactory[T]:
7171
return cls._instance
7272

7373
@classmethod
74-
def register(cls, t: Optional[Type[T]] = None) -> Callable[[Type[T]], Type[T]]:
74+
def register(cls, t: Type[T] | None = None) -> Callable[[Type[T]], Type[T]]:
7575
"""
7676
Decorator for registering implementation classes with the factory.
7777

core/data/impl/instanceimpl.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from core.const import SAVED_GAMES
99
from core.utils.helper import SettingsDict
1010
from dataclasses import dataclass
11-
from typing import Optional, TYPE_CHECKING
11+
from typing import TYPE_CHECKING
1212

1313
if TYPE_CHECKING:
1414
from core import Server
@@ -72,7 +72,7 @@ def __post_init__(self):
7272
server_name = None
7373
self.update_instance(server_name)
7474

75-
def update_instance(self, server_name: Optional[str] = None):
75+
def update_instance(self, server_name: str | None = None):
7676
try:
7777
with self.pool.connection() as conn:
7878
with conn.transaction():
@@ -90,15 +90,15 @@ def update_instance(self, server_name: Optional[str] = None):
9090
def home(self) -> str:
9191
return os.path.expandvars(self.locals.get('home', os.path.join(SAVED_GAMES, self.name)))
9292

93-
def update_server(self, server: Optional[Server] = None):
93+
def update_server(self, server: Server | None = None):
9494
with self.pool.connection() as conn:
9595
with conn.transaction():
9696
conn.execute("""
9797
UPDATE instances SET server_name = %s, last_seen = (now() AT TIME ZONE 'utc')
9898
WHERE node = %s AND instance = %s
9999
""", (server.name if server and server.name != 'n/a' else None, self.node.name, self.name))
100100

101-
def set_server(self, server: Optional[Server]):
101+
def set_server(self, server: Server | None):
102102
if self._server and self._server.status not in [Status.UNREGISTERED, Status.SHUTDOWN]:
103103
raise InstanceBusyError()
104104
self._server = server

core/data/impl/nodeimpl.py

Lines changed: 28 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
from psycopg.errors import UndefinedTable, InFailedSqlTransaction, ConnectionTimeout, UniqueViolation
3434
from psycopg.types.json import Json
3535
from psycopg_pool import ConnectionPool, AsyncConnectionPool
36-
from typing import Optional, Union, Awaitable, Callable, Any, cast
36+
from typing import Awaitable, Callable, Any, cast
3737
from urllib.parse import urlparse, quote
3838
from version import __version__
3939
from zoneinfo import ZoneInfo
@@ -89,24 +89,24 @@
8989

9090
class NodeImpl(Node):
9191

92-
def __init__(self, name: str, config_dir: Optional[str] = 'config'):
92+
def __init__(self, name: str, config_dir: str | None = 'config'):
9393
super().__init__(name, config_dir)
9494
self.node = self # to be able to address self.node
95-
self._public_ip: Optional[str] = None
95+
self._public_ip: str | None = None
9696
self.bot_version = __version__[:__version__.rfind('.')]
9797
self.sub_version = int(__version__[__version__.rfind('.') + 1:])
9898
self.is_shutdown = asyncio.Event()
9999
self.rc = 0
100100
self.dcs_branch = None
101-
self.all_nodes: dict[str, Optional[Node]] = {self.name: self}
101+
self.all_nodes: dict[str, Node | None] = {self.name: self}
102102
self.suspect: dict[str, Node] = {}
103103
self.update_pending = False
104104
self.before_update: dict[str, Callable[[], Awaitable[Any]]] = {}
105105
self.after_update: dict[str, Callable[[], Awaitable[Any]]] = {}
106106
self.db_version = None
107-
self.pool: Optional[ConnectionPool] = None
108-
self.apool: Optional[AsyncConnectionPool] = None
109-
self.cpool: Optional[AsyncConnectionPool] = None
107+
self.pool: ConnectionPool | None = None
108+
self.apool: AsyncConnectionPool | None = None
109+
self.cpool: AsyncConnectionPool | None = None
110110
self._master = None
111111

112112
def _check_branch_version(self):
@@ -206,8 +206,8 @@ def listen_address(self) -> str:
206206
def listen_port(self) -> int:
207207
return self.locals.get('listen_port', 10042)
208208

209-
async def audit(self, message, *, user: Optional[Union[discord.Member, str]] = None,
210-
server: Optional[Server] = None, **kwargs):
209+
async def audit(self, message, *, user: discord.Member | str | None = None,
210+
server: Server | None = None, **kwargs):
211211
from services.bot import BotService
212212
from services.servicebus import ServiceBus
213213

@@ -292,7 +292,7 @@ def read_locals(self) -> dict:
292292
raise FatalException(f"No {config_file} found. Exiting.")
293293

294294
async def init_db(self):
295-
async def check_db(url: str) -> Optional[str]:
295+
async def check_db(url: str) -> str | None:
296296
max_attempts = self.locals.get("database", self.config.get('database')).get('max_retries', 10)
297297
for attempt in range(max_attempts + 1):
298298
try:
@@ -577,9 +577,9 @@ async def get_dcs_branch_and_version(self) -> tuple[str, str]:
577577
exit(SHUTDOWN)
578578
return self.dcs_branch, self.dcs_version
579579

580-
async def update(self, warn_times: list[int], branch: Optional[str] = None, version: Optional[str] = None) -> int:
580+
async def update(self, warn_times: list[int], branch: str | None = None, version: str | None = None) -> int:
581581

582-
async def do_update(branch: str, version: Optional[str] = None) -> int:
582+
async def do_update(branch: str, version: str | None = None) -> int:
583583
# disable any popup on the remote machine
584584
if sys.platform == 'win32':
585585
startupinfo = subprocess.STARTUPINFO()
@@ -812,12 +812,12 @@ async def get_available_modules(self) -> list[str]:
812812
licenses.add(lic)
813813
async with session.get(LOGOUT_URL):
814814
pass
815-
return list(licenses)
815+
return list(licenses)
816816

817817
@cache_with_expiration(expiration=120)
818-
async def get_available_dcs_versions(self, branch: str) -> Optional[list[str]]:
818+
async def get_available_dcs_versions(self, branch: str) -> list[str] | None:
819819

820-
async def _get_latest_versions_no_auth() -> Optional[list[str]]:
820+
async def _get_latest_versions_no_auth() -> list[str] | None:
821821
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(
822822
ssl=ssl.create_default_context(cafile=certifi.where()))) as session:
823823
async with session.get(
@@ -826,7 +826,7 @@ async def _get_latest_versions_no_auth() -> Optional[list[str]]:
826826
return [x['version'] for x in json.loads(gzip.decompress(await response.read()))['versions2']]
827827
return None
828828

829-
async def _get_latest_versions_auth() -> Optional[list[str]]:
829+
async def _get_latest_versions_auth() -> list[str] | None:
830830
user = self.locals['DCS'].get('user')
831831
password = utils.get_password('DCS', self.config_dir)
832832
headers = {
@@ -855,7 +855,7 @@ async def _get_latest_versions_auth() -> Optional[list[str]]:
855855
return await _get_latest_versions_auth()
856856

857857

858-
async def get_latest_version(self, branch: str) -> Optional[str]:
858+
async def get_latest_version(self, branch: str) -> str | None:
859859
versions = await self.get_available_dcs_versions(branch)
860860
return versions[-1] if versions else None
861861

@@ -919,7 +919,7 @@ async def handle_upgrade(master: str) -> bool:
919919
await take_over()
920920
return True
921921

922-
async def get_master() -> tuple[Optional[str], str, bool]:
922+
async def get_master() -> tuple[str | None, str, bool]:
923923
cursor = await conn.execute("""
924924
SELECT master, version, update_pending
925925
FROM cluster WHERE guild_id = %s FOR UPDATE
@@ -1048,7 +1048,7 @@ async def get_active_nodes(self) -> list[str]:
10481048
cursor = await conn.execute(query, (self.guild_id, self.name))
10491049
return [row[0] async for row in cursor]
10501050

1051-
async def shell_command(self, cmd: str, timeout: int = 60) -> Optional[tuple[str, str]]:
1051+
async def shell_command(self, cmd: str, timeout: int = 60) -> tuple[str, str] | None:
10521052
def run_subprocess():
10531053
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
10541054
return proc.communicate(timeout=timeout)
@@ -1064,7 +1064,7 @@ def run_subprocess():
10641064
except subprocess.TimeoutExpired:
10651065
raise TimeoutError()
10661066

1067-
async def read_file(self, path: str) -> Union[bytes, int]:
1067+
async def read_file(self, path: str) -> bytes | int:
10681068
async def _read_file(path: str):
10691069
if path.startswith('http'):
10701070
async with aiohttp.ClientSession() as session:
@@ -1109,7 +1109,7 @@ async def write_file(self, filename: str, url: str, overwrite: bool = False) ->
11091109
else:
11101110
return UploadStatus.READ_ERROR
11111111

1112-
async def list_directory(self, path: str, *, pattern: Union[str, list[str]] = '*',
1112+
async def list_directory(self, path: str, *, pattern: str | list[str] = '*',
11131113
order: SortOrder = SortOrder.DATE,
11141114
is_dir: bool = False, ignore: list[str] = None, traverse: bool = False
11151115
) -> tuple[str, list[str]]:
@@ -1141,7 +1141,7 @@ async def remove_file(self, path: str):
11411141
for file in files:
11421142
os.remove(file)
11431143

1144-
async def rename_file(self, old_name: str, new_name: str, *, force: Optional[bool] = False):
1144+
async def rename_file(self, old_name: str, new_name: str, *, force: bool | None = False):
11451145
shutil.move(old_name, new_name, copy_function=shutil.copy2 if force else None)
11461146

11471147
async def rename_server(self, server: Server, new_name: str):
@@ -1162,7 +1162,7 @@ async def rename_server(self, server: Server, new_name: str):
11621162
if server.is_remote:
11631163
server.name = new_name
11641164

1165-
async def is_dcs_update_available(self) -> Optional[str]:
1165+
async def is_dcs_update_available(self) -> str | None:
11661166
branch, old_version = await self.get_dcs_branch_and_version()
11671167
try:
11681168
new_version = await self.get_latest_version(branch)
@@ -1178,8 +1178,8 @@ async def is_dcs_update_available(self) -> Optional[str]:
11781178
self.log.warning("DCS update check failed, possible server outage at ED.")
11791179
return None
11801180

1181-
async def dcs_update(self, *, branch: Optional[str] = None, version: Optional[str] = None,
1182-
warn_times: list[int] = None, announce: Optional[bool] = True):
1181+
async def dcs_update(self, *, branch: str | None = None, version: str | None = None,
1182+
warn_times: list[int] = None, announce: bool | None = True):
11831183
from services.bot import BotService
11841184
from services.servicebus import ServiceBus
11851185

@@ -1367,7 +1367,8 @@ async def add_instance(self, name: str, *, template: str = "") -> "Instance":
13671367
yaml.dump(config, outfile)
13681368
settings_path = os.path.join(instance.home, 'Config', 'serverSettings.lua')
13691369
if os.path.exists(settings_path):
1370-
settings = SettingsDict(cast(DataObject, self), settings_path, root='cfg')
1370+
# TODO: dirty cast
1371+
settings = SettingsDict(cast(DataObject, cast(object, self)), settings_path, root='cfg')
13711372
settings['port'] = instance.dcs_port
13721373
settings['name'] = 'n/a'
13731374
settings['missionList'] = []
@@ -1584,7 +1585,7 @@ async def uninstall_plugin(self, plugin: str) -> bool:
15841585
self.plugins.remove(plugin)
15851586
return True
15861587

1587-
async def get_cpu_info(self) -> Union[bytes, int]:
1588+
async def get_cpu_info(self) -> bytes | int:
15881589
def create_image() -> bytes:
15891590
p_core_affinity_mask = utils.get_p_core_affinity()
15901591
e_core_affinity_mask = utils.get_e_core_affinity()

0 commit comments

Comments
 (0)