core/script/hassfest/mqtt.py

49 lines
1.4 KiB
Python
Raw Normal View History

"""Generate MQTT file."""
2021-03-18 21:58:19 +00:00
from __future__ import annotations
from collections import defaultdict
from .model import Config, Integration
2022-11-09 15:58:20 +00:00
from .serializer import format_python_namespace
2022-11-23 18:05:31 +00:00
def generate_and_validate(integrations: dict[str, Integration]) -> str:
"""Validate and generate MQTT data."""
data = defaultdict(list)
for domain in sorted(integrations):
mqtt = integrations[domain].manifest.get("mqtt")
if not mqtt:
continue
for topic in mqtt:
data[domain].append(topic)
2022-11-09 15:58:20 +00:00
return format_python_namespace({"MQTT": data})
2022-11-23 18:05:31 +00:00
def validate(integrations: dict[str, Integration], config: Config) -> None:
"""Validate MQTT file."""
mqtt_path = config.root / "homeassistant/generated/mqtt.py"
config.cache["mqtt"] = content = generate_and_validate(integrations)
if config.specific_integrations:
return
with open(str(mqtt_path)) as fp:
if fp.read() != content:
config.add_error(
"mqtt",
"File mqtt.py is not up to date. Run python3 -m script.hassfest",
fixable=True,
)
2022-11-23 18:05:31 +00:00
def generate(integrations: dict[str, Integration], config: Config) -> None:
"""Generate MQTT file."""
mqtt_path = config.root / "homeassistant/generated/mqtt.py"
with open(str(mqtt_path), "w") as fp:
fp.write(f"{config.cache['mqtt']}")