Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 33 additions & 7 deletions pyhilo/util/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ class StateDict(TypedDict, total=False):
T = TypeVar("T", bound="StateDict")


def _get_defaults(cls: type[T]) -> dict[str, Any]:
def _get_defaults(cls: type[T]) -> T:
"""Generate a default dict based on typed dict

This function recursively creates a nested dictionary structure that mirrors
Expand Down Expand Up @@ -127,12 +127,38 @@ async def get_state(state_yaml: str) -> StateDict:
if not isfile(
state_yaml
): # noqa: PTH113 - isfile is fine and simpler in this case.
return _get_defaults(StateDict) # type: ignore
async with aiofiles.open(state_yaml, mode="r") as yaml_file:
LOG.debug("Loading state from yaml")
content = await yaml_file.read()
state_yaml_payload: StateDict = yaml.safe_load(content)
return state_yaml_payload
return _get_defaults(StateDict)

try:
async with aiofiles.open(state_yaml, mode="r") as yaml_file:
LOG.debug("Loading state from yaml")
content = await yaml_file.read()
state_yaml_payload: StateDict | None = yaml.safe_load(content)

# Handle corrupted/empty YAML files
if state_yaml_payload is None:
LOG.warning(
"State file %s is corrupted or empty, reinitializing with defaults",
state_yaml,
)
defaults = _get_defaults(StateDict)
async with aiofiles.open(state_yaml, mode="w") as yaml_file_write:
content = yaml.dump(defaults)
await yaml_file_write.write(content)
return defaults

return state_yaml_payload
except yaml.YAMLError as e:
LOG.error(
"Failed to parse state file %s: %s. Reinitializing with defaults.",
state_yaml,
e,
)
defaults = _get_defaults(StateDict)
async with aiofiles.open(state_yaml, mode="w") as yaml_file_write:
content = yaml.dump(defaults)
await yaml_file_write.write(content)
return defaults


async def set_state(
Expand Down