additional api refactor
This commit is contained in:
1 parent
8792ed6ed8
commit
7cb1a5d907
11 files changed
+415
-271
No files matched your search
@@ -82,7 +82,7 @@ class AutomationDBConnection:
|
||||
"{automation.alias}",
|
||||
"{automation.description}",
|
||||
"{automation.mode}",
|
||||
"{automation.source_file.absolute()}",
|
||||
"{automation.source_file}",
|
||||
"{automation.source_file_type}",
|
||||
"{automation.configuration_key}",
|
||||
"{encode_auto(automation)}"
|
||||
|
||||
@@ -4,7 +4,7 @@ from typing import Any, Iterator, Tuple, Union
|
||||
from src.json_serializer import normalize_obj
|
||||
from src.logger import get_logger
|
||||
from src.utils import extract_files
|
||||
from src.yaml_serializer import load_yaml
|
||||
from src.yaml_serializer import dump_yaml, load_yaml
|
||||
from src.yaml_serializer.types import IncludedYaml, IncludedYamlDir
|
||||
|
||||
from ..hass_config.loader import HassConfig
|
||||
@@ -14,30 +14,62 @@ from .types import ExtenededAutomation
|
||||
|
||||
logger = get_logger(__file__)
|
||||
|
||||
AUTOMATION_CONFIGURATION_KEY = "automation shortumation"
|
||||
|
||||
|
||||
def extract_automation_paths(
|
||||
hass_config: HassConfig,
|
||||
) -> Iterator[Tuple[str, Path]]:
|
||||
) -> Iterator[Tuple[str, str]]:
|
||||
found = False
|
||||
for key, value in extract_automation_keys(hass_config):
|
||||
logger.info(f"Loading automations from '{key}'")
|
||||
found = True
|
||||
if isinstance(value, IncludedYaml):
|
||||
yield key, value.path_str
|
||||
elif isinstance(value, IncludedYamlDir):
|
||||
yield key, value.name
|
||||
else:
|
||||
logger.warning(f"found an invalid type in {key}!")
|
||||
if not found:
|
||||
yield "", "automations.yaml"
|
||||
|
||||
|
||||
def get_base_automation_key(hass_config: HassConfig):
|
||||
found_any = False
|
||||
for key, value in extract_automation_keys(hass_config):
|
||||
found_any = True
|
||||
if isinstance(value, IncludedYaml):
|
||||
return key, value.path_str
|
||||
configurations = hass_config.configurations
|
||||
if found_any:
|
||||
out_path = hass_config.get_backup_automation_file_path()
|
||||
else:
|
||||
out_path = hass_config.get_default_automation_path()
|
||||
out_file = str(out_path.relative_to(hass_config.root_path))
|
||||
configurations[AUTOMATION_CONFIGURATION_KEY] = IncludedYaml(out_file)
|
||||
out_path.touch(exist_ok=True)
|
||||
with hass_config.get_configuration_path().open("w") as fp:
|
||||
fp.write(dump_yaml(configurations))
|
||||
return AUTOMATION_CONFIGURATION_KEY, out_file
|
||||
|
||||
|
||||
def extract_automation_keys(
|
||||
hass_config: HassConfig,
|
||||
) -> Iterator[Tuple[str, Union[IncludedYaml, IncludedYamlDir]]]:
|
||||
for key, value in hass_config.configurations.items():
|
||||
if str(key).startswith("automation"):
|
||||
logger.info(f"Loading automations from '{key}'")
|
||||
found = True
|
||||
if isinstance(value, dict):
|
||||
if isinstance(value, dict) or isinstance(value, list):
|
||||
raise NotImplementedError(
|
||||
"No support for automations baked into configuration.yaml! Please extract these into a seperate file"
|
||||
)
|
||||
elif isinstance(value, IncludedYaml):
|
||||
yield key, hass_config.root_path / value.path_str
|
||||
elif isinstance(value, IncludedYamlDir):
|
||||
yield key, hass_config.root_path / value.name
|
||||
elif isinstance(value, IncludedYaml) or isinstance(value, IncludedYamlDir):
|
||||
yield key, value
|
||||
else:
|
||||
logger.warning(f"found an invalid type in {key}!")
|
||||
if not found:
|
||||
yield "", hass_config.root_path / "automations.yaml"
|
||||
|
||||
|
||||
def load_automation_path(
|
||||
root_path: Path,
|
||||
automation_path: Path,
|
||||
configuration_key: str,
|
||||
tag_manager: TagManager,
|
||||
@@ -57,7 +89,7 @@ def load_automation_path(
|
||||
return
|
||||
if automation_path.is_dir():
|
||||
for f in extract_files(automation_path):
|
||||
yield from load_automation_path(f, configuration_key, tag_manager)
|
||||
yield from load_automation_path(root_path, f, configuration_key, tag_manager)
|
||||
else:
|
||||
try:
|
||||
with automation_path.open("r") as fp:
|
||||
@@ -75,7 +107,7 @@ def load_automation_path(
|
||||
**clean_automation(automations),
|
||||
tags=tag_manager.get(automations["id"], {}),
|
||||
configuration_key=configuration_key,
|
||||
source_file=str(automation_path),
|
||||
source_file=str(automation_path.relative_to(root_path)),
|
||||
source_file_type="obj",
|
||||
)
|
||||
except Exception as err:
|
||||
@@ -94,7 +126,7 @@ def load_automation_path(
|
||||
**clean_automation(automation),
|
||||
tags=tag_manager.get(automation["id"], {}),
|
||||
configuration_key=configuration_key,
|
||||
source_file=str(automation_path),
|
||||
source_file=str(automation_path.relative_to(root_path)),
|
||||
source_file_type="list",
|
||||
)
|
||||
except Exception as err:
|
||||
|
||||
@@ -14,9 +14,9 @@ from .errors import (
|
||||
DBError,
|
||||
InvalidAutomationFile,
|
||||
)
|
||||
from .loader import extract_automation_paths, load_automation_path
|
||||
from .loader import extract_automation_paths, get_base_automation_key, load_automation_path
|
||||
from .tags import TagManager
|
||||
from .types import ExtenededAutomation
|
||||
from .types import Automation, ExtenededAutomation
|
||||
|
||||
logger = get_logger(__file__)
|
||||
|
||||
@@ -45,7 +45,14 @@ class AutomationManager:
|
||||
errors = []
|
||||
for config_key, p in extract_automation_paths(self.hass_config):
|
||||
try:
|
||||
automations = list(load_automation_path(p, config_key, self.tag_manager))
|
||||
automations = list(
|
||||
load_automation_path(
|
||||
self.hass_config.root_path,
|
||||
self.hass_config.root_path / p,
|
||||
config_key,
|
||||
self.tag_manager,
|
||||
)
|
||||
)
|
||||
self.db.insert_automations(automations)
|
||||
except InvalidAutomationFile as e:
|
||||
logger.warning(e)
|
||||
@@ -65,32 +72,45 @@ class AutomationManager:
|
||||
def get(self, auto_id: str):
|
||||
return self.db.get_automation(auto_id)
|
||||
|
||||
def upsert(self, automation: ExtenededAutomation):
|
||||
if not automation.source_file.parent.exists():
|
||||
automation.source_file.parent.mkdir(parents=True)
|
||||
def create(self, automation: Automation):
|
||||
config_key, config_path = get_base_automation_key(self.hass_config)
|
||||
return self.update(
|
||||
ExtenededAutomation(
|
||||
**automation.dict(),
|
||||
configuration_key=config_key,
|
||||
source_file=config_path,
|
||||
source_file_type="list",
|
||||
),
|
||||
create_if_not_found=True,
|
||||
)
|
||||
|
||||
def update(self, automation: ExtenededAutomation, create_if_not_found: bool = False):
|
||||
automation_path = self.hass_config.root_path / automation.source_file
|
||||
if not automation_path.parent.exists():
|
||||
automation_path.parent.mkdir(parents=True)
|
||||
|
||||
objs: Optional[Union[list, dict]] = None
|
||||
if automation.source_file.exists():
|
||||
with automation.source_file.open("r") as fp:
|
||||
if automation_path.exists():
|
||||
with automation_path.open("r") as fp:
|
||||
objs = load_yaml(fp)
|
||||
|
||||
if automation.source_file_type == "obj":
|
||||
if isinstance(objs, list):
|
||||
raise AttemptingToOverwriteAnIncompatibleFileError(
|
||||
f"{automation.source_file} is a list, but expected a obj for {automation}"
|
||||
f"{automation_path} is a list, but expected a obj for {automation}"
|
||||
)
|
||||
raw_auto = automation.to_primitive(include_tags=False)
|
||||
automation.source_file.write_text(dump_yaml(raw_auto))
|
||||
automation_path.write_text(dump_yaml(raw_auto))
|
||||
else:
|
||||
if isinstance(objs, dict):
|
||||
raise AttemptingToOverwriteAnIncompatibleFileError(
|
||||
f"{automation.source_file} is a list, but expected a obj for {automation}"
|
||||
f"{automation_path} is a list, but expected a obj for {automation}"
|
||||
)
|
||||
elif objs is None:
|
||||
objs = []
|
||||
if not isinstance(objs, list):
|
||||
raise AssertionError(
|
||||
f"Attemption to save automation to {automation.source_file} but encountering an invalid list yaml file. Did you modify this file prior to saving?\n{automation}"
|
||||
f"Attemption to save automation to {automation_path} but encountering an invalid list yaml file. Did you modify this file prior to saving?\n{automation}"
|
||||
)
|
||||
found = False
|
||||
for i, obj in enumerate(objs):
|
||||
@@ -99,8 +119,13 @@ class AutomationManager:
|
||||
found = True
|
||||
break
|
||||
if not found:
|
||||
objs.append(automation.to_primitive(include_tags=False))
|
||||
automation.source_file.write_text(dump_yaml(objs))
|
||||
if create_if_not_found:
|
||||
objs.append(automation.to_primitive(include_tags=False))
|
||||
else:
|
||||
raise InvalidAutomationFile(
|
||||
"Could not update automations, not found in source file."
|
||||
)
|
||||
automation_path.write_text(dump_yaml(objs))
|
||||
self.update_tags(automation.id, automation.tags)
|
||||
|
||||
def update_tags(self, automation_id: str, tags: Dict[str, str]):
|
||||
@@ -115,18 +140,19 @@ class AutomationManager:
|
||||
self.tag_manager.save(self.tag_path)
|
||||
|
||||
def delete(self, automation: ExtenededAutomation):
|
||||
automation_path = self.hass_config.root_path / automation.source_file
|
||||
if automation.source_file_type == "obj":
|
||||
automation.source_file.unlink(missing_ok=True)
|
||||
automation_path.unlink(missing_ok=True)
|
||||
else:
|
||||
with automation.source_file.open("r") as fp:
|
||||
with automation_path.open("r") as fp:
|
||||
objs = load_yaml(fp)
|
||||
if not isinstance(objs, list):
|
||||
raise AssertionError(
|
||||
f"Attemption to save automation to {automation.source_file} but encountering an invalid list yaml file. Did you modify this file prior to saving?\n{automation}"
|
||||
f"Attemption to save automation to {automation_path} but encountering an invalid list yaml file. Did you modify this file prior to saving?\n{automation}"
|
||||
)
|
||||
kept = []
|
||||
for i, obj in enumerate(objs):
|
||||
if obj["id"] != automation.id:
|
||||
kept.append(obj)
|
||||
automation.source_file.write_text(dump_yaml(kept))
|
||||
automation_path.write_text(dump_yaml(kept))
|
||||
self.delete_tags(automation.id)
|
||||
@@ -20,20 +20,27 @@ class BaseAutomation(BaseModel):
|
||||
return self.dict(exclude_unset=True, exclude_none=True)
|
||||
|
||||
|
||||
class ExtenededAutomation(BaseAutomation):
|
||||
source_file: Path
|
||||
source_file_type: Literal["list", "obj"]
|
||||
configuration_key: str
|
||||
class Automation(BaseAutomation):
|
||||
tags: Dict[str, str] = Field(default_factory=dict)
|
||||
|
||||
def to_primitive(self, include_tags: bool = False):
|
||||
out = super().to_primitive()
|
||||
del out["source_file"]
|
||||
del out["source_file_type"]
|
||||
del out["configuration_key"]
|
||||
if not include_tags and out.get("tags", None) is not None:
|
||||
del out["tags"]
|
||||
return out
|
||||
|
||||
|
||||
class ExtenededAutomation(Automation):
|
||||
source_file: str
|
||||
source_file_type: Literal["list", "obj"]
|
||||
configuration_key: str
|
||||
|
||||
def to_primitive(self, include_tags: bool = False):
|
||||
out = super().to_primitive(include_tags=include_tags)
|
||||
del out["source_file"]
|
||||
del out["source_file_type"]
|
||||
del out["configuration_key"]
|
||||
return out
|
||||
|
||||
def to_json(self):
|
||||
return json.loads(self.json())
|
||||
Reference in new issue
Block a user