impr(external): ArcaeaParser file reading

This commit is contained in:
283375 2023-09-16 02:40:56 +08:00
parent 6258a55ba4
commit 5796d9a80f
Signed by: 283375
SSH Key Fingerprint: SHA256:UcX0qg6ZOSDOeieKPGokA5h7soykG61nz2uxuQgVLSk
3 changed files with 22 additions and 4 deletions

View File

@ -1,3 +1,4 @@
import contextlib
import json
from os import PathLike
from typing import Any, List, Optional, Union
@ -43,6 +44,25 @@ class ArcaeaParser:
def __init__(self, filepath: Union[str, bytes, PathLike]):
self.filepath = filepath
def read_file_text(self):
file_handle = None
with contextlib.suppress(TypeError):
# original open
file_handle = open(self.filepath, "r", encoding="utf-8")
if file_handle is None:
try:
# or maybe a `pathlib.Path` subset
# or an `importlib.resources.abc.Traversable` like object
# e.g. `zipfile.Path`
file_handle = self.filepath.open(mode="r", encoding="utf-8")
except Exception as e:
raise ValueError("Invalid `filepath`.") from e
with file_handle:
return file_handle.read()
def parse(self) -> List[DeclarativeBase]:
...

View File

@ -10,8 +10,7 @@ class PacklistParser(ArcaeaParser):
super().__init__(filepath)
def parse(self) -> List[Union[Pack, PackLocalized]]:
with open(self.filepath, "r", encoding="utf-8") as pl_f:
packlist_json_root = json.loads(pl_f.read())
packlist_json_root = json.loads(self.read_file_text())
packlist_json = packlist_json_root["packs"]
results: List[Union[Pack, PackLocalized]] = [

View File

@ -12,8 +12,7 @@ class SonglistParser(ArcaeaParser):
def parse(
self,
) -> List[Union[Song, SongLocalized, Difficulty, DifficultyLocalized]]:
with open(self.filepath, "r", encoding="utf-8") as sl_f:
songlist_json_root = json.loads(sl_f.read())
songlist_json_root = json.loads(self.read_file_text())
songlist_json = songlist_json_root["songs"]
results = []