functioning manager

This commit is contained in:
ari committed 2022-01-03 21:25:00 -05:00
1 parent ef5715ea6c
commit 00505c0faa
8 files changed
+239 -54

No files matched your search

+8
View File
@@ -1,2 +1,10 @@
class AutomationLoaderException(Exception):
pass
class InvalidAutomationFile(AutomationLoaderException):
pass
class FailedDeletion(AutomationLoaderException):
pass
+16 -11
View File
@@ -1,8 +1,10 @@
from itertools import chain
from typing import Iterable, Iterator
from pydantic.error_wrappers import ValidationError
from src.json_serializer import normalize_obj
from .types import AutomationData, AutomationMetdata
from .parsers import _parse_actions
from .errors import InvalidAutomationFile
# Single loader
def load_automation(
@@ -19,15 +21,18 @@ def load_automation(
"""
for auto_raw in automations_raw_data:
yield AutomationData(
metadata=AutomationMetdata.parse_obj(auto_raw),
sequence=list(
_parse_actions(
chain(
auto_raw.get("condition", []),
auto_raw.get("action", []),
try:
yield AutomationData(
metadata=AutomationMetdata.parse_obj(auto_raw),
sequence=list(
_parse_actions(
chain(
auto_raw.get("condition", []),
auto_raw.get("action", []),
)
)
)
),
trigger=[normalize_obj(obj) for obj in auto_raw.get("trigger", [])],
)
),
trigger=[normalize_obj(obj) for obj in auto_raw.get("trigger", [])],
)
except ValidationError as err:
raise InvalidAutomationFile from err
+34 -1
View File
@@ -1,4 +1,5 @@
from typing import Iterator, Optional
from typing import Iterator, List, Optional
from src.automations.errors import FailedDeletion
from src.automations.types import AutomationData
from src.hass_config.loader import HassConfig
from .loader import load_automation
@@ -26,3 +27,35 @@ class AutomationManager:
if i == index:
return next(load_automation(([auto])))
return None
def update(self, index: int, automation: AutomationData):
automations: List[dict] = []
updated = False
for i, orig_auto in enumerate(self.hass_config.automations):
if i == index:
automations.append(automation.to_primitive())
updated = True
else:
automations.append(orig_auto)
if not updated:
automations.append(automation.to_primitive())
self.hass_config.save_automations(automations)
def delete(self, index: int):
automations: List[dict] = []
deleted = False
for i, orig_auto in enumerate(self.hass_config.automations):
if i == index:
deleted = True
else:
automations.append(orig_auto)
if not deleted:
raise FailedDeletion("No such automation found")
self.hass_config.save_automations(automations)
# TODO: improve on this without keeping things in memory
def get_total_items(self) -> int:
count = 0
for i, _ in enumerate(self.hass_config.automations):
count = i
return count + 1