Skip to content

Commit 5ef0ff9

Browse files
Merge pull request #20 from TabulateJarl8/improved_typing
Finish fully typing
2 parents e344dd5 + fa2e98b commit 5ef0ff9

File tree

8 files changed

+703
-358
lines changed

8 files changed

+703
-358
lines changed

poetry.lock

Lines changed: 436 additions & 307 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[tool.poetry]
22
name = "vapor-steam"
3-
version = "1.5.7"
3+
version = "1.5.8"
44
description = "TUI program to check the ProtonDB compatibility of all the games of a Steam user."
55
authors = ["TabulateJarl8 <tabulatejarl8@gmail.com>"]
66
license = "GPLv3"
@@ -46,6 +46,9 @@ pytest-asyncio = "^0.24.0"
4646
[tool.pytest.ini_options]
4747
asyncio_default_fixture_loop_scope = "function"
4848

49+
[tool.pyright]
50+
reportUnusedCallResult = false
51+
4952
[build-system]
5053
requires = ["poetry-core"]
5154
build-backend = "poetry.core.masonry.api"

vapor/api_interface.py

Lines changed: 25 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,21 @@
1313
HTTP_UNAUTHORIZED,
1414
RATING_DICT,
1515
STEAM_USER_ID_LENGTH,
16+
AntiCheatAPIResponse,
1617
AntiCheatData,
1718
AntiCheatStatus,
1819
Game,
20+
ProtonDBAPIResponse,
1921
Response,
22+
SteamAPINameResolutionResponse,
23+
SteamAPIPlatformsResponse,
24+
SteamAPIUserDataResponse,
2025
SteamUserData,
2126
)
2227
from vapor.exceptions import InvalidIDError, PrivateAccountError, UnauthorizedError
2328

2429

25-
async def async_get(url: str, **session_kwargs: Any) -> Response:
30+
async def async_get(url: str, **session_kwargs: Any) -> Response: # pyright: ignore[reportAny]
2631
"""Async get request for fetching web content.
2732
2833
Args:
@@ -32,7 +37,7 @@ async def async_get(url: str, **session_kwargs: Any) -> Response:
3237
Returns:
3338
Response: A Response object containing the body and status code.
3439
"""
35-
async with aiohttp.ClientSession(**session_kwargs) as session, session.get(
40+
async with aiohttp.ClientSession(**session_kwargs) as session, session.get( # pyright: ignore[reportAny]
3641
url,
3742
) as response:
3843
return Response(data=await response.text(), status=response.status)
@@ -53,16 +58,19 @@ async def check_game_is_native(app_id: str) -> bool:
5358
if data.status != HTTP_SUCCESS:
5459
return False
5560

56-
json_data = json.loads(data.data)
61+
json_data: Dict[str, SteamAPIPlatformsResponse] = json.loads(data.data)
5762

5863
return _extract_game_is_native(json_data, app_id)
5964

6065

61-
def _extract_game_is_native(data: Dict, app_id: str) -> bool:
66+
def _extract_game_is_native(
67+
data: Dict[str, SteamAPIPlatformsResponse],
68+
app_id: str,
69+
) -> bool:
6270
"""Extract whether or not a game is Linux native from API data.
6371
6472
Args:
65-
data (Dict): the data from the Steam API.
73+
data (Dict[str, SteamAPIPlatformsResponse]): the data from the Steam API.
6674
app_id (str): The App ID of the game
6775
6876
Returns:
@@ -98,7 +106,7 @@ async def get_anti_cheat_data() -> Optional[Cache]:
98106
return None
99107

100108
try:
101-
anti_cheat_data = json.loads(data.data)
109+
anti_cheat_data: List[AntiCheatAPIResponse] = json.loads(data.data)
102110
except json.JSONDecodeError:
103111
return None
104112

@@ -109,11 +117,11 @@ async def get_anti_cheat_data() -> Optional[Cache]:
109117
return cache
110118

111119

112-
def parse_anti_cheat_data(data: List[Dict]) -> List[AntiCheatData]:
120+
def parse_anti_cheat_data(data: List[AntiCheatAPIResponse]) -> List[AntiCheatData]:
113121
"""Parse and return data from AreWeAntiCheatYet.
114122
115123
Args:
116-
data (List[Dict]): The data from AreWeAntiCheatYet
124+
data (List[AntiCheatAPIResponse]): The data from AreWeAntiCheatYet
117125
118126
Returns:
119127
List[AntiCheatData]: the anticheat statuses of each game in the given data
@@ -152,7 +160,7 @@ async def get_game_average_rating(app_id: str, cache: Cache) -> str:
152160
if data.status != HTTP_SUCCESS:
153161
return 'pending'
154162

155-
json_data = json.loads(data.data)
163+
json_data: ProtonDBAPIResponse = json.loads(data.data)
156164

157165
return json_data.get('tier', 'pending')
158166

@@ -178,7 +186,7 @@ async def resolve_vanity_name(api_key: str, name: str) -> str:
178186
if data.status == HTTP_FORBIDDEN:
179187
raise UnauthorizedError
180188

181-
user_data = json.loads(data.data)
189+
user_data: SteamAPINameResolutionResponse = json.loads(data.data)
182190
if 'response' not in user_data or user_data['response']['success'] != 1:
183191
raise InvalidIDError
184192

@@ -218,19 +226,19 @@ async def get_steam_user_data(api_key: str, user_id: str) -> SteamUserData:
218226
if data.status == HTTP_UNAUTHORIZED:
219227
raise UnauthorizedError
220228

221-
data = json.loads(data.data)
229+
user_data: SteamAPIUserDataResponse = json.loads(data.data)
222230

223-
return await parse_steam_user_games(data, cache)
231+
return await parse_steam_user_games(user_data, cache)
224232

225233

226234
async def parse_steam_user_games(
227-
data: Dict,
235+
data: SteamAPIUserDataResponse,
228236
cache: Cache,
229237
) -> SteamUserData:
230238
"""Parse user data from the Steam API and return information on their games.
231239
232240
Args:
233-
data (Dict): user data from the Steam API
241+
data (SteamAPIUserDataResponse): user data from the Steam API
234242
cache (Cache): the loaded Cache file
235243
236244
Returns:
@@ -240,12 +248,12 @@ async def parse_steam_user_games(
240248
PrivateAccountError: if `games` is not present in `data['response']`
241249
(the user's account was found but is private)
242250
"""
243-
data = data['response']
251+
game_data = data['response']
244252

245-
if 'games' not in data:
253+
if 'games' not in game_data:
246254
raise PrivateAccountError
247255

248-
games = data['games']
256+
games = game_data['games']
249257
game_ratings = [
250258
Game(
251259
name=game['name'],

vapor/argument_handler.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,12 @@ def parse_args() -> None:
1515
),
1616
)
1717
parser.add_argument(
18-
'--clear-cache', action='store_true', help="Clear all of vapor's cache",
18+
'--clear-cache',
19+
action='store_true',
20+
help="Clear all of vapor's cache",
1921
)
2022

2123
args = parser.parse_args()
2224

23-
if args.clear_cache:
25+
if args.clear_cache: # pyright: ignore[reportAny]
2426
cache_handler.CACHE_PATH.unlink(missing_ok=True)

vapor/cache_handler.py

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,20 @@
22

33
import json
44
from datetime import datetime
5+
from pathlib import Path
56
from typing import Dict, List, Optional, Tuple
67

7-
from typing_extensions import Self
8+
from typing_extensions import Self, override
89

9-
from vapor.data_structures import CONFIG_DIR, AntiCheatData, AntiCheatStatus, Game
10+
from vapor.data_structures import (
11+
CONFIG_DIR,
12+
AntiCheatData,
13+
AntiCheatStatus,
14+
CacheFile,
15+
Game,
16+
SerializedAnticheatData,
17+
SerializedGameData,
18+
)
1019

1120
CACHE_PATH = CONFIG_DIR / 'cache.json'
1221
"""The path to the cache file."""
@@ -26,20 +35,21 @@ class Cache:
2635

2736
def __init__(self) -> None:
2837
"""Construct a new Cache object."""
29-
self.cache_path = CACHE_PATH
38+
self.cache_path: Path = CACHE_PATH
3039
self._games_data: Dict[str, Tuple[Game, str]] = {}
3140
self._anti_cheat_data: Dict[str, AntiCheatData] = {}
3241
self._anti_cheat_timestamp: str = ''
3342

43+
@override
3444
def __repr__(self) -> str:
3545
"""Return the string representation of the Cache object."""
3646
return f'Cache({self.__dict__!r})'
3747

38-
def _serialize_game_data(self) -> dict:
48+
def _serialize_game_data(self) -> Dict[str, SerializedGameData]:
3949
"""Serialize the game data into a valid JSON dict.
4050
4151
Returns:
42-
dict: Valid JSON dict.
52+
Dict[str, SerializedGameData]: Valid JSON dict.
4353
"""
4454
return {
4555
app_id: {
@@ -50,11 +60,11 @@ def _serialize_game_data(self) -> dict:
5060
for app_id, game in self._games_data.items()
5161
}
5262

53-
def _serialize_anti_cheat_data(self) -> dict:
63+
def _serialize_anti_cheat_data(self) -> SerializedAnticheatData:
5464
"""Serialize the anticheat data into a valid JSON dict.
5565
5666
Returns:
57-
dict: Valid JSON dict.
67+
SerializedAnticheatData: Valid JSON dict.
5868
"""
5969
return {
6070
'data': {
@@ -118,7 +128,7 @@ def load_cache(self, prune: Optional[bool] = True) -> Self:
118128
self.prune_cache()
119129

120130
try:
121-
data = json.loads(self.cache_path.read_text())
131+
data: CacheFile = json.loads(self.cache_path.read_text())
122132
except Exception:
123133
return self
124134

@@ -197,7 +207,7 @@ def prune_cache(self) -> Self:
197207
Self: self.
198208
"""
199209
try:
200-
data = json.loads(self.cache_path.read_text())
210+
data: CacheFile = json.loads(self.cache_path.read_text())
201211
except Exception:
202212
return self
203213

@@ -217,7 +227,8 @@ def prune_cache(self) -> Self:
217227
if 'anticheat_cache' in data:
218228
try:
219229
parsed_date = datetime.strptime(
220-
data['anticheat_cache']['timestamp'], TIMESTAMP_FORMAT,
230+
data['anticheat_cache']['timestamp'],
231+
TIMESTAMP_FORMAT,
221232
)
222233
if (datetime.now() - parsed_date).days > CACHE_INVALIDATION_DAYS:
223234
# cache is too old, delete game

vapor/config_handler.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Vapor configuration file handling."""
22

33
from configparser import ConfigParser
4+
from pathlib import Path
45
from typing import Optional
56

67
from typing_extensions import Self
@@ -20,7 +21,7 @@ class Config:
2021

2122
def __init__(self) -> None:
2223
"""Construct a new Config object."""
23-
self._config_path = CONFIG_PATH
24+
self._config_path: Path = CONFIG_PATH
2425
self._config_data: Optional[ConfigParser] = None
2526

2627
def set_value(self, key: str, value: str) -> Self:

0 commit comments

Comments
 (0)