Changes Initial commit
This commit is contained in:
39
ota_agent/state_store.py
Normal file
39
ota_agent/state_store.py
Normal file
@@ -0,0 +1,39 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from .models import AgentState
|
||||
|
||||
|
||||
class StateStore:
|
||||
def __init__(self, state_file: str) -> None:
|
||||
self.path = Path(state_file)
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def load(self, vehicle_id: str, vin: str, current_release: str) -> AgentState:
|
||||
if not self.path.exists() or self._is_empty_file():
|
||||
state = AgentState(vehicle_id=vehicle_id, vin=vin, current_release=current_release)
|
||||
self.save(state)
|
||||
return state
|
||||
|
||||
try:
|
||||
raw = json.loads(self.path.read_text(encoding="utf-8"))
|
||||
except json.JSONDecodeError:
|
||||
state = AgentState(vehicle_id=vehicle_id, vin=vin, current_release=current_release)
|
||||
self.save(state)
|
||||
return state
|
||||
|
||||
raw["vehicle_id"] = vehicle_id
|
||||
raw["vin"] = vin
|
||||
raw["current_release"] = current_release
|
||||
return AgentState(**raw)
|
||||
|
||||
def save(self, state: AgentState) -> None:
|
||||
self.path.write_text(
|
||||
state.model_dump_json(indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
def _is_empty_file(self) -> bool:
|
||||
return self.path.stat().st_size == 0
|
||||
Reference in New Issue
Block a user