Skip to content

Commit

Permalink
hp: better support for RequiredMsg/Required
Browse files Browse the repository at this point in the history
also better logging errors.
  • Loading branch information
th3w1zard1 committed Apr 25, 2024
1 parent b753294 commit 4af037b
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 16 deletions.
4 changes: 2 additions & 2 deletions Libraries/PyKotor/src/pykotor/tslpatcher/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ def __init__(self):
self.confirm_message: str = ""
self.game_number: int | None = None

self.required_file: str | None = None
self.required_message: str = ""
self.required_files: list[tuple[str, ...]] = []
self.required_messages: list[str] = []
self.save_processed_scripts: int = 0
self.log_level: LogLevel = LogLevel.WARNINGS

Expand Down
4 changes: 3 additions & 1 deletion Libraries/PyKotor/src/pykotor/tslpatcher/mods/twoda.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from pykotor.tools.path import CaseAwarePath
from pykotor.tslpatcher.mods.template import PatcherModifications
from utility.error_handling import format_exception_with_variables, universal_simplify_exception
from utility.logger_util import get_root_logger
from utility.system.path import PureWindowsPath

if TYPE_CHECKING:
Expand All @@ -33,7 +34,7 @@ class TargetType(IntEnum):


class Target:
def __init__(self, target_type: TargetType, value: str | int):
def __init__(self, target_type: TargetType, value: str | int | RowValue2DAMemory | RowValueTLKMemory):
self.target_type: TargetType = target_type
self.value: str | int | RowValueTLKMemory | RowValue2DAMemory = value

Expand Down Expand Up @@ -573,6 +574,7 @@ def apply(
f.write(f"\n{detailed_msg}")
if isinstance(e, WarningError):
logger.add_warning(msg)
get_root_logger().debug(msg, exc_info=True)
else:
logger.add_error(msg)
break
18 changes: 10 additions & 8 deletions Libraries/PyKotor/src/pykotor/tslpatcher/patcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from pykotor.tslpatcher.mods.install import InstallFile, create_backup
from pykotor.tslpatcher.mods.template import OverrideType
from utility.error_handling import format_exception_with_variables, universal_simplify_exception
from utility.logger_util import get_root_logger
from utility.system.path import PurePath

if TYPE_CHECKING:
Expand Down Expand Up @@ -99,10 +100,12 @@ def config(self) -> PatcherConfig:
self._config = PatcherConfig()
self._config.load(ini_text, self.mod_path, self.log)

if self._config.required_file:
requiredfile_path: CaseAwarePath = self.game_path / "Override" / self._config.required_file
if not requiredfile_path.safe_isfile():
raise ImportError(self._config.required_message.strip() or "cannot install - missing a required mod")
if self._config.required_files:
for i, files in enumerate(self._config.required_files):
for file in files:
requiredfile_path: CaseAwarePath = self.game_path / "Override" / file
if not requiredfile_path.safe_isfile():
raise ImportError(self._config.required_messages[i].strip() or "cannot install - missing a required mod")
return self._config

def backup(self) -> tuple[CaseAwarePath, set]:
Expand Down Expand Up @@ -425,10 +428,9 @@ def install(
except Exception as e: # pylint: disable=W0718 # noqa: BLE001
exc_type, exc_msg = universal_simplify_exception(e)
fmt_exc_str = f"{exc_type}: {exc_msg}"
self.log.add_error(f"An error occurred in patchlist {patch.__class__.__name__}:\n{fmt_exc_str}\n")
detailed_error = format_exception_with_variables(e)
with CaseAwarePath.cwd().joinpath("errorlog.txt").open("a", encoding="utf-8") as f:
f.write(f"\n{detailed_error}")
msg = f"An error occurred in patchlist {patch.__class__.__name__}:\n{fmt_exc_str}\n"
self.log.add_error(msg)
get_root_logger().exception(msg)
if progress_update_func is not None:
progress_update_func()

Expand Down
28 changes: 23 additions & 5 deletions Libraries/PyKotor/src/pykotor/tslpatcher/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,8 +230,26 @@ def load_settings(self):

self.config.window_title = settings_ini.get("WindowCaption", "")
self.config.confirm_message = settings_ini.get("ConfirmMessage", "")
self.config.required_file = settings_ini.get("Required")
self.config.required_message = settings_ini.get("RequiredMsg", "")
for key, value in settings_ini.items():
lower_key = key.lower()
if (
lower_key == "required"
or lower_key.startswith("required") and len(key) > len("required") and not key[len("required"):].lower().startswith("msg")
):
if lower_key != "required" and not key[len("required"):].isdigit():
raise ValueError(f"Key '{key}' improperly defined in settings ini. Expected (Required) or (RequiredMsg)")
these_files = tuple(filename.strip() for filename in value.split(","))
self.config.required_files.append(these_files)

if (
lower_key == "requiredmsg"
or lower_key.startswith("requiredmsg") and len(key) > len("requiredmsg")
):
if lower_key != "requiredmsg" and not key[len("requiredmsg"):].isdigit():
raise ValueError(f"Key '{key}' improperly defined in settings ini. Expected (Required) or (RequiredMsg)")
self.config.required_messages.append(value.strip())
if len(self.config.required_files) != len(self.config.required_messages):
raise ValueError(f"Required files definitions must match required msg count ({len(self.config.required_files)}/{len(self.config.required_messages)})")
self.config.save_processed_scripts = int(settings_ini.get("SaveProcessedScripts", 0))
self.config.log_level = LogLevel(int(settings_ini.get("LogLevel", LogLevel.WARNINGS.value)))

Expand Down Expand Up @@ -1260,9 +1278,9 @@ def get_target(
msg = f"[2DAList] parse error: '{key}' missing from [{identifier}] in ini."
raise ValueError(msg)
lower_raw_value = raw_value.lower()
if lower_raw_value.startswith("strref"):
if lower_raw_value.startswith("strref") and len(raw_value) > "strref" and raw_value[6:].isdigit():
value: str | int | RowValue2DAMemory | RowValueTLKMemory = RowValueTLKMemory(int(raw_value[6:]))
elif lower_raw_value.startswith("2damemory"):
elif lower_raw_value.startswith("2damemory") and len(raw_value) > "2damemory" and raw_value[9:].isdigit():
value = RowValue2DAMemory(int(raw_value[9:]))
else:
value = int(raw_value) if is_int else raw_value
Expand All @@ -1275,7 +1293,7 @@ def get_target(
if "LabelIndex" in modifiers:
return get_target(TargetType.LABEL_COLUMN, "LabelIndex")

self.log.add_warning(f"No line set to be modified in [{identifier}].") # TODO: should raise an exception?
self.log.add_warning(f"No line set to be modified in [{identifier}].")
return None

def cells_2da(
Expand Down

0 comments on commit 4af037b

Please sign in to comment.