Skip to content

Commit 9135c6a

Browse files
committed
Hilo_state corruption logic
Add a recreation in case of corruption.
1 parent 4e70ee9 commit 9135c6a

2 files changed

Lines changed: 32 additions & 6 deletions

File tree

pyhilo/const.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import logging
22
import platform
3-
import uuid
43
from typing import Final
4+
import uuid
55

66
import aiohttp
77

pyhilo/util/state.py

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -128,11 +128,37 @@ async def get_state(state_yaml: str) -> StateDict:
128128
state_yaml
129129
): # noqa: PTH113 - isfile is fine and simpler in this case.
130130
return _get_defaults(StateDict) # type: ignore
131-
async with aiofiles.open(state_yaml, mode="r") as yaml_file:
132-
LOG.debug("Loading state from yaml")
133-
content = await yaml_file.read()
134-
state_yaml_payload: StateDict = yaml.safe_load(content)
135-
return state_yaml_payload
131+
132+
try:
133+
async with aiofiles.open(state_yaml, mode="r") as yaml_file:
134+
LOG.debug("Loading state from yaml")
135+
content = await yaml_file.read()
136+
state_yaml_payload: StateDict = yaml.safe_load(content)
137+
138+
# Handle corrupted/empty YAML files
139+
if state_yaml_payload is None:
140+
LOG.warning(
141+
"State file %s is corrupted or empty, reinitializing with defaults",
142+
state_yaml,
143+
)
144+
defaults = _get_defaults(StateDict) # type: ignore
145+
async with aiofiles.open(state_yaml, mode="w") as yaml_file_write:
146+
content = yaml.dump(defaults)
147+
await yaml_file_write.write(content)
148+
return defaults
149+
150+
return state_yaml_payload
151+
except yaml.YAMLError as e:
152+
LOG.error(
153+
"Failed to parse state file %s: %s. Reinitializing with defaults.",
154+
state_yaml,
155+
e,
156+
)
157+
defaults = _get_defaults(StateDict) # type: ignore
158+
async with aiofiles.open(state_yaml, mode="w") as yaml_file_write:
159+
content = yaml.dump(defaults)
160+
await yaml_file_write.write(content)
161+
return defaults
136162

137163

138164
async def set_state(

0 commit comments

Comments
 (0)