init home-assistant

This commit is contained in:
2026-11-19 15:15:32 -05:00
parent 2e81d9d300
commit feec6ef9fb
19230 changed files with 3335526 additions and 0 deletions

View File

@@ -0,0 +1 @@
"""Home Assistant scripts."""

View File

@@ -0,0 +1,67 @@
"""Check if upstream Alexa locales are subset of the core Alexa supported locales."""
from pprint import pprint
import re
from bs4 import BeautifulSoup
import requests
from homeassistant.components.alexa import capabilities
SITE = (
"https://developer.amazon.com/en-GB/docs/alexa/device-apis/list-of-interfaces.html"
)
def run_script() -> None:
"""Run the script."""
response = requests.get(SITE, timeout=10)
soup = BeautifulSoup(response.text, "html.parser")
table = soup.find("table")
table_body = table.find_all("tbody")[-1]
rows = table_body.find_all("tr")
data = [[ele.text.strip() for ele in row.find_all("td") if ele] for row in rows]
upstream_locales_raw = {row[0]: row[3] for row in data}
language_pattern = re.compile(r"^[a-z]{2}-[A-Z]{2}$")
upstream_locales = {
upstream_interface: {
name
for word in upstream_locale.split(" ")
if (name := word.strip(",")) and language_pattern.match(name) is not None
}
for upstream_interface, upstream_locale in upstream_locales_raw.items()
if upstream_interface.count(".") == 1 # Skip sub-interfaces
}
interfaces_missing = {}
interfaces_nok = {}
interfaces_ok = {}
for upstream_interface, upstream_locale in upstream_locales.items():
core_interface_name = upstream_interface.replace(".", "")
core_interface = getattr(capabilities, core_interface_name, None)
if core_interface is None:
interfaces_missing[upstream_interface] = upstream_locale
continue
core_locale = core_interface.supported_locales
if not upstream_locale.issubset(core_locale):
interfaces_nok[core_interface_name] = core_locale
else:
interfaces_ok[core_interface_name] = core_locale
print("Missing interfaces:")
pprint(list(interfaces_missing))
print("\n")
print("Interfaces where upstream locales are not subsets of the core locales:")
pprint(list(interfaces_nok))
print("\n")
print("Interfaces checked ok:")
pprint(list(interfaces_ok))
if __name__ == "__main__":
run_script()

View File

@@ -0,0 +1,70 @@
"""Helper script to update supported languages for Amazone Polly text-to-speech (TTS).
N.B. This script requires AWS credentials.
"""
from dataclasses import dataclass
from pathlib import Path
from typing import Self
import boto3
from .hassfest.serializer import format_python_namespace
@dataclass(frozen=True)
class AmazonPollyVoice:
"""Amazon Polly Voice."""
id: str
name: str
gender: str
language_name: str
language_code: str
supported_engines: set[str]
additional_language_codes: set[str]
@classmethod
def validate(cls, model: dict[str, str | list[str]]) -> Self:
"""Validate data model."""
return cls(
id=model["Id"],
name=model["Name"],
gender=model["Gender"],
language_name=model["LanguageName"],
language_code=model["LanguageCode"],
supported_engines=set(model["SupportedEngines"]),
additional_language_codes=set(model.get("AdditionalLanguageCodes", [])),
)
def get_all_voices(client: boto3.client) -> list[AmazonPollyVoice]:
"""Get list of all supported voices from Amazon Polly."""
response = client.describe_voices()
return [AmazonPollyVoice.validate(voice) for voice in response["Voices"]]
supported_regions = set(
boto3.session.Session().get_available_regions(service_name="polly")
)
polly_client = boto3.client(service_name="polly", region_name="us-east-1")
voices = get_all_voices(polly_client)
supported_voices = set({v.id for v in voices})
supported_engines = set().union(*[v.supported_engines for v in voices])
Path("homeassistant/generated/amazon_polly.py").write_text(
format_python_namespace(
{
"SUPPORTED_VOICES": supported_voices,
"SUPPORTED_REGIONS": supported_regions,
"SUPPORTED_ENGINES": supported_engines,
},
annotations={
"SUPPORTED_VOICES": "Final[set[str]]",
"SUPPORTED_REGIONS": "Final[set[str]]",
"SUPPORTED_ENGINES": "Final[set[str]]",
},
generator="script.amazon_polly",
)
)

12
home-assistant/script/bootstrap Executable file
View File

@@ -0,0 +1,12 @@
#!/bin/sh
# Resolve all dependencies that the application requires to run.
# Stop on errors
set -e
cd "$(dirname "$0")/.."
echo "Installing development dependencies..."
uv pip install wheel --constraint homeassistant/package_constraints.txt --upgrade
uv pip install colorlog $(grep awesomeversion requirements.txt) --constraint homeassistant/package_constraints.txt --upgrade
uv pip install -r requirements_test.txt -c homeassistant/package_constraints.txt --upgrade

View File

@@ -0,0 +1,7 @@
#!/bin/bash
[[ -z $(git ls-files --others --exclude-standard) ]] && exit 0
echo -e '\n***** ERROR\nTests are leaving files behind. Please update the tests to avoid writing any files:'
git ls-files --others --exclude-standard
echo
exit 1

View File

@@ -0,0 +1,10 @@
#!/bin/sh
# Format code with ruff-format.
cd "$(dirname "$0")/.."
ruff \
format \
--check \
--quiet \
homeassistant tests script *.py

View File

@@ -0,0 +1,5 @@
"""Script constants."""
from pathlib import Path
COMPONENT_DIR = Path("homeassistant/components")

View File

@@ -0,0 +1,29 @@
"""Helper script to update country list.
ISO does not publish a machine readable list free of charge, so the list is generated
with help of the pycountry package.
"""
from pathlib import Path
import pycountry
from .hassfest.serializer import format_python_namespace
countries = {x.alpha_2 for x in pycountry.countries}
generator_string = """script.countries
The values are directly corresponding to the ISO 3166 standard. If you need changes
to the political situation in the world, please contact the ISO 3166 working group.
"""
Path("homeassistant/generated/countries.py").write_text(
format_python_namespace(
{
"COUNTRIES": countries,
},
generator=generator_string,
annotations={"COUNTRIES": "Final[set[str]]"},
)
)

View File

@@ -0,0 +1,45 @@
"""Helper script to update currency list from the official source."""
from pathlib import Path
from bs4 import BeautifulSoup
import requests
from .hassfest.serializer import format_python_namespace
req = requests.get(
"https://www.six-group.com/dam/download/financial-information/data-center/iso-currrency/lists/list-one.xml"
)
soup = BeautifulSoup(req.content, "xml")
active_currencies = {
x.Ccy.contents[0]
for x in soup.ISO_4217.CcyTbl.children
if x.name == "CcyNtry"
and x.Ccy
and x.CcyMnrUnts.contents[0] != "N.A."
and "IsFund" not in x.CcyNm.attrs
and x.Ccy.contents[0] != "UYW"
}
req = requests.get(
"https://www.six-group.com/dam/download/financial-information/data-center/iso-currrency/lists/list-three.xml"
)
soup = BeautifulSoup(req.content, "xml")
historic_currencies = {
x.Ccy.contents[0]
for x in soup.ISO_4217.HstrcCcyTbl.children
if x.name == "HstrcCcyNtry"
and x.Ccy
and "IsFund" not in x.CcyNm.attrs
and x.Ccy.contents[0] not in active_currencies
}
Path("homeassistant/generated/currencies.py").write_text(
format_python_namespace(
{
"ACTIVE_CURRENCIES": active_currencies,
"HISTORIC_CURRENCIES": historic_currencies,
},
generator="script.currencies",
)
)

View File

@@ -0,0 +1,637 @@
#!/usr/bin/env python3
"""Generate updated constraint and requirements files."""
from __future__ import annotations
import difflib
import importlib
from operator import itemgetter
from pathlib import Path
import pkgutil
import re
import sys
import tomllib
from typing import Any
from homeassistant.util.yaml.loader import load_yaml
from script.hassfest.model import Config, Integration
# Requirements which can't be installed on all systems because they rely on additional
# system packages. Requirements listed in EXCLUDED_REQUIREMENTS_ALL will be commented-out
# in requirements_all.txt and requirements_test_all.txt.
EXCLUDED_REQUIREMENTS_ALL = {
"atenpdu", # depends on pysnmp which is not maintained at this time
"avea", # depends on bluepy
"avion",
"beacontools",
"beewi-smartclim", # depends on bluepy
"bluepy",
"decora",
"decora-wifi",
"evdev",
"face-recognition",
"pybluez",
"pycocotools",
"pycups",
"python-gammu",
"python-lirc",
"pyuserinput",
"tensorflow",
"tf-models-official",
}
# Requirements excluded by EXCLUDED_REQUIREMENTS_ALL which should be included when
# building integration wheels for all architectures.
INCLUDED_REQUIREMENTS_WHEELS = {
"decora-wifi",
"evdev",
"pycups",
"python-gammu",
"pyuserinput",
}
# Requirements to exclude or include when running github actions.
# Requirements listed in "exclude" will be commented-out in
# requirements_all_{action}.txt
# Requirements listed in "include" must be listed in EXCLUDED_REQUIREMENTS_CI, and
# will be included in requirements_all_{action}.txt
OVERRIDDEN_REQUIREMENTS_ACTIONS = {
"pytest": {
"exclude": set(),
"include": {"python-gammu"},
"markers": {},
},
"wheels_aarch64": {
"exclude": set(),
"include": INCLUDED_REQUIREMENTS_WHEELS,
"markers": {},
},
# Pandas has issues building on armhf, it is expected they
# will drop the platform in the near future (they consider it
# "flimsy" on 386). The following packages depend on pandas,
# so we comment them out.
"wheels_armhf": {
"exclude": {"env-canada", "noaa-coops", "pyezviz", "pykrakenapi"},
"include": INCLUDED_REQUIREMENTS_WHEELS,
"markers": {},
},
"wheels_armv7": {
"exclude": set(),
"include": INCLUDED_REQUIREMENTS_WHEELS,
"markers": {},
},
"wheels_amd64": {
"exclude": set(),
"include": INCLUDED_REQUIREMENTS_WHEELS,
"markers": {},
},
"wheels_i386": {
"exclude": set(),
"include": INCLUDED_REQUIREMENTS_WHEELS,
"markers": {},
},
}
IGNORE_PIN = ("colorlog>2.1,<3", "urllib3")
URL_PIN = (
"https://developers.home-assistant.io/docs/"
"creating_platform_code_review.html#1-requirements"
)
CONSTRAINT_PATH = (
Path(__file__).parent.parent / "homeassistant" / "package_constraints.txt"
)
CONSTRAINT_BASE = """
# Constrain pycryptodome to avoid vulnerability
# see https://github.com/home-assistant/core/pull/16238
pycryptodome>=3.6.6
# Constrain httplib2 to protect against GHSA-93xj-8mrv-444m
# https://github.com/advisories/GHSA-93xj-8mrv-444m
httplib2>=0.19.0
# gRPC is an implicit dependency that we want to make explicit so we manage
# upgrades intentionally. It is a large package to build from source and we
# want to ensure we have wheels built.
grpcio==1.67.1
grpcio-status==1.67.1
grpcio-reflection==1.67.1
# This is a old unmaintained library and is replaced with pycryptodome
pycrypto==1000000000.0.0
# This is a old unmaintained library and is replaced with faust-cchardet
cchardet==1000000000.0.0
# To remove reliance on typing
btlewrap>=0.0.10
# This overrides a built-in Python package
enum34==1000000000.0.0
typing==1000000000.0.0
uuid==1000000000.0.0
# httpx requires httpcore, and httpcore requires anyio and h11, but the version constraints on
# these requirements are quite loose. As the entire stack has some outstanding issues, and
# even newer versions seem to introduce new issues, it's useful for us to pin all these
# requirements so we can directly link HA versions to these library versions.
anyio==4.7.0
h11==0.14.0
httpcore==1.0.5
# Ensure we have a hyperframe version that works in Python 3.10
# 5.2.0 fixed a collections abc deprecation
hyperframe>=5.2.0
# Ensure we run compatible with musllinux build env
numpy==2.2.0
pandas~=2.2.3
# Constrain multidict to avoid typing issues
# https://github.com/home-assistant/core/pull/67046
multidict>=6.0.2
# Version 2.0 added typing, prevent accidental fallbacks
backoff>=2.0
# ensure pydantic version does not float since it might have breaking changes
pydantic==2.10.4
# Required for Python 3.12.4 compatibility (#119223).
mashumaro>=3.13.1
# Breaks asyncio
# https://github.com/pubnub/python/issues/130
pubnub!=6.4.0
# Package's __init__.pyi stub has invalid syntax and breaks mypy
# https://github.com/dahlia/iso4217/issues/16
iso4217!=1.10.20220401
# pyOpenSSL 24.0.0 or later required to avoid import errors when
# cryptography 42.0.0 is installed with botocore
pyOpenSSL>=24.0.0
# protobuf must be in package constraints for the wheel
# builder to build binary wheels
protobuf==5.29.2
# faust-cchardet: Ensure we have a version we can build wheels
# 2.1.18 is the first version that works with our wheel builder
faust-cchardet>=2.1.18
# websockets 13.1 is the first version to fully support the new
# asyncio implementation. The legacy implementation is now
# deprecated as of websockets 14.0.
# https://websockets.readthedocs.io/en/13.0.1/howto/upgrade.html#missing-features
# https://websockets.readthedocs.io/en/stable/howto/upgrade.html
websockets>=13.1
# pysnmplib is no longer maintained and does not work with newer
# python
pysnmplib==1000000000.0.0
# The get-mac package has been replaced with getmac. Installing get-mac alongside getmac
# breaks getmac due to them both sharing the same python package name inside 'getmac'.
get-mac==1000000000.0.0
# We want to skip the binary wheels for the 'charset-normalizer' packages.
# They are build with mypyc, but causes issues with our wheel builder.
# In order to do so, we need to constrain the version.
charset-normalizer==3.4.0
# dacite: Ensure we have a version that is able to handle type unions for
# NAM, Brother, and GIOS.
dacite>=1.7.0
# chacha20poly1305-reuseable==0.12.x is incompatible with cryptography==43.0.x
chacha20poly1305-reuseable>=0.13.0
# pycountry<23.12.11 imports setuptools at run time
# https://github.com/pycountry/pycountry/blob/ea69bab36f00df58624a0e490fdad4ccdc14268b/HISTORY.txt#L39
pycountry>=23.12.11
# scapy==2.6.0 causes CI failures due to a race condition
scapy>=2.6.1
# tuf isn't updated to deal with breaking changes in securesystemslib==1.0.
# Only tuf>=4 includes a constraint to <1.0.
# https://github.com/theupdateframework/python-tuf/releases/tag/v4.0.0
tuf>=4.0.0
# https://github.com/jd/tenacity/issues/471
tenacity!=8.4.0
# 5.0.0 breaks Timeout as a context manager
# TypeError: 'Timeout' object does not support the context manager protocol
async-timeout==4.0.3
# aiofiles keeps getting downgraded by custom components
# causing newer methods to not be available and breaking
# some integrations at startup
# https://github.com/home-assistant/core/issues/127529
# https://github.com/home-assistant/core/issues/122508
# https://github.com/home-assistant/core/issues/118004
aiofiles>=24.1.0
"""
GENERATED_MESSAGE = (
f"# Automatically generated by {Path(__file__).name}, do not edit\n\n"
)
IGNORE_PRE_COMMIT_HOOK_ID = (
"check-executables-have-shebangs",
"check-json",
"no-commit-to-branch",
"prettier",
"python-typing-update",
"ruff-format", # it's just ruff
)
PACKAGE_REGEX = re.compile(r"^(?:--.+\s)?([-_\.\w\d]+).*==.+$")
def has_tests(module: str) -> bool:
"""Test if a module has tests.
Module format: homeassistant.components.hue
Test if exists: tests/components/hue/__init__.py
"""
path = (
Path(module.replace(".", "/").replace("homeassistant", "tests")) / "__init__.py"
)
return path.exists()
def explore_module(package: str, explore_children: bool) -> list[str]:
"""Explore the modules."""
module = importlib.import_module(package)
found: list[str] = []
if not hasattr(module, "__path__"):
return found
for _, name, _ in pkgutil.iter_modules(module.__path__, f"{package}."):
found.append(name)
if explore_children:
found.extend(explore_module(name, False))
return found
def core_requirements() -> list[str]:
"""Gather core requirements out of pyproject.toml."""
data = tomllib.loads(Path("pyproject.toml").read_text())
dependencies: list[str] = data["project"]["dependencies"]
return dependencies
def gather_recursive_requirements(
domain: str, seen: set[str] | None = None
) -> set[str]:
"""Recursively gather requirements from a module."""
if seen is None:
seen = set()
seen.add(domain)
integration = Integration(
Path(f"homeassistant/components/{domain}"), _get_hassfest_config()
)
integration.load_manifest()
reqs = {x for x in integration.requirements if x not in CONSTRAINT_BASE}
for dep_domain in integration.dependencies:
reqs.update(gather_recursive_requirements(dep_domain, seen))
return reqs
def _normalize_package_name(package_name: str) -> str:
"""Normalize a package name."""
# pipdeptree needs lowercase and dash instead of underscore or period as separator
return package_name.lower().replace("_", "-").replace(".", "-")
def normalize_package_name(requirement: str) -> str:
"""Return a normalized package name from a requirement string."""
# This function is also used in hassfest.
match = PACKAGE_REGEX.search(requirement)
if not match:
return ""
# pipdeptree needs lowercase and dash instead of underscore or period as separator
return _normalize_package_name(match.group(1))
def comment_requirement(req: str) -> bool:
"""Comment out requirement. Some don't install on all systems."""
return normalize_package_name(req) in EXCLUDED_REQUIREMENTS_ALL
def process_action_requirement(req: str, action: str) -> str:
"""Process requirement for a specific github action."""
normalized_package_name = normalize_package_name(req)
if normalized_package_name in OVERRIDDEN_REQUIREMENTS_ACTIONS[action]["exclude"]:
return f"# {req}"
if normalized_package_name in OVERRIDDEN_REQUIREMENTS_ACTIONS[action]["include"]:
return req
if normalized_package_name in EXCLUDED_REQUIREMENTS_ALL:
return f"# {req}"
if markers := OVERRIDDEN_REQUIREMENTS_ACTIONS[action]["markers"].get(
normalized_package_name, None
):
return f"{req};{markers}"
return req
def gather_modules() -> dict[str, list[str]] | None:
"""Collect the information."""
reqs: dict[str, list[str]] = {}
errors: list[str] = []
gather_requirements_from_manifests(errors, reqs)
gather_requirements_from_modules(errors, reqs)
for value in reqs.values():
value = sorted(value, key=lambda name: (len(name.split(".")), name))
if errors:
print("******* ERROR")
print("Errors while importing: ", ", ".join(errors))
return None
return reqs
def gather_requirements_from_manifests(
errors: list[str], reqs: dict[str, list[str]]
) -> None:
"""Gather all of the requirements from manifests."""
config = _get_hassfest_config()
integrations = Integration.load_dir(config.core_integrations_path, config)
for domain in sorted(integrations):
integration = integrations[domain]
if integration.disabled:
continue
process_requirements(
errors, integration.requirements, f"homeassistant.components.{domain}", reqs
)
def gather_requirements_from_modules(
errors: list[str], reqs: dict[str, list[str]]
) -> None:
"""Collect the requirements from the modules directly."""
for package in sorted(
explore_module("homeassistant.scripts", True)
+ explore_module("homeassistant.auth", True)
):
try:
module = importlib.import_module(package)
except ImportError as err:
print(f"{package.replace('.', '/')}.py: {err}")
errors.append(package)
continue
if getattr(module, "REQUIREMENTS", None):
process_requirements(errors, module.REQUIREMENTS, package, reqs)
def process_requirements(
errors: list[str],
module_requirements: list[str],
package: str,
reqs: dict[str, list[str]],
) -> None:
"""Process all of the requirements."""
for req in module_requirements:
if "://" in req:
errors.append(f"{package}[Only pypi dependencies are allowed: {req}]")
if req.partition("==")[1] == "" and req not in IGNORE_PIN:
errors.append(f"{package}[Please pin requirement {req}, see {URL_PIN}]")
reqs.setdefault(req, []).append(package)
def generate_requirements_list(reqs: dict[str, list[str]]) -> str:
"""Generate a pip file based on requirements."""
output = []
for pkg, requirements in sorted(reqs.items(), key=itemgetter(0)):
output.extend(f"\n# {req}" for req in sorted(requirements))
if comment_requirement(pkg):
output.append(f"\n# {pkg}\n")
else:
output.append(f"\n{pkg}\n")
return "".join(output)
def generate_action_requirements_list(reqs: dict[str, list[str]], action: str) -> str:
"""Generate a pip file based on requirements."""
output = []
for pkg, requirements in sorted(reqs.items(), key=itemgetter(0)):
output.extend(f"\n# {req}" for req in sorted(requirements))
processed_pkg = process_action_requirement(pkg, action)
output.append(f"\n{processed_pkg}\n")
return "".join(output)
def requirements_output() -> str:
"""Generate output for requirements."""
output = [
GENERATED_MESSAGE,
"-c homeassistant/package_constraints.txt\n",
"\n",
"# Home Assistant Core\n",
]
output.append("\n".join(core_requirements()))
output.append("\n")
return "".join(output)
def requirements_all_output(reqs: dict[str, list[str]]) -> str:
"""Generate output for requirements_all."""
output = [
"# Home Assistant Core, full dependency set\n",
GENERATED_MESSAGE,
"-r requirements.txt\n",
]
output.append(generate_requirements_list(reqs))
return "".join(output)
def requirements_all_action_output(reqs: dict[str, list[str]], action: str) -> str:
"""Generate output for requirements_all_{action}."""
output = [
f"# Home Assistant Core, full dependency set for {action}\n",
GENERATED_MESSAGE,
"-r requirements.txt\n",
]
output.append(generate_action_requirements_list(reqs, action))
return "".join(output)
def requirements_test_all_output(reqs: dict[str, list[str]]) -> str:
"""Generate output for test_requirements."""
output = [
"# Home Assistant tests, full dependency set\n",
GENERATED_MESSAGE,
"-r requirements_test.txt\n",
]
filtered = {
requirement: modules
for requirement, modules in reqs.items()
if any(
# Always install requirements that are not part of integrations
not mdl.startswith("homeassistant.components.")
or
# Install tests for integrations that have tests
has_tests(mdl)
for mdl in modules
)
}
output.append(generate_requirements_list(filtered))
return "".join(output)
def requirements_pre_commit_output() -> str:
"""Generate output for pre-commit dependencies."""
source = ".pre-commit-config.yaml"
pre_commit_conf: dict[str, list[dict[str, Any]]]
pre_commit_conf = load_yaml(source) # type: ignore[assignment]
reqs: list[str] = []
hook: dict[str, Any]
for repo in (x for x in pre_commit_conf["repos"] if x.get("rev")):
rev: str = repo["rev"]
for hook in repo["hooks"]:
if hook["id"] not in IGNORE_PRE_COMMIT_HOOK_ID:
reqs.append(f"{hook['id']}=={rev.lstrip('v')}")
reqs.extend(x for x in hook.get("additional_dependencies", ()))
output = [
f"# Automatically generated "
f"from {source} by {Path(__file__).name}, do not edit",
"",
]
output.extend(sorted(reqs))
return "\n".join(output) + "\n"
def gather_constraints() -> str:
"""Construct output for constraint file."""
return (
GENERATED_MESSAGE
+ "\n".join(
[
*sorted(
{
*core_requirements(),
*gather_recursive_requirements("default_config"),
*gather_recursive_requirements("mqtt"),
},
key=str.lower,
),
"",
]
)
+ CONSTRAINT_BASE
)
def diff_file(filename: str, content: str) -> list[str]:
"""Diff a file."""
return list(
difflib.context_diff(
[f"{line}\n" for line in Path(filename).read_text().split("\n")],
[f"{line}\n" for line in content.split("\n")],
filename,
"generated",
)
)
def main(validate: bool, ci: bool) -> int:
"""Run the script."""
if not Path("requirements_all.txt").is_file():
print("Run this from HA root dir")
return 1
data = gather_modules()
if data is None:
return 1
reqs_file = requirements_output()
reqs_all_file = requirements_all_output(data)
reqs_all_action_files = {
action: requirements_all_action_output(data, action)
for action in OVERRIDDEN_REQUIREMENTS_ACTIONS
}
reqs_test_all_file = requirements_test_all_output(data)
# Always calling requirements_pre_commit_output is intentional to ensure
# the code is called by the pre-commit hooks.
reqs_pre_commit_file = requirements_pre_commit_output()
constraints = gather_constraints()
files = [
("requirements.txt", reqs_file),
("requirements_all.txt", reqs_all_file),
("requirements_test_pre_commit.txt", reqs_pre_commit_file),
("requirements_test_all.txt", reqs_test_all_file),
("homeassistant/package_constraints.txt", constraints),
]
if ci:
files.extend(
(f"requirements_all_{action}.txt", reqs_all_file)
for action, reqs_all_file in reqs_all_action_files.items()
)
if validate:
errors = []
for filename, content in files:
diff = diff_file(filename, content)
if diff:
errors.append("".join(diff))
if errors:
print("ERROR - FOUND THE FOLLOWING DIFFERENCES")
print()
print()
print("\n\n".join(errors))
print()
print("Please run python3 -m script.gen_requirements_all")
return 1
return 0
for filename, content in files:
Path(filename).write_text(content)
return 0
def _get_hassfest_config() -> Config:
"""Get hassfest config."""
return Config(
root=Path().absolute(),
specific_integrations=None,
action="validate",
requirements=True,
)
if __name__ == "__main__":
_VAL = sys.argv[-1] == "validate"
_CI = sys.argv[-1] == "ci"
sys.exit(main(_VAL, _CI))

View File

@@ -0,0 +1,14 @@
"""Manifest validator."""
import ast
from functools import lru_cache
from pathlib import Path
@lru_cache
def ast_parse_module(file_path: Path) -> ast.Module:
"""Parse a module.
Cached to avoid parsing the same file for each plugin.
"""
return ast.parse(file_path.read_text())

View File

@@ -0,0 +1,256 @@
"""Validate manifests."""
from __future__ import annotations
import argparse
from operator import attrgetter
from pathlib import Path
import sys
from time import monotonic
from . import (
application_credentials,
bluetooth,
codeowners,
config_flow,
config_schema,
dependencies,
dhcp,
docker,
icons,
json,
manifest,
metadata,
mqtt,
mypy_config,
quality_scale,
requirements,
services,
ssdp,
translations,
usb,
zeroconf,
)
from .model import Config, Integration
INTEGRATION_PLUGINS = [
application_credentials,
bluetooth,
codeowners,
config_schema,
dependencies,
dhcp,
icons,
json,
manifest,
mqtt,
quality_scale,
requirements,
services,
ssdp,
translations,
usb,
zeroconf,
config_flow, # This needs to run last, after translations are processed
]
HASS_PLUGINS = [
docker,
mypy_config,
metadata,
]
ALL_PLUGIN_NAMES = [
plugin.__name__.rsplit(".", maxsplit=1)[-1]
for plugin in (*INTEGRATION_PLUGINS, *HASS_PLUGINS)
]
def valid_integration_path(integration_path: Path | str) -> Path:
"""Test if it's a valid integration."""
path = Path(integration_path)
if not path.is_dir():
raise argparse.ArgumentTypeError(f"{integration_path} is not a directory.")
return path
def validate_plugins(plugin_names: str) -> list[str]:
"""Split and validate plugin names."""
all_plugin_names = set(ALL_PLUGIN_NAMES)
plugins = plugin_names.split(",")
for plugin in plugins:
if plugin not in all_plugin_names:
raise argparse.ArgumentTypeError(f"{plugin} is not a valid plugin name")
return plugins
def get_config() -> Config:
"""Return config."""
parser = argparse.ArgumentParser(description="Hassfest")
parser.add_argument(
"--action", type=str, choices=["validate", "generate"], default=None
)
parser.add_argument(
"--integration-path",
action="append",
type=valid_integration_path,
help="Validate a single integration",
)
parser.add_argument(
"--requirements",
action="store_true",
help="Validate requirements",
)
parser.add_argument(
"-p",
"--plugins",
type=validate_plugins,
default=ALL_PLUGIN_NAMES,
help="Comma-separate list of plugins to run. Valid plugin names: %(default)s",
)
parser.add_argument(
"--core-path",
type=Path,
default=Path(),
help="Path to core",
)
parsed = parser.parse_args()
if parsed.action is None:
parsed.action = "validate" if parsed.integration_path else "generate"
if parsed.action == "generate" and parsed.integration_path:
raise RuntimeError(
"Generate is not allowed when limiting to specific integrations"
)
if (
not parsed.integration_path
and not (parsed.core_path / "requirements_all.txt").is_file()
):
raise RuntimeError("Run from Home Assistant root")
return Config(
root=parsed.core_path.absolute(),
specific_integrations=parsed.integration_path,
action=parsed.action,
requirements=parsed.requirements,
plugins=set(parsed.plugins),
)
def main() -> int:
"""Validate manifests."""
try:
config = get_config()
except RuntimeError as err:
print(err)
return 1
plugins = [*INTEGRATION_PLUGINS]
if config.specific_integrations:
integrations = {}
for int_path in config.specific_integrations:
integration = Integration(int_path, config)
integration.load_manifest()
integrations[integration.domain] = integration
else:
integrations = Integration.load_dir(config.core_integrations_path, config)
plugins += HASS_PLUGINS
for plugin in plugins:
plugin_name = plugin.__name__.rsplit(".", maxsplit=1)[-1]
if plugin_name not in config.plugins:
continue
try:
start = monotonic()
print(f"Validating {plugin_name}...", end="", flush=True)
if (
plugin is requirements
and config.requirements
and not config.specific_integrations
):
print()
plugin.validate(integrations, config)
print(f" done in {monotonic() - start:.2f}s")
except RuntimeError as err:
print()
print()
print("Error!")
print(err)
return 1
# When we generate, all errors that are fixable will be ignored,
# as generating them will be fixed.
if config.action == "generate":
general_errors = [err for err in config.errors if not err.fixable]
invalid_itg = [
itg
for itg in integrations.values()
if any(not error.fixable for error in itg.errors)
]
else:
# action == validate
general_errors = config.errors
invalid_itg = [itg for itg in integrations.values() if itg.errors]
warnings_itg = [itg for itg in integrations.values() if itg.warnings]
print()
print("Integrations:", len(integrations))
print("Invalid integrations:", len(invalid_itg))
print()
if not invalid_itg and not general_errors:
print_integrations_status(config, warnings_itg, show_fixable_errors=False)
if config.action == "generate":
for plugin in plugins:
plugin_name = plugin.__name__.rsplit(".", maxsplit=1)[-1]
if plugin_name not in config.plugins:
continue
if hasattr(plugin, "generate"):
plugin.generate(integrations, config)
return 0
if config.action == "generate":
print("Found errors. Generating files canceled.")
print()
if general_errors:
print("General errors:")
for error in general_errors:
print("*", error)
print()
invalid_itg.extend(itg for itg in warnings_itg if itg not in invalid_itg)
print_integrations_status(config, invalid_itg, show_fixable_errors=False)
return 1
def print_integrations_status(
config: Config,
integrations: list[Integration],
*,
show_fixable_errors: bool = True,
) -> None:
"""Print integration status."""
for integration in sorted(integrations, key=attrgetter("domain")):
extra = f" - {integration.path}" if config.specific_integrations else ""
print(f"Integration {integration.domain}{extra}:")
for error in integration.errors:
if show_fixable_errors or not error.fixable:
print("*", "[ERROR]", error)
for warning in integration.warnings:
print("*", "[WARNING]", warning)
print()
if __name__ == "__main__":
sys.exit(main())

View File

@@ -0,0 +1,52 @@
"""Generate application_credentials data."""
from __future__ import annotations
from .model import Config, Integration
from .serializer import format_python_namespace
def generate_and_validate(integrations: dict[str, Integration], config: Config) -> str:
"""Validate and generate application_credentials data."""
match_list = []
for domain in sorted(integrations):
integration = integrations[domain]
application_credentials_file = integration.path / "application_credentials.py"
if not application_credentials_file.is_file():
continue
match_list.append(domain)
return format_python_namespace({"APPLICATION_CREDENTIALS": match_list})
def validate(integrations: dict[str, Integration], config: Config) -> None:
"""Validate application_credentials data."""
application_credentials_path = (
config.root / "homeassistant/generated/application_credentials.py"
)
config.cache["application_credentials"] = content = generate_and_validate(
integrations, config
)
if config.specific_integrations:
return
if application_credentials_path.read_text(encoding="utf-8") != content:
config.add_error(
"application_credentials",
"File application_credentials.py is not up to date. Run python3 -m script.hassfest",
fixable=True,
)
def generate(integrations: dict[str, Integration], config: Config) -> None:
"""Generate application_credentials data."""
application_credentials_path = (
config.root / "homeassistant/generated/application_credentials.py"
)
application_credentials_path.write_text(
f"{config.cache['application_credentials']}", encoding="utf-8"
)

View File

@@ -0,0 +1,48 @@
"""Generate bluetooth file."""
from __future__ import annotations
from .model import Config, Integration
from .serializer import format_python_namespace
def generate_and_validate(integrations: dict[str, Integration]) -> str:
"""Validate and generate bluetooth data."""
match_list = []
for domain in sorted(integrations):
match_types = integrations[domain].manifest.get("bluetooth", [])
if not match_types:
continue
match_list.extend({"domain": domain, **entry} for entry in match_types)
return format_python_namespace(
{"BLUETOOTH": match_list},
annotations={
"BLUETOOTH": "Final[list[dict[str, bool | str | int | list[int]]]]"
},
)
def validate(integrations: dict[str, Integration], config: Config) -> None:
"""Validate bluetooth file."""
bluetooth_path = config.root / "homeassistant/generated/bluetooth.py"
config.cache["bluetooth"] = content = generate_and_validate(integrations)
if config.specific_integrations:
return
if bluetooth_path.read_text() != content:
config.add_error(
"bluetooth",
"File bluetooth.py is not up to date. Run python3 -m script.hassfest",
fixable=True,
)
def generate(integrations: dict[str, Integration], config: Config) -> None:
"""Generate bluetooth file."""
bluetooth_path = config.root / "homeassistant/generated/bluetooth.py"
bluetooth_path.write_text(f"{config.cache['bluetooth']}")

View File

@@ -0,0 +1,77 @@
"""Brand validation."""
from __future__ import annotations
import voluptuous as vol
from voluptuous.humanize import humanize_error
from .model import Brand, Config, Integration
BRAND_SCHEMA = vol.Schema(
{
vol.Required("domain"): str,
vol.Required("name"): str,
vol.Optional("integrations"): [str],
vol.Optional("iot_standards"): [
vol.Any("homekit", "matter", "zigbee", "zwave")
],
}
)
BRAND_EXCEPTIONS = ["u_tec"]
def _validate_brand(
brand: Brand, integrations: dict[str, Integration], config: Config
) -> None:
"""Validate brand file."""
try:
BRAND_SCHEMA(brand.brand)
except vol.Invalid as err:
config.add_error(
"brand",
f"Invalid brand file {brand.path.name}: {humanize_error(brand.brand, err)}",
)
return
if brand.domain != brand.path.stem:
config.add_error(
"brand",
f"Domain '{brand.domain}' does not match file name {brand.path.name}",
)
if (
len(brand.integrations) < 2
and not brand.iot_standards
and brand.domain not in BRAND_EXCEPTIONS
):
config.add_error(
"brand",
f"{brand.path.name}: At least two integrations or "
"iot_standards must be non-empty",
)
if brand.integrations:
for sub_integration in brand.integrations:
if sub_integration not in integrations:
config.add_error(
"brand",
f"{brand.path.name}: References unknown integration {sub_integration}",
)
if brand.domain in integrations and (
not brand.integrations or brand.domain not in brand.integrations
):
config.add_error(
"brand",
f"{brand.path.name}: Brand '{brand.domain}' "
f"is an integration but is missing in the brand's 'integrations' list'",
)
def validate(
brands: dict[str, Brand], integrations: dict[str, Integration], config: Config
) -> None:
"""Handle all integrations' brands."""
for brand in brands.values():
_validate_brand(brand, integrations, config)

View File

@@ -0,0 +1,112 @@
"""Generate CODEOWNERS."""
from __future__ import annotations
from .model import Config, Integration
BASE = """
# This file is generated by script/hassfest/codeowners.py
# People marked here will be automatically requested for a review
# when the code that they own is touched.
# https://github.com/blog/2392-introducing-code-owners
# https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners
# Home Assistant Core
.core_files.yaml @home-assistant/core
.git-blame-ignore-revs @home-assistant/core
.gitattributes @home-assistant/core
.gitignore @home-assistant/core
.hadolint.yaml @home-assistant/core
.pre-commit-config.yaml @home-assistant/core
.prettierignore @home-assistant/core
.yamllint @home-assistant/core
pyproject.toml @home-assistant/core
requirements_test.txt @home-assistant/core
/.devcontainer/ @home-assistant/core
/.github/ @home-assistant/core
/.vscode/ @home-assistant/core
/homeassistant/*.py @home-assistant/core
/homeassistant/auth/ @home-assistant/core
/homeassistant/backports/ @home-assistant/core
/homeassistant/helpers/ @home-assistant/core
/homeassistant/scripts/ @home-assistant/core
/homeassistant/util/ @home-assistant/core
/pylint/ @home-assistant/core
/script/ @home-assistant/core
# Home Assistant Supervisor
.dockerignore @home-assistant/supervisor
build.json @home-assistant/supervisor
/machine/ @home-assistant/supervisor
/rootfs/ @home-assistant/supervisor
/Dockerfile @home-assistant/supervisor
# Other code
/homeassistant/scripts/check_config.py @kellerza
# Integrations
""".strip()
INDIVIDUAL_FILES = """
# Individual files
/homeassistant/components/demo/weather.py @fabaff
"""
REMOVE_CODEOWNERS = """
# Remove codeowners from files
/homeassistant/components/*/translations/
"""
def generate_and_validate(integrations: dict[str, Integration], config: Config) -> str:
"""Generate CODEOWNERS."""
parts = [BASE]
for domain in sorted(integrations):
integration = integrations[domain]
if integration.integration_type == "virtual":
continue
codeowners = integration.manifest["codeowners"]
if not codeowners:
continue
for owner in codeowners:
if not owner.startswith("@"):
integration.add_error(
"codeowners", "Code owners need to be valid GitHub handles."
)
parts.append(f"/homeassistant/components/{domain}/ {' '.join(codeowners)}")
if (config.root / "tests/components" / domain / "__init__.py").exists():
parts.append(f"/tests/components/{domain}/ {' '.join(codeowners)}")
parts.append(f"\n{INDIVIDUAL_FILES.strip()}")
parts.append(f"\n{REMOVE_CODEOWNERS.strip()}")
return "\n".join(parts)
def validate(integrations: dict[str, Integration], config: Config) -> None:
"""Validate CODEOWNERS."""
codeowners_path = config.root / "CODEOWNERS"
config.cache["codeowners"] = content = generate_and_validate(integrations, config)
if config.specific_integrations:
return
if codeowners_path.read_text() != content + "\n":
config.add_error(
"codeowners",
"File CODEOWNERS is not up to date. Run python3 -m script.hassfest",
fixable=True,
)
def generate(integrations: dict[str, Integration], config: Config) -> None:
"""Generate CODEOWNERS."""
codeowners_path = config.root / "CODEOWNERS"
codeowners_path.write_text(f"{config.cache['codeowners']}\n")

View File

@@ -0,0 +1,245 @@
"""Generate config flow file."""
from __future__ import annotations
import json
from typing import Any
from .brand import validate as validate_brands
from .model import Brand, Config, Integration
from .serializer import format_python_namespace
UNIQUE_ID_IGNORE = {"huawei_lte", "mqtt", "adguard"}
def _validate_integration(config: Config, integration: Integration) -> None:
"""Validate config flow of an integration."""
config_flow_file = integration.path / "config_flow.py"
if not config_flow_file.is_file():
if integration.manifest.get("config_flow"):
integration.add_error(
"config_flow",
"Config flows need to be defined in the file config_flow.py",
)
return
config_flow = config_flow_file.read_text()
needs_unique_id = integration.domain not in UNIQUE_ID_IGNORE and (
"async_step_discovery" in config_flow
or "async_step_bluetooth" in config_flow
or "async_step_hassio" in config_flow
or "async_step_homekit" in config_flow
or "async_step_mqtt" in config_flow
or "async_step_ssdp" in config_flow
or "async_step_zeroconf" in config_flow
or "async_step_dhcp" in config_flow
or "async_step_usb" in config_flow
)
if not needs_unique_id:
return
has_unique_id = (
"self.async_set_unique_id" in config_flow
or "self._async_handle_discovery_without_unique_id" in config_flow
or "register_discovery_flow" in config_flow
or "AbstractOAuth2FlowHandler" in config_flow
)
if has_unique_id:
return
if config.specific_integrations:
notice_method = integration.add_warning
else:
notice_method = integration.add_error
notice_method(
"config_flow", "Config flows that are discoverable need to set a unique ID"
)
def _generate_and_validate(integrations: dict[str, Integration], config: Config) -> str:
"""Validate and generate config flow data."""
domains: dict[str, list[str]] = {
"integration": [],
"helper": [],
}
for domain in sorted(integrations):
integration = integrations[domain]
if not integration.config_flow:
continue
_validate_integration(config, integration)
if integration.integration_type == "helper":
domains["helper"].append(domain)
else:
domains["integration"].append(domain)
return format_python_namespace({"FLOWS": domains})
def _populate_brand_integrations(
integration_data: dict[str, Any],
integrations: dict[str, Integration],
brand_metadata: dict[str, Any],
sub_integrations: list[str],
) -> None:
"""Add referenced integrations to a brand's metadata."""
brand_metadata.setdefault("integrations", {})
for domain in sub_integrations:
integration = integrations.get(domain)
if not integration or integration.integration_type in (
"entity",
"hardware",
"system",
):
continue
metadata: dict[str, Any] = {
"integration_type": integration.integration_type,
}
# Always set the config_flow key to avoid breaking the frontend
# https://github.com/home-assistant/frontend/issues/14376
metadata["config_flow"] = bool(integration.config_flow)
if integration.iot_class:
metadata["iot_class"] = integration.iot_class
if integration.supported_by:
metadata["supported_by"] = integration.supported_by
if integration.iot_standards:
metadata["iot_standards"] = integration.iot_standards
if integration.translated_name:
integration_data["translated_name"].add(domain)
else:
metadata["name"] = integration.name
brand_metadata["integrations"][domain] = metadata
def _generate_integrations(
brands: dict[str, Brand],
integrations: dict[str, Integration],
config: Config,
) -> str:
"""Generate integrations data."""
result: dict[str, Any] = {
"integration": {},
"helper": {},
"translated_name": set(),
}
# Not all integrations will have an item in the brands collection.
# The config flow data index will be the union of the integrations without a brands item
# and the brand domain names from the brands collection.
# Compile a set of integrations which are referenced from at least one brand's
# integrations list. These integrations will not be present in the root level of the
# generated config flow index.
brand_integration_domains = {
brand_integration_domain
for brand in brands.values()
for brand_integration_domain in brand.integrations or []
}
# Compile a set of integrations which are not referenced from any brand's
# integrations list.
primary_domains = {
domain
for domain, integration in integrations.items()
if domain not in brand_integration_domains
}
# Add all brands to the set
primary_domains |= set(brands)
# Generate the config flow index
for domain in sorted(primary_domains):
metadata: dict[str, Any] = {}
if brand := brands.get(domain):
metadata["name"] = brand.name
if brand.integrations:
# Add the integrations which are referenced from the brand's
# integrations list
_populate_brand_integrations(
result, integrations, metadata, brand.integrations
)
if brand.iot_standards:
metadata["iot_standards"] = brand.iot_standards
result["integration"][domain] = metadata
else: # integration
integration = integrations[domain]
if integration.integration_type in ("entity", "system", "hardware"):
continue
if integration.translated_name:
result["translated_name"].add(domain)
else:
metadata["name"] = integration.name
metadata["integration_type"] = integration.integration_type
if integration.integration_type == "virtual":
if integration.supported_by:
metadata["supported_by"] = integration.supported_by
if integration.iot_standards:
metadata["iot_standards"] = integration.iot_standards
else:
metadata["config_flow"] = integration.config_flow
if integration.iot_class:
metadata["iot_class"] = integration.iot_class
if single_config_entry := integration.manifest.get(
"single_config_entry"
):
metadata["single_config_entry"] = single_config_entry
if integration.integration_type == "helper":
result["helper"][domain] = metadata
else:
result["integration"][domain] = metadata
return json.dumps(
result | {"translated_name": sorted(result["translated_name"])}, indent=2
)
def validate(integrations: dict[str, Integration], config: Config) -> None:
"""Validate config flow file."""
config_flow_path = config.root / "homeassistant/generated/config_flows.py"
integrations_path = config.root / "homeassistant/generated/integrations.json"
config.cache["config_flow"] = content = _generate_and_validate(integrations, config)
if config.specific_integrations:
return
brands = Brand.load_dir(config.root / "homeassistant/brands", config)
validate_brands(brands, integrations, config)
if config_flow_path.read_text() != content:
config.add_error(
"config_flow",
"File config_flows.py is not up to date. Run python3 -m script.hassfest",
fixable=True,
)
config.cache["integrations"] = content = _generate_integrations(
brands, integrations, config
)
if integrations_path.read_text() != content + "\n":
config.add_error(
"config_flow",
"File integrations.json is not up to date. "
"Run python3 -m script.hassfest",
fixable=True,
)
def generate(integrations: dict[str, Integration], config: Config) -> None:
"""Generate config flow file."""
config_flow_path = config.root / "homeassistant/generated/config_flows.py"
integrations_path = config.root / "homeassistant/generated/integrations.json"
config_flow_path.write_text(f"{config.cache['config_flow']}")
integrations_path.write_text(f"{config.cache['integrations']}\n")

View File

@@ -0,0 +1,109 @@
"""Validate integrations which can be setup from YAML have config schemas."""
from __future__ import annotations
import ast
from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN
from . import ast_parse_module
from .model import Config, Integration
CONFIG_SCHEMA_IGNORE = {
# Configuration under the homeassistant key is a special case, it's handled by
# core_config.async_process_ha_core_config already during bootstrapping, not by
# a schema in the homeassistant integration.
HOMEASSISTANT_DOMAIN,
}
def _has_assignment(module: ast.Module, name: str) -> bool:
"""Test if the module assigns to a name."""
for item in module.body:
if type(item) not in (ast.Assign, ast.AnnAssign, ast.AugAssign):
continue
if type(item) is ast.Assign:
for target in item.targets:
if getattr(target, "id", None) == name:
return True
continue
if item.target.id == name:
return True
return False
def _has_function(
module: ast.Module, _type: ast.AsyncFunctionDef | ast.FunctionDef, name: str
) -> bool:
"""Test if the module defines a function."""
return any(type(item) is _type and item.name == name for item in module.body)
def _has_import(module: ast.Module, name: str) -> bool:
"""Test if the module imports to a name."""
for item in module.body:
if type(item) not in (ast.Import, ast.ImportFrom):
continue
for alias in item.names:
if alias.asname == name or (alias.asname is None and alias.name == name):
return True
return False
def _validate_integration(config: Config, integration: Integration) -> None:
"""Validate integration has has a configuration schema."""
if integration.domain in CONFIG_SCHEMA_IGNORE:
return
init_file = integration.path / "__init__.py"
if not init_file.is_file():
# Virtual integrations don't have any implementation
return
init = ast_parse_module(init_file)
# No YAML Support
if not _has_function(
init, ast.AsyncFunctionDef, "async_setup"
) and not _has_function(init, ast.FunctionDef, "setup"):
return
# No schema
if (
_has_assignment(init, "CONFIG_SCHEMA")
or _has_assignment(init, "PLATFORM_SCHEMA")
or _has_assignment(init, "PLATFORM_SCHEMA_BASE")
or _has_import(init, "CONFIG_SCHEMA")
or _has_import(init, "PLATFORM_SCHEMA")
or _has_import(init, "PLATFORM_SCHEMA_BASE")
):
return
config_file = integration.path / "config.py"
if config_file.is_file():
config_module = ast_parse_module(config_file)
if _has_function(config_module, ast.AsyncFunctionDef, "async_validate_config"):
return
if config.specific_integrations:
notice_method = integration.add_warning
else:
notice_method = integration.add_error
notice_method(
"config_schema",
"Integrations which implement 'async_setup' or 'setup' must define either "
"'CONFIG_SCHEMA', 'PLATFORM_SCHEMA' or 'PLATFORM_SCHEMA_BASE'. If the "
"integration has no configuration parameters, can only be set up from platforms"
" or can only be set up from config entries, one of the helpers "
"cv.empty_config_schema, cv.platform_only_config_schema or "
"cv.config_entry_only_config_schema can be used.",
)
def validate(integrations: dict[str, Integration], config: Config) -> None:
"""Validate integrations have configuration schemas."""
for domain in sorted(integrations):
integration = integrations[domain]
_validate_integration(config, integration)

View File

@@ -0,0 +1,377 @@
"""Validate dependencies."""
from __future__ import annotations
import ast
from collections import deque
import multiprocessing
from pathlib import Path
from homeassistant.const import Platform
from homeassistant.requirements import DISCOVERY_INTEGRATIONS
from . import ast_parse_module
from .model import Config, Integration
class ImportCollector(ast.NodeVisitor):
"""Collect all integrations referenced."""
def __init__(self, integration: Integration) -> None:
"""Initialize the import collector."""
self.integration = integration
self.referenced: dict[Path, set[str]] = {}
# Current file or dir we're inspecting
self._cur_fil_dir: Path | None = None
def collect(self) -> None:
"""Collect imports from a source file."""
for fil in self.integration.path.glob("**/*.py"):
if not fil.is_file():
continue
self._cur_fil_dir = fil.relative_to(self.integration.path)
self.referenced[self._cur_fil_dir] = set()
try:
self.visit(ast_parse_module(fil))
except SyntaxError as e:
e.add_note(f"File: {fil}")
raise
self._cur_fil_dir = None
def _add_reference(self, reference_domain: str) -> None:
"""Add a reference."""
assert self._cur_fil_dir
self.referenced[self._cur_fil_dir].add(reference_domain)
def visit_If(self, node: ast.If) -> None:
"""Visit If node."""
if isinstance(node.test, ast.Name) and node.test.id == "TYPE_CHECKING":
# Ignore TYPE_CHECKING block
return
# Have it visit other kids
self.generic_visit(node)
def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
"""Visit ImportFrom node."""
if node.module is None:
return
# Exception: we will allow importing the sign path code.
if (
node.module == "homeassistant.components.http.auth"
and len(node.names) == 1
and node.names[0].name == "async_sign_path"
):
return
if node.module.startswith("homeassistant.components."):
# from homeassistant.components.alexa.smart_home import EVENT_ALEXA_SMART_HOME
# from homeassistant.components.logbook import bla
self._add_reference(node.module.split(".")[2])
elif node.module == "homeassistant.components":
# from homeassistant.components import sun
for name_node in node.names:
self._add_reference(name_node.name)
def visit_Import(self, node: ast.Import) -> None:
"""Visit Import node."""
# import homeassistant.components.hue as hue
for name_node in node.names:
if name_node.name.startswith("homeassistant.components."):
self._add_reference(name_node.name.split(".")[2])
def visit_Attribute(self, node: ast.Attribute) -> None:
"""Visit Attribute node."""
# hass.components.hue.async_create()
# Name(id=hass)
# .Attribute(attr=hue)
# .Attribute(attr=async_create)
# self.hass.components.hue.async_create()
# Name(id=self)
# .Attribute(attr=hass) or .Attribute(attr=_hass)
# .Attribute(attr=hue)
# .Attribute(attr=async_create)
if (
isinstance(node.value, ast.Attribute)
and node.value.attr == "components"
and (
(
isinstance(node.value.value, ast.Name)
and node.value.value.id == "hass"
)
or (
isinstance(node.value.value, ast.Attribute)
and node.value.value.attr in ("hass", "_hass")
)
)
):
self._add_reference(node.attr)
else:
# Have it visit other kids
self.generic_visit(node)
ALLOWED_USED_COMPONENTS = {
*{platform.value for platform in Platform},
# Internal integrations
"alert",
"automation",
"conversation",
"default_config",
"device_automation",
"frontend",
"group",
"homeassistant",
"input_boolean",
"input_button",
"input_datetime",
"input_number",
"input_select",
"input_text",
"media_source",
"onboarding",
"panel_custom",
"persistent_notification",
"person",
"script",
"shopping_list",
"sun",
"system_health",
"system_log",
"timer",
"webhook",
"websocket_api",
"zone",
# Other
"mjpeg", # base class, has no reqs or component to load.
"stream", # Stream cannot install on all systems, can be imported without reqs.
}
IGNORE_VIOLATIONS = {
# Has same requirement, gets defaults.
("sql", "recorder"),
# Sharing a base class
("lutron_caseta", "lutron"),
("ffmpeg_noise", "ffmpeg_motion"),
# Demo
("demo", "manual"),
# This would be a circular dep
("http", "network"),
("http", "cloud"),
# This would be a circular dep
("zha", "homeassistant_hardware"),
("zha", "homeassistant_sky_connect"),
("zha", "homeassistant_yellow"),
("homeassistant_sky_connect", "zha"),
# This should become a helper method that integrations can submit data to
("websocket_api", "lovelace"),
("websocket_api", "shopping_list"),
"logbook",
# Temporary needed for migration until 2024.10
("conversation", "assist_pipeline"),
}
def calc_allowed_references(integration: Integration) -> set[str]:
"""Return a set of allowed references."""
manifest = integration.manifest
allowed_references = (
ALLOWED_USED_COMPONENTS
| set(manifest.get("dependencies", []))
| set(manifest.get("after_dependencies", []))
)
# bluetooth_adapters is a wrapper to ensure
# that all the integrations that provide bluetooth
# adapters are setup before loading integrations
# that use them.
if "bluetooth_adapters" in allowed_references:
allowed_references.add("bluetooth")
# Discovery requirements are ok if referenced in manifest
for check_domain, to_check in DISCOVERY_INTEGRATIONS.items():
if any(check in manifest for check in to_check):
allowed_references.add(check_domain)
return allowed_references
def find_non_referenced_integrations(
integrations: dict[str, Integration],
integration: Integration,
references: dict[Path, set[str]],
) -> set[str]:
"""Find integrations that are not allowed to be referenced."""
allowed_references = calc_allowed_references(integration)
referenced = set()
for path, refs in references.items():
if len(path.parts) == 1:
# climate.py is stored as climate
cur_fil_dir = path.stem
else:
# climate/__init__.py is stored as climate
cur_fil_dir = path.parts[0]
is_platform_other_integration = cur_fil_dir in integrations
for ref in refs:
# We are always allowed to import from ourselves
if ref == integration.domain:
continue
# These references are approved based on the manifest
if ref in allowed_references:
continue
# Some violations are whitelisted
if (integration.domain, ref) in IGNORE_VIOLATIONS:
continue
# If it's a platform for another integration, the other integration is ok
if is_platform_other_integration and cur_fil_dir == ref:
continue
# These have a platform specified in this integration
if not is_platform_other_integration and (
(integration.path / f"{ref}.py").is_file()
# Platform dir
or (integration.path / ref).is_dir()
):
continue
referenced.add(ref)
return referenced
def _compute_integration_dependencies(
integration: Integration,
) -> tuple[str, dict[Path, set[str]] | None]:
"""Compute integration dependencies."""
# Some integrations are allowed to have violations.
if integration.domain in IGNORE_VIOLATIONS:
return (integration.domain, None)
# Find usage of hass.components
collector = ImportCollector(integration)
collector.collect()
return (integration.domain, collector.referenced)
def _validate_dependency_imports(
integrations: dict[str, Integration],
) -> None:
"""Validate all dependencies."""
# Find integration dependencies with multiprocessing
# (because it takes some time to parse thousands of files)
with multiprocessing.Pool() as pool:
integration_imports = dict(
pool.imap_unordered(
_compute_integration_dependencies,
integrations.values(),
chunksize=10,
)
)
for integration in integrations.values():
referenced = integration_imports[integration.domain]
if not referenced: # Either ignored or has no references
continue
for domain in sorted(
find_non_referenced_integrations(integrations, integration, referenced)
):
integration.add_error(
"dependencies",
f"Using component {domain} but it's not in 'dependencies' "
"or 'after_dependencies'",
)
def _check_circular_deps(
integrations: dict[str, Integration],
start_domain: str,
integration: Integration,
checked: set[str],
checking: deque[str],
) -> None:
"""Check for circular dependencies pointing at starting_domain."""
if integration.domain in checked or integration.domain in checking:
return
checking.append(integration.domain)
for domain in integration.manifest.get("dependencies", []):
if domain == start_domain:
integrations[start_domain].add_error(
"dependencies",
f"Found a circular dependency with {integration.domain} ({', '.join(checking)})",
)
break
_check_circular_deps(
integrations, start_domain, integrations[domain], checked, checking
)
else:
for domain in integration.manifest.get("after_dependencies", []):
if domain == start_domain:
integrations[start_domain].add_error(
"dependencies",
f"Found a circular dependency with after dependencies of {integration.domain} ({', '.join(checking)})",
)
break
_check_circular_deps(
integrations, start_domain, integrations[domain], checked, checking
)
checked.add(integration.domain)
checking.remove(integration.domain)
def _validate_circular_dependencies(integrations: dict[str, Integration]) -> None:
for integration in integrations.values():
if integration.domain in IGNORE_VIOLATIONS:
continue
_check_circular_deps(
integrations, integration.domain, integration, set(), deque()
)
def _validate_dependencies(
integrations: dict[str, Integration],
) -> None:
"""Check that all referenced dependencies exist and are not duplicated."""
for integration in integrations.values():
if not integration.manifest:
continue
after_deps = integration.manifest.get("after_dependencies", [])
for dep in integration.manifest.get("dependencies", []):
if dep in after_deps:
integration.add_error(
"dependencies",
f"Dependency {dep} is both in dependencies and after_dependencies",
)
if dep not in integrations:
integration.add_error(
"dependencies", f"Dependency {dep} does not exist"
)
def validate(
integrations: dict[str, Integration],
config: Config,
) -> None:
"""Handle dependencies for integrations."""
_validate_dependency_imports(integrations)
if not config.specific_integrations:
_validate_dependencies(integrations)
_validate_circular_dependencies(integrations)

View File

@@ -0,0 +1,46 @@
"""Generate dhcp file."""
from __future__ import annotations
from .model import Config, Integration
from .serializer import format_python_namespace
def generate_and_validate(integrations: dict[str, Integration]) -> str:
"""Validate and generate dhcp data."""
match_list = []
for domain in sorted(integrations):
match_types = integrations[domain].manifest.get("dhcp", [])
if not match_types:
continue
match_list.extend({"domain": domain, **entry} for entry in match_types)
return format_python_namespace(
{"DHCP": match_list},
annotations={"DHCP": "Final[list[dict[str, str | bool]]]"},
)
def validate(integrations: dict[str, Integration], config: Config) -> None:
"""Validate dhcp file."""
dhcp_path = config.root / "homeassistant/generated/dhcp.py"
config.cache["dhcp"] = content = generate_and_validate(integrations)
if config.specific_integrations:
return
if dhcp_path.read_text() != content:
config.add_error(
"dhcp",
"File dhcp.py is not up to date. Run python3 -m script.hassfest",
fixable=True,
)
def generate(integrations: dict[str, Integration], config: Config) -> None:
"""Generate dhcp file."""
dhcp_path = config.root / "homeassistant/generated/dhcp.py"
dhcp_path.write_text(f"{config.cache['dhcp']}")

View File

@@ -0,0 +1,226 @@
"""Generate and validate the dockerfile."""
from dataclasses import dataclass
from pathlib import Path
from homeassistant import core
from homeassistant.components.go2rtc.const import RECOMMENDED_VERSION as GO2RTC_VERSION
from homeassistant.const import Platform
from homeassistant.util import executor, thread
from script.gen_requirements_all import gather_recursive_requirements
from .model import Config, Integration
from .requirements import PACKAGE_REGEX, PIP_VERSION_RANGE_SEPARATOR
DOCKERFILE_TEMPLATE = r"""# Automatically generated by hassfest.
#
# To update, run python3 -m script.hassfest -p docker
ARG BUILD_FROM
FROM ${{BUILD_FROM}}
# Synchronize with homeassistant/core.py:async_stop
ENV \
S6_SERVICES_GRACETIME={timeout} \
UV_SYSTEM_PYTHON=true \
UV_NO_CACHE=true
ARG QEMU_CPU
# Install uv
RUN pip3 install uv=={uv}
WORKDIR /usr/src
## Setup Home Assistant Core dependencies
COPY requirements.txt homeassistant/
COPY homeassistant/package_constraints.txt homeassistant/homeassistant/
RUN \
uv pip install \
--no-build \
-r homeassistant/requirements.txt
COPY requirements_all.txt home_assistant_frontend-* home_assistant_intents-* homeassistant/
RUN \
if ls homeassistant/home_assistant_*.whl 1> /dev/null 2>&1; then \
uv pip install homeassistant/home_assistant_*.whl; \
fi \
&& uv pip install \
--no-build \
-r homeassistant/requirements_all.txt
## Setup Home Assistant Core
COPY . homeassistant/
RUN \
uv pip install \
-e ./homeassistant \
&& python3 -m compileall \
homeassistant/homeassistant
# Home Assistant S6-Overlay
COPY rootfs /
# Needs to be redefined inside the FROM statement to be set for RUN commands
ARG BUILD_ARCH
# Get go2rtc binary
RUN \
case "${{BUILD_ARCH}}" in \
"aarch64") go2rtc_suffix='arm64' ;; \
"armhf") go2rtc_suffix='armv6' ;; \
"armv7") go2rtc_suffix='arm' ;; \
*) go2rtc_suffix=${{BUILD_ARCH}} ;; \
esac \
&& curl -L https://github.com/AlexxIT/go2rtc/releases/download/v{go2rtc}/go2rtc_linux_${{go2rtc_suffix}} --output /bin/go2rtc \
&& chmod +x /bin/go2rtc \
# Verify go2rtc can be executed
&& go2rtc --version
WORKDIR /config
"""
_HASSFEST_TEMPLATE = r"""# Automatically generated by hassfest.
#
# To update, run python3 -m script.hassfest -p docker
FROM python:3.13-alpine
ENV \
UV_SYSTEM_PYTHON=true \
UV_EXTRA_INDEX_URL="https://wheels.home-assistant.io/musllinux-index/"
SHELL ["/bin/sh", "-o", "pipefail", "-c"]
ENTRYPOINT ["/usr/src/homeassistant/script/hassfest/docker/entrypoint.sh"]
WORKDIR "/github/workspace"
COPY . /usr/src/homeassistant
# Uv is only needed during build
RUN --mount=from=ghcr.io/astral-sh/uv:{uv},source=/uv,target=/bin/uv \
# Required for PyTurboJPEG
apk add --no-cache libturbojpeg \
&& uv pip install \
--no-build \
--no-cache \
-c /usr/src/homeassistant/homeassistant/package_constraints.txt \
-r /usr/src/homeassistant/requirements.txt \
stdlib-list==0.10.0 pipdeptree=={pipdeptree} tqdm=={tqdm} ruff=={ruff} \
{required_components_packages}
LABEL "name"="hassfest"
LABEL "maintainer"="Home Assistant <hello@home-assistant.io>"
LABEL "com.github.actions.name"="hassfest"
LABEL "com.github.actions.description"="Run hassfest to validate standalone integration repositories"
LABEL "com.github.actions.icon"="terminal"
LABEL "com.github.actions.color"="gray-dark"
"""
def _get_package_versions(file: Path, packages: set[str]) -> dict[str, str]:
package_versions: dict[str, str] = {}
with file.open(encoding="UTF-8") as fp:
for _, line in enumerate(fp):
if package_versions.keys() == packages:
return package_versions
if match := PACKAGE_REGEX.match(line):
pkg, sep, version = match.groups()
if pkg not in packages:
continue
if sep != "==" or not version:
raise RuntimeError(
f'Requirement {pkg} need to be pinned "{pkg}==<version>".'
)
for part in version.split(";", 1)[0].split(","):
version_part = PIP_VERSION_RANGE_SEPARATOR.match(part)
if version_part:
package_versions[pkg] = version_part.group(2)
break
if package_versions.keys() == packages:
return package_versions
raise RuntimeError("At least one package was not found in the requirements file.")
@dataclass
class File:
"""File."""
content: str
path: Path
def _generate_hassfest_dockerimage(
config: Config, timeout: int, package_versions: dict[str, str]
) -> File:
packages = set()
already_checked_domains = set()
for platform in Platform:
packages.update(
gather_recursive_requirements(platform.value, already_checked_domains)
)
# Add go2rtc requirements as this file needs the go2rtc integration
packages.update(gather_recursive_requirements("go2rtc", already_checked_domains))
return File(
_HASSFEST_TEMPLATE.format(
timeout=timeout,
required_components_packages=" ".join(sorted(packages)),
**package_versions,
),
config.root / "script/hassfest/docker/Dockerfile",
)
def _generate_files(config: Config) -> list[File]:
timeout = (
core.STOPPING_STAGE_SHUTDOWN_TIMEOUT
+ core.STOP_STAGE_SHUTDOWN_TIMEOUT
+ core.FINAL_WRITE_STAGE_SHUTDOWN_TIMEOUT
+ core.CLOSE_STAGE_SHUTDOWN_TIMEOUT
+ executor.EXECUTOR_SHUTDOWN_TIMEOUT
+ thread.THREADING_SHUTDOWN_TIMEOUT
+ 10
) * 1000
package_versions = _get_package_versions(config.root / "requirements.txt", {"uv"})
package_versions |= _get_package_versions(
config.root / "requirements_test.txt", {"pipdeptree", "tqdm"}
)
package_versions |= _get_package_versions(
config.root / "requirements_test_pre_commit.txt", {"ruff"}
)
return [
File(
DOCKERFILE_TEMPLATE.format(
timeout=timeout,
**package_versions,
go2rtc=GO2RTC_VERSION,
),
config.root / "Dockerfile",
),
_generate_hassfest_dockerimage(config, timeout, package_versions),
]
def validate(integrations: dict[str, Integration], config: Config) -> None:
"""Validate dockerfile."""
docker_files = _generate_files(config)
config.cache["docker"] = docker_files
for file in docker_files:
if file.content != file.path.read_text():
config.add_error(
"docker",
f"File {file.path} is not up to date. Run python3 -m script.hassfest",
fixable=True,
)
def generate(integrations: dict[str, Integration], config: Config) -> None:
"""Generate dockerfile."""
for file in _generate_files(config):
file.path.write_text(file.content)

View File

@@ -0,0 +1,34 @@
# Automatically generated by hassfest.
#
# To update, run python3 -m script.hassfest -p docker
FROM python:3.13-alpine
ENV \
UV_SYSTEM_PYTHON=true \
UV_EXTRA_INDEX_URL="https://wheels.home-assistant.io/musllinux-index/"
SHELL ["/bin/sh", "-o", "pipefail", "-c"]
ENTRYPOINT ["/usr/src/homeassistant/script/hassfest/docker/entrypoint.sh"]
WORKDIR "/github/workspace"
COPY . /usr/src/homeassistant
# Uv is only needed during build
RUN --mount=from=ghcr.io/astral-sh/uv:0.5.8,source=/uv,target=/bin/uv \
# Required for PyTurboJPEG
apk add --no-cache libturbojpeg \
&& uv pip install \
--no-build \
--no-cache \
-c /usr/src/homeassistant/homeassistant/package_constraints.txt \
-r /usr/src/homeassistant/requirements.txt \
stdlib-list==0.10.0 pipdeptree==2.23.4 tqdm==4.66.5 ruff==0.8.3 \
PyTurboJPEG==1.7.5 go2rtc-client==0.1.2 ha-ffmpeg==3.2.2 hassil==2.1.0 home-assistant-intents==2025.1.1 mutagen==1.47.0 pymicro-vad==1.0.1 pyspeex-noise==1.0.2
LABEL "name"="hassfest"
LABEL "maintainer"="Home Assistant <hello@home-assistant.io>"
LABEL "com.github.actions.name"="hassfest"
LABEL "com.github.actions.description"="Run hassfest to validate standalone integration repositories"
LABEL "com.github.actions.icon"="terminal"
LABEL "com.github.actions.color"="gray-dark"

View File

@@ -0,0 +1,11 @@
# Ignore everything except the specified files
*
!homeassistant/
!requirements.txt
!script/
script/hassfest/docker/
!script/hassfest/docker/entrypoint.sh
# Temporary files
**/__pycache__

View File

@@ -0,0 +1,30 @@
#!/bin/sh
integrations=""
integration_path=""
core_path_provided=false
for arg in "$@"; do
case "$arg" in
--core-path=*)
core_path_provided=true
break
;;
esac
done
if [ "$core_path_provided" = false ]; then
# Enable recursive globbing using find
for manifest in $(find . -name "manifest.json"); do
manifest_path=$(realpath "${manifest}")
integrations="$integrations --integration-path ${manifest_path%/*}"
done
if [ -z "$integrations" ]; then
echo "Error: No integrations found!"
exit 1
fi
fi
cd /usr/src/homeassistant || exit 1
exec python3 -m script.hassfest --action validate $integrations "$@"

View File

@@ -0,0 +1,196 @@
"""Validate integration icon translation files."""
from __future__ import annotations
from typing import Any
import orjson
import voluptuous as vol
from voluptuous.humanize import humanize_error
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.icon import convert_shorthand_service_icon
from .model import Config, Integration
from .translations import translation_key_validator
def icon_value_validator(value: Any) -> str:
"""Validate that the icon is a valid icon."""
value = cv.string_with_no_html(value)
if not value.startswith("mdi:"):
raise vol.Invalid(
"The icon needs to be a valid icon from Material Design Icons and start with `mdi:`"
)
return str(value)
def require_default_icon_validator(value: dict) -> dict:
"""Validate that a default icon is set."""
if "_" not in value:
raise vol.Invalid(
"An entity component needs to have a default icon defined with `_`"
)
return value
def ensure_not_same_as_default(value: dict) -> dict:
"""Validate an icon isn't the same as its default icon."""
for translation_key, section in value.items():
if (default := section.get("default")) and (states := section.get("state")):
for state, icon in states.items():
if icon == default:
raise vol.Invalid(
f"The icon for state `{translation_key}.{state}` is the"
" same as the default icon and thus can be removed"
)
return value
DATA_ENTRY_ICONS_SCHEMA = vol.Schema(
{
"step": {
str: {
"sections": {
str: icon_value_validator,
}
}
}
}
)
CORE_SERVICE_ICONS_SCHEMA = cv.schema_with_slug_keys(
vol.Schema(
{
vol.Optional("service"): icon_value_validator,
vol.Optional("sections"): cv.schema_with_slug_keys(
icon_value_validator, slug_validator=translation_key_validator
),
}
),
slug_validator=translation_key_validator,
)
CUSTOM_INTEGRATION_SERVICE_ICONS_SCHEMA = cv.schema_with_slug_keys(
vol.All(
convert_shorthand_service_icon,
vol.Schema(
{
vol.Optional("service"): icon_value_validator,
vol.Optional("sections"): cv.schema_with_slug_keys(
icon_value_validator, slug_validator=translation_key_validator
),
}
),
),
slug_validator=translation_key_validator,
)
def icon_schema(
core_integration: bool, integration_type: str, no_entity_platform: bool
) -> vol.Schema:
"""Create an icon schema."""
state_validator = cv.schema_with_slug_keys(
icon_value_validator,
slug_validator=translation_key_validator,
)
def icon_schema_slug(marker: type[vol.Marker]) -> dict[vol.Marker, Any]:
return {
marker("default"): icon_value_validator,
vol.Optional("state"): state_validator,
vol.Optional("state_attributes"): vol.All(
cv.schema_with_slug_keys(
{
marker("default"): icon_value_validator,
marker("state"): state_validator,
},
slug_validator=translation_key_validator,
),
ensure_not_same_as_default,
),
}
schema = vol.Schema(
{
vol.Optional("config"): DATA_ENTRY_ICONS_SCHEMA,
vol.Optional("issues"): vol.Schema(
{str: {"fix_flow": DATA_ENTRY_ICONS_SCHEMA}}
),
vol.Optional("options"): DATA_ENTRY_ICONS_SCHEMA,
vol.Optional("services"): CORE_SERVICE_ICONS_SCHEMA
if core_integration
else CUSTOM_INTEGRATION_SERVICE_ICONS_SCHEMA,
}
)
if integration_type in ("entity", "helper", "system"):
if integration_type != "entity" or no_entity_platform:
field = vol.Optional("entity_component")
else:
field = vol.Required("entity_component")
schema = schema.extend(
{
field: vol.All(
cv.schema_with_slug_keys(
icon_schema_slug(vol.Required),
slug_validator=vol.Any("_", cv.slug),
),
require_default_icon_validator,
ensure_not_same_as_default,
)
}
)
if integration_type not in ("entity", "system"):
schema = schema.extend(
{
vol.Optional("entity"): vol.All(
cv.schema_with_slug_keys(
cv.schema_with_slug_keys(
icon_schema_slug(vol.Optional),
slug_validator=translation_key_validator,
),
slug_validator=cv.slug,
),
ensure_not_same_as_default,
)
}
)
return schema
def validate_icon_file(config: Config, integration: Integration) -> None:
"""Validate icon file for integration."""
icons_file = integration.path / "icons.json"
if not icons_file.is_file():
return
name = str(icons_file.relative_to(integration.path))
try:
icons = orjson.loads(icons_file.read_text())
except ValueError as err:
integration.add_error("icons", f"Invalid JSON in {name}: {err}")
return
no_entity_platform = integration.domain in ("notify", "image_processing")
schema = icon_schema(
integration.core, integration.integration_type, no_entity_platform
)
try:
schema(icons)
except vol.Invalid as err:
integration.add_error("icons", f"Invalid {name}: {humanize_error(icons, err)}")
def validate(integrations: dict[str, Integration], config: Config) -> None:
"""Handle JSON files inside integrations."""
for integration in integrations.values():
validate_icon_file(config, integration)

View File

@@ -0,0 +1,29 @@
"""Validate integration JSON files."""
from __future__ import annotations
import json
from .model import Config, Integration
def validate_json_files(integration: Integration) -> None:
"""Validate JSON files for integration."""
for json_file in integration.path.glob("**/*.json"):
if not json_file.is_file():
continue
try:
json.loads(json_file.read_text())
except json.JSONDecodeError:
relative_path = json_file.relative_to(integration.path)
integration.add_error("json", f"Invalid JSON file {relative_path}")
def validate(integrations: dict[str, Integration], config: Config) -> None:
"""Handle JSON files inside integrations."""
if not config.specific_integrations:
return
for integration in integrations.values():
validate_json_files(integration)

View File

@@ -0,0 +1,416 @@
"""Manifest validation."""
from __future__ import annotations
from enum import StrEnum, auto
import json
from pathlib import Path
import subprocess
from typing import Any
from urllib.parse import urlparse
from awesomeversion import (
AwesomeVersion,
AwesomeVersionException,
AwesomeVersionStrategy,
)
import voluptuous as vol
from voluptuous.humanize import humanize_error
from homeassistant.const import Platform
from homeassistant.helpers import config_validation as cv
from .model import Config, Integration, ScaledQualityScaleTiers
DOCUMENTATION_URL_SCHEMA = "https"
DOCUMENTATION_URL_HOST = "www.home-assistant.io"
DOCUMENTATION_URL_PATH_PREFIX = "/integrations/"
DOCUMENTATION_URL_EXCEPTIONS = {"https://www.home-assistant.io/hassio"}
class NonScaledQualityScaleTiers(StrEnum):
"""Supported manifest quality scales."""
CUSTOM = auto()
NO_SCORE = auto()
INTERNAL = auto()
LEGACY = auto()
SUPPORTED_QUALITY_SCALES = [
value.name.lower()
for enum in [ScaledQualityScaleTiers, NonScaledQualityScaleTiers]
for value in enum
]
SUPPORTED_IOT_CLASSES = [
"assumed_state",
"calculated",
"cloud_polling",
"cloud_push",
"local_polling",
"local_push",
]
# List of integrations that are supposed to have no IoT class
NO_IOT_CLASS = [
*{platform.value for platform in Platform},
"api",
"application_credentials",
"auth",
"automation",
"blueprint",
"color_extractor",
"config",
"configurator",
"counter",
"default_config",
"device_automation",
"device_tracker",
"diagnostics",
"downloader",
"ffmpeg",
"file_upload",
"frontend",
"hardkernel",
"hardware",
"history",
"homeassistant",
"homeassistant_alerts",
"homeassistant_green",
"homeassistant_hardware",
"homeassistant_sky_connect",
"homeassistant_yellow",
"image_upload",
"input_boolean",
"input_button",
"input_datetime",
"input_number",
"input_select",
"input_text",
"intent_script",
"intent",
"logbook",
"logger",
"lovelace",
"media_source",
"my",
"onboarding",
"panel_custom",
"plant",
"profiler",
"proxy",
"python_script",
"raspberry_pi",
"recovery_mode",
"repairs",
"schedule",
"script",
"search",
"system_health",
"system_log",
"tag",
"timer",
"trace",
"webhook",
"websocket_api",
"zone",
]
def documentation_url(value: str) -> str:
"""Validate that a documentation url has the correct path and domain."""
if value in DOCUMENTATION_URL_EXCEPTIONS:
return value
parsed_url = urlparse(value)
if parsed_url.scheme != DOCUMENTATION_URL_SCHEMA:
raise vol.Invalid("Documentation url is not prefixed with https")
if parsed_url.netloc == DOCUMENTATION_URL_HOST and not parsed_url.path.startswith(
DOCUMENTATION_URL_PATH_PREFIX
):
raise vol.Invalid(
"Documentation url does not begin with www.home-assistant.io/integrations"
)
return value
def verify_lowercase(value: str) -> str:
"""Verify a value is lowercase."""
if value.lower() != value:
raise vol.Invalid("Value needs to be lowercase")
return value
def verify_uppercase(value: str) -> str:
"""Verify a value is uppercase."""
if value.upper() != value:
raise vol.Invalid("Value needs to be uppercase")
return value
def verify_version(value: str) -> str:
"""Verify the version."""
try:
AwesomeVersion(
value,
ensure_strategy=[
AwesomeVersionStrategy.CALVER,
AwesomeVersionStrategy.SEMVER,
AwesomeVersionStrategy.SIMPLEVER,
AwesomeVersionStrategy.BUILDVER,
AwesomeVersionStrategy.PEP440,
],
)
except AwesomeVersionException as err:
raise vol.Invalid(f"'{value}' is not a valid version.") from err
return value
def verify_wildcard(value: str) -> str:
"""Verify the matcher contains a wildcard."""
if "*" not in value:
raise vol.Invalid(f"'{value}' needs to contain a wildcard matcher")
return value
INTEGRATION_MANIFEST_SCHEMA = vol.Schema(
{
vol.Required("domain"): str,
vol.Required("name"): str,
vol.Optional("integration_type", default="hub"): vol.In(
[
"device",
"entity",
"hardware",
"helper",
"hub",
"service",
"system",
]
),
vol.Optional("config_flow"): bool,
vol.Optional("mqtt"): [str],
vol.Optional("zeroconf"): [
vol.Any(
str,
vol.All(
cv.deprecated("macaddress"),
cv.deprecated("model"),
cv.deprecated("manufacturer"),
vol.Schema(
{
vol.Required("type"): str,
vol.Optional("macaddress"): vol.All(
str, verify_uppercase, verify_wildcard
),
vol.Optional("manufacturer"): vol.All(
str, verify_lowercase
),
vol.Optional("model"): vol.All(str, verify_lowercase),
vol.Optional("name"): vol.All(str, verify_lowercase),
vol.Optional("properties"): vol.Schema(
{str: verify_lowercase}
),
}
),
),
)
],
vol.Optional("ssdp"): vol.Schema(
vol.All([vol.All(vol.Schema({}, extra=vol.ALLOW_EXTRA), vol.Length(min=1))])
),
vol.Optional("bluetooth"): [
vol.Schema(
{
vol.Optional("connectable"): bool,
vol.Optional("service_uuid"): vol.All(str, verify_lowercase),
vol.Optional("service_data_uuid"): vol.All(str, verify_lowercase),
vol.Optional("local_name"): vol.All(str),
vol.Optional("manufacturer_id"): int,
vol.Optional("manufacturer_data_start"): [int],
}
)
],
vol.Optional("homekit"): vol.Schema({vol.Optional("models"): [str]}),
vol.Optional("dhcp"): [
vol.Schema(
{
vol.Optional("macaddress"): vol.All(
str, verify_uppercase, verify_wildcard
),
vol.Optional("hostname"): vol.All(str, verify_lowercase),
vol.Optional("registered_devices"): cv.boolean,
}
)
],
vol.Optional("usb"): [
vol.Schema(
{
vol.Optional("vid"): vol.All(str, verify_uppercase),
vol.Optional("pid"): vol.All(str, verify_uppercase),
vol.Optional("serial_number"): vol.All(str, verify_lowercase),
vol.Optional("manufacturer"): vol.All(str, verify_lowercase),
vol.Optional("description"): vol.All(str, verify_lowercase),
vol.Optional("known_devices"): [str],
}
)
],
vol.Required("documentation"): vol.All(vol.Url(), documentation_url),
vol.Optional("quality_scale"): vol.In(SUPPORTED_QUALITY_SCALES),
vol.Optional("requirements"): [str],
vol.Optional("dependencies"): [str],
vol.Optional("after_dependencies"): [str],
vol.Required("codeowners"): [str],
vol.Optional("loggers"): [str],
vol.Optional("disabled"): str,
vol.Optional("iot_class"): vol.In(SUPPORTED_IOT_CLASSES),
vol.Optional("single_config_entry"): bool,
}
)
VIRTUAL_INTEGRATION_MANIFEST_SCHEMA = vol.Schema(
{
vol.Required("domain"): str,
vol.Required("name"): str,
vol.Required("integration_type"): "virtual",
vol.Exclusive("iot_standards", "virtual_integration"): [
vol.Any("homekit", "zigbee", "zwave")
],
vol.Exclusive("supported_by", "virtual_integration"): str,
}
)
def manifest_schema(value: dict[str, Any]) -> vol.Schema:
"""Validate integration manifest."""
if value.get("integration_type") == "virtual":
return VIRTUAL_INTEGRATION_MANIFEST_SCHEMA(value)
return INTEGRATION_MANIFEST_SCHEMA(value)
CUSTOM_INTEGRATION_MANIFEST_SCHEMA = INTEGRATION_MANIFEST_SCHEMA.extend(
{
vol.Optional("version"): vol.All(str, verify_version),
vol.Optional("issue_tracker"): vol.Url(),
vol.Optional("import_executor"): bool,
}
)
def validate_version(integration: Integration) -> None:
"""Validate the version of the integration.
Will be removed when the version key is no longer optional for custom integrations.
"""
if not integration.manifest.get("version"):
integration.add_error("manifest", "No 'version' key in the manifest file.")
return
def validate_manifest(integration: Integration, core_components_dir: Path) -> None:
"""Validate manifest."""
try:
if integration.core:
manifest_schema(integration.manifest)
else:
CUSTOM_INTEGRATION_MANIFEST_SCHEMA(integration.manifest)
except vol.Invalid as err:
integration.add_error(
"manifest", f"Invalid manifest: {humanize_error(integration.manifest, err)}"
)
if (domain := integration.manifest["domain"]) != integration.path.name:
integration.add_error("manifest", "Domain does not match dir name")
if not integration.core and (core_components_dir / domain).exists():
integration.add_warning(
"manifest", "Domain collides with built-in core integration"
)
if domain in NO_IOT_CLASS and "iot_class" in integration.manifest:
integration.add_error("manifest", "Domain should not have an IoT Class")
if (
domain not in NO_IOT_CLASS
and "iot_class" not in integration.manifest
and integration.manifest.get("integration_type") != "virtual"
):
integration.add_error("manifest", "Domain is missing an IoT Class")
if (
integration.manifest.get("integration_type") == "virtual"
and (supported_by := integration.manifest.get("supported_by"))
and not (core_components_dir / supported_by).exists()
):
integration.add_error(
"manifest",
"Virtual integration points to non-existing supported_by integration",
)
if (
(quality_scale := integration.manifest.get("quality_scale"))
and quality_scale.upper() in ScaledQualityScaleTiers
and ScaledQualityScaleTiers[quality_scale.upper()]
>= ScaledQualityScaleTiers.SILVER
):
if not integration.manifest.get("codeowners"):
integration.add_error(
"manifest",
f"{quality_scale} integration does not have a code owner",
)
if not integration.core:
validate_version(integration)
_SORT_KEYS = {"domain": ".domain", "name": ".name"}
def _sort_manifest_keys(key: str) -> str:
return _SORT_KEYS.get(key, key)
def sort_manifest(integration: Integration, config: Config) -> bool:
"""Sort manifest."""
keys = list(integration.manifest.keys())
if (keys_sorted := sorted(keys, key=_sort_manifest_keys)) != keys:
manifest = {key: integration.manifest[key] for key in keys_sorted}
if config.action == "generate":
integration.manifest_path.write_text(json.dumps(manifest, indent=2))
text = "have been sorted"
else:
text = "are not sorted correctly"
integration.add_error(
"manifest",
f"Manifest keys {text}: domain, name, then alphabetical order",
)
return True
return False
def validate(integrations: dict[str, Integration], config: Config) -> None:
"""Handle all integrations manifests."""
core_components_dir = config.root / "homeassistant/components"
manifests_resorted = []
for integration in integrations.values():
validate_manifest(integration, core_components_dir)
if not integration.errors:
if sort_manifest(integration, config):
manifests_resorted.append(integration.manifest_path)
if config.action == "generate" and manifests_resorted:
subprocess.run(
[
"pre-commit",
"run",
"--hook-stage",
"manual",
"prettier",
"--files",
*manifests_resorted,
],
stdout=subprocess.DEVNULL,
check=True,
)

View File

@@ -0,0 +1,31 @@
"""Package metadata validation."""
import tomllib
from homeassistant.const import REQUIRED_PYTHON_VER, __version__
from .model import Config, Integration
def validate(integrations: dict[str, Integration], config: Config) -> None:
"""Validate project metadata keys."""
metadata_path = config.root / "pyproject.toml"
data = tomllib.loads(metadata_path.read_text())
try:
if data["project"]["version"] != __version__:
config.add_error(
"metadata", f"'project.version' value does not match '{__version__}'"
)
except KeyError:
config.add_error("metadata", "No 'metadata.version' key found!")
required_py_version = f">={'.'.join(map(str, REQUIRED_PYTHON_VER))}"
try:
if data["project"]["requires-python"] != required_py_version:
config.add_error(
"metadata",
f"'project.requires-python' value doesn't match '{required_py_version}'",
)
except KeyError:
config.add_error("metadata", "No 'options.python_requires' key found!")

View File

@@ -0,0 +1,246 @@
"""Models for manifest validator."""
from __future__ import annotations
from dataclasses import dataclass, field
from enum import IntEnum
import json
import pathlib
from typing import Any, Literal
@dataclass
class Error:
"""Error validating an integration."""
plugin: str
error: str
fixable: bool = False
def __str__(self) -> str:
"""Represent error as string."""
return f"[{self.plugin.upper()}] {self.error}"
@dataclass
class Config:
"""Config for the run."""
specific_integrations: list[pathlib.Path] | None
root: pathlib.Path
action: Literal["validate", "generate"]
requirements: bool
core_integrations_path: pathlib.Path = field(init=False)
errors: list[Error] = field(default_factory=list)
cache: dict[str, Any] = field(default_factory=dict)
plugins: set[str] = field(default_factory=set)
def __post_init__(self) -> None:
"""Post init."""
self.core_integrations_path = self.root / "homeassistant/components"
def add_error(self, *args: Any, **kwargs: Any) -> None:
"""Add an error."""
self.errors.append(Error(*args, **kwargs))
@dataclass
class Brand:
"""Represent a brand in our validator."""
@classmethod
def load_dir(cls, path: pathlib.Path, config: Config) -> dict[str, Brand]:
"""Load all brands in a directory."""
assert path.is_dir()
brands: dict[str, Brand] = {}
for fil in path.iterdir():
brand = cls(fil)
brand.load_brand(config)
brands[brand.domain] = brand
return brands
path: pathlib.Path
_brand: dict[str, Any] | None = None
@property
def brand(self) -> dict[str, Any]:
"""Guarded access to brand."""
assert self._brand is not None, "brand has not been loaded"
return self._brand
@property
def domain(self) -> str:
"""Integration domain."""
return self.path.stem
@property
def name(self) -> str | None:
"""Return name of the integration."""
return self.brand.get("name")
@property
def integrations(self) -> list[str]:
"""Return the sub integrations of this brand."""
return self.brand.get("integrations", [])
@property
def iot_standards(self) -> list[str]:
"""Return list of supported IoT standards."""
return self.brand.get("iot_standards", [])
def load_brand(self, config: Config) -> None:
"""Load brand file."""
if not self.path.is_file():
config.add_error("model", f"Brand file {self.path} not found")
return
try:
brand: dict[str, Any] = json.loads(self.path.read_text())
except ValueError as err:
config.add_error(
"model", f"Brand file {self.path.name} contains invalid JSON: {err}"
)
return
self._brand = brand
@dataclass
class Integration:
"""Represent an integration in our validator."""
@classmethod
def load_dir(cls, path: pathlib.Path, config: Config) -> dict[str, Integration]:
"""Load all integrations in a directory."""
assert path.is_dir()
integrations: dict[str, Integration] = {}
for fil in path.iterdir():
if fil.is_file() or fil.name == "__pycache__":
continue
init = fil / "__init__.py"
manifest = fil / "manifest.json"
if not init.exists() and not manifest.exists():
print(
f"Warning: {init} and manifest.json missing, "
"skipping directory. If this is your development "
"environment, you can safely delete this folder."
)
continue
integration = cls(fil, config)
integration.load_manifest()
integrations[integration.domain] = integration
return integrations
path: pathlib.Path
_config: Config
_manifest: dict[str, Any] | None = None
manifest_path: pathlib.Path | None = None
errors: list[Error] = field(default_factory=list)
warnings: list[Error] = field(default_factory=list)
translated_name: bool = False
@property
def manifest(self) -> dict[str, Any]:
"""Guarded access to manifest."""
assert self._manifest is not None, "manifest has not been loaded"
return self._manifest
@property
def domain(self) -> str:
"""Integration domain."""
return self.path.name
@property
def core(self) -> bool:
"""Core integration."""
return self.path.as_posix().startswith(
self._config.core_integrations_path.as_posix()
)
@property
def disabled(self) -> str | None:
"""Return if integration is disabled."""
return self.manifest.get("disabled")
@property
def name(self) -> str:
"""Return name of the integration."""
name: str = self.manifest["name"]
return name
@property
def quality_scale(self) -> str | None:
"""Return quality scale of the integration."""
return self.manifest.get("quality_scale")
@property
def config_flow(self) -> bool:
"""Return if the integration has a config flow."""
return self.manifest.get("config_flow", False)
@property
def requirements(self) -> list[str]:
"""List of requirements."""
return self.manifest.get("requirements", [])
@property
def dependencies(self) -> list[str]:
"""List of dependencies."""
return self.manifest.get("dependencies", [])
@property
def supported_by(self) -> str:
"""Return the integration supported by this virtual integration."""
return self.manifest.get("supported_by", {})
@property
def integration_type(self) -> str:
"""Get integration_type."""
return self.manifest.get("integration_type", "hub")
@property
def iot_class(self) -> str | None:
"""Return the integration IoT Class."""
return self.manifest.get("iot_class")
@property
def iot_standards(self) -> list[str]:
"""Return the IoT standard supported by this virtual integration."""
return self.manifest.get("iot_standards", [])
def add_error(self, *args: Any, **kwargs: Any) -> None:
"""Add an error."""
self.errors.append(Error(*args, **kwargs))
def add_warning(self, *args: Any, **kwargs: Any) -> None:
"""Add a warning."""
self.warnings.append(Error(*args, **kwargs))
def load_manifest(self) -> None:
"""Load manifest."""
manifest_path = self.path / "manifest.json"
if not manifest_path.is_file():
self.add_error("model", f"Manifest file {manifest_path} not found")
return
try:
manifest: dict[str, Any] = json.loads(manifest_path.read_text())
except ValueError as err:
self.add_error("model", f"Manifest contains invalid JSON: {err}")
return
self._manifest = manifest
self.manifest_path = manifest_path
class ScaledQualityScaleTiers(IntEnum):
"""Supported manifest quality scales."""
BRONZE = 1
SILVER = 2
GOLD = 3
PLATINUM = 4

View File

@@ -0,0 +1,47 @@
"""Generate MQTT file."""
from __future__ import annotations
from collections import defaultdict
from .model import Config, Integration
from .serializer import format_python_namespace
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)
return format_python_namespace({"MQTT": data})
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
if mqtt_path.read_text() != content:
config.add_error(
"mqtt",
"File mqtt.py is not up to date. Run python3 -m script.hassfest",
fixable=True,
)
def generate(integrations: dict[str, Integration], config: Config) -> None:
"""Generate MQTT file."""
mqtt_path = config.root / "homeassistant/generated/mqtt.py"
mqtt_path.write_text(f"{config.cache['mqtt']}")

View File

@@ -0,0 +1,278 @@
"""Generate mypy config."""
from __future__ import annotations
from collections.abc import Iterable
import configparser
import io
import os
from pathlib import Path
from typing import Final
from homeassistant.const import REQUIRED_PYTHON_VER
from .model import Config, Integration
# Component modules which should set no_implicit_reexport = true.
NO_IMPLICIT_REEXPORT_MODULES: set[str] = {
"homeassistant.components",
"homeassistant.components.application_credentials.*",
"homeassistant.components.diagnostics.*",
"homeassistant.components.spotify.*",
"homeassistant.components.stream.*",
"homeassistant.components.update.*",
}
HEADER: Final = """
# Automatically generated by hassfest.
#
# To update, run python3 -m script.hassfest -p mypy_config
""".lstrip()
GENERAL_SETTINGS: Final[dict[str, str]] = {
"python_version": ".".join(str(x) for x in REQUIRED_PYTHON_VER[:2]),
"platform": "linux",
"plugins": ", ".join( # noqa: FLY002
[
"pydantic.mypy",
"pydantic.v1.mypy",
]
),
"show_error_codes": "true",
"follow_imports": "normal",
# "enable_incomplete_feature": ", ".join( # noqa: FLY002
# []
# ),
# Enable some checks globally.
"local_partial_types": "true",
"strict_equality": "true",
"strict_bytes": "true",
"no_implicit_optional": "true",
"warn_incomplete_stub": "true",
"warn_redundant_casts": "true",
"warn_unused_configs": "true",
"warn_unused_ignores": "true",
"enable_error_code": ", ".join( # noqa: FLY002
[
"deprecated",
"ignore-without-code",
"redundant-self",
"truthy-iterable",
]
),
"disable_error_code": ", ".join( # noqa: FLY002
[
"annotation-unchecked",
"import-not-found",
"import-untyped",
]
),
# Impractical in real code
# E.g. this breaks passthrough ParamSpec typing with Concatenate
"extra_checks": "false",
}
# This is basically the list of checks which is enabled for "strict=true".
# "strict=false" in config files does not turn strict settings off if they've been
# set in a more general section (it instead means as if strict was not specified at
# all), so we need to list all checks manually to be able to flip them wholesale.
STRICT_SETTINGS: Final[list[str]] = [
"check_untyped_defs",
"disallow_incomplete_defs",
"disallow_subclassing_any",
"disallow_untyped_calls",
"disallow_untyped_decorators",
"disallow_untyped_defs",
"warn_return_any",
"warn_unreachable",
# TODO: turn these on, address issues
# "disallow_any_generics",
# "no_implicit_reexport",
]
# Strict settings are already applied for core files.
# To enable granular typing, add additional settings if core files are given.
STRICT_SETTINGS_CORE: Final[list[str]] = [
"disallow_any_generics",
]
# Plugin specific settings
# Bump mypy cache when updating! Some plugins don't invalidate the cache properly.
# pydantic: https://docs.pydantic.dev/mypy_plugin/#plugin-settings
PLUGIN_CONFIG: Final[dict[str, dict[str, str]]] = {
"pydantic-mypy": {
"init_forbid_extra": "true",
"init_typed": "true",
"warn_required_dynamic_aliases": "true",
"warn_untyped_fields": "true",
}
}
def _sort_within_sections(line_iter: Iterable[str]) -> Iterable[str]:
"""Sort lines within sections.
Sections are defined as anything not delimited by a blank line
or an octothorpe-prefixed comment line.
"""
section: list[str] = []
for line in line_iter:
if line.startswith("#") or not line.strip():
yield from sorted(section)
section.clear()
yield line
continue
section.append(line)
yield from sorted(section)
def _get_strict_typing_path(config: Config) -> Path:
return config.root / ".strict-typing"
def _get_mypy_ini_path(config: Config) -> Path:
return config.root / "mypy.ini"
def _generate_and_validate_strict_typing(config: Config) -> str:
"""Validate and generate strict_typing."""
lines = [
line.strip()
for line in _get_strict_typing_path(config).read_text().splitlines()
]
return "\n".join(_sort_within_sections(lines)) + "\n"
def _generate_and_validate_mypy_config(config: Config) -> str:
"""Validate and generate mypy config."""
# Filter empty and commented lines.
parsed_modules: list[str] = [
line.strip()
for line in config.cache["strict_typing"].splitlines()
if line.strip() != "" and not line.startswith("#")
]
strict_modules: list[str] = []
strict_core_modules: list[str] = []
for module in parsed_modules:
if module.startswith("homeassistant.components"):
strict_modules.append(module)
else:
strict_core_modules.append(module)
# Validate that all modules exist.
all_modules = (
strict_modules + strict_core_modules + list(NO_IMPLICIT_REEXPORT_MODULES)
)
for module in all_modules:
if module.endswith(".*"):
module_path = Path(module[:-2].replace(".", os.path.sep))
if not module_path.is_dir():
config.add_error("mypy_config", f"Module '{module} is not a folder")
else:
module = module.replace(".", os.path.sep)
module_path = Path(f"{module}.py")
if module_path.is_file():
continue
module_path = Path(module) / "__init__.py"
if not module_path.is_file():
config.add_error("mypy_config", f"Module '{module} doesn't exist")
# Don't generate mypy.ini if there're errors found because it will likely crash.
if any(err.plugin == "mypy_config" for err in config.errors):
return ""
mypy_config = configparser.ConfigParser()
general_section = "mypy"
mypy_config.add_section(general_section)
for key, value in GENERAL_SETTINGS.items():
mypy_config.set(general_section, key, value)
for key in STRICT_SETTINGS:
mypy_config.set(general_section, key, "true")
for plugin_name, plugin_config in PLUGIN_CONFIG.items():
if not plugin_config:
continue
mypy_config.add_section(plugin_name)
for key, value in plugin_config.items():
mypy_config.set(plugin_name, key, value)
# By default enable no_implicit_reexport only for homeassistant.*
# Disable it afterwards for all components
components_section = "mypy-homeassistant.*"
mypy_config.add_section(components_section)
mypy_config.set(components_section, "no_implicit_reexport", "true")
for core_module in strict_core_modules:
core_section = f"mypy-{core_module}"
mypy_config.add_section(core_section)
for key in STRICT_SETTINGS_CORE:
mypy_config.set(core_section, key, "true")
# By default strict checks are disabled for components.
components_section = "mypy-homeassistant.components.*"
mypy_config.add_section(components_section)
for key in STRICT_SETTINGS:
mypy_config.set(components_section, key, "false")
mypy_config.set(components_section, "no_implicit_reexport", "false")
for strict_module in strict_modules:
strict_section = f"mypy-{strict_module}"
mypy_config.add_section(strict_section)
for key in STRICT_SETTINGS:
mypy_config.set(strict_section, key, "true")
if strict_module in NO_IMPLICIT_REEXPORT_MODULES:
mypy_config.set(strict_section, "no_implicit_reexport", "true")
for reexport_module in sorted(
NO_IMPLICIT_REEXPORT_MODULES.difference(strict_modules)
):
reexport_section = f"mypy-{reexport_module}"
mypy_config.add_section(reexport_section)
mypy_config.set(reexport_section, "no_implicit_reexport", "true")
# Disable strict checks for tests
tests_section = "mypy-tests.*"
mypy_config.add_section(tests_section)
for key in STRICT_SETTINGS:
mypy_config.set(tests_section, key, "false")
with io.StringIO() as fp:
mypy_config.write(fp)
fp.seek(0)
return f"{HEADER}{fp.read().strip()}\n"
def validate(integrations: dict[str, Integration], config: Config) -> None:
"""Validate strict_typing and mypy config."""
strict_typing_content = _generate_and_validate_strict_typing(config)
config.cache["strict_typing"] = strict_typing_content
mypy_content = _generate_and_validate_mypy_config(config)
config.cache["mypy_config"] = mypy_content
if any(err.plugin == "mypy_config" for err in config.errors):
return
if _get_strict_typing_path(config).read_text() != strict_typing_content:
config.add_error(
"mypy_config",
"File .strict_typing is not up to date. Run python3 -m script.hassfest",
fixable=True,
)
if _get_mypy_ini_path(config).read_text() != mypy_content:
config.add_error(
"mypy_config",
"File mypy.ini is not up to date. Run python3 -m script.hassfest",
fixable=True,
)
def generate(integrations: dict[str, Integration], config: Config) -> None:
"""Generate strict_typing and mypy config."""
_get_mypy_ini_path(config).write_text(config.cache["mypy_config"])
_get_strict_typing_path(config).write_text(config.cache["strict_typing"])

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,17 @@
"""Integration quality scale rules."""
from typing import Protocol
from script.hassfest.model import Config, Integration
class RuleValidationProtocol(Protocol):
"""Protocol for rule validation."""
def validate(
self, config: Config, integration: Integration, *, rules_done: set[str]
) -> list[str] | None:
"""Validate a quality scale rule.
Returns error (if any).
"""

View File

@@ -0,0 +1,33 @@
"""Enforce that the integration implements entry unloading.
https://developers.home-assistant.io/docs/core/integration-quality-scale/rules/config-entry-unloading/
"""
import ast
from script.hassfest import ast_parse_module
from script.hassfest.model import Config, Integration
def _has_unload_entry_function(module: ast.Module) -> bool:
"""Test if the module defines `async_unload_entry` function."""
return any(
type(item) is ast.AsyncFunctionDef and item.name == "async_unload_entry"
for item in module.body
)
def validate(
config: Config, integration: Integration, *, rules_done: set[str]
) -> list[str] | None:
"""Validate that the integration has a config flow."""
init_file = integration.path / "__init__.py"
init = ast_parse_module(init_file)
if not _has_unload_entry_function(init):
return [
"Integration does not support config entry unloading "
"(is missing `async_unload_entry` in __init__.py)"
]
return None

View File

@@ -0,0 +1,26 @@
"""Enforce that the integration implements config flow.
https://developers.home-assistant.io/docs/core/integration-quality-scale/rules/config-flow/
"""
from script.hassfest.model import Config, Integration
def validate(
config: Config, integration: Integration, *, rules_done: set[str]
) -> list[str] | None:
"""Validate that the integration implements config flow."""
if not integration.config_flow:
return [
"Integration does not set config_flow in its manifest "
f"homeassistant/components/{integration.domain}/manifest.json",
]
config_flow_file = integration.path / "config_flow.py"
if not config_flow_file.exists():
return [
"Integration does not implement config flow (is missing config_flow.py)",
]
return None

View File

@@ -0,0 +1,45 @@
"""Enforce that the integration implements diagnostics.
https://developers.home-assistant.io/docs/core/integration-quality-scale/rules/diagnostics/
"""
import ast
from script.hassfest import ast_parse_module
from script.hassfest.model import Config, Integration
DIAGNOSTICS_FUNCTIONS = {
"async_get_config_entry_diagnostics",
"async_get_device_diagnostics",
}
def _has_diagnostics_function(module: ast.Module) -> bool:
"""Test if the module defines at least one of diagnostic functions."""
return any(
type(item) is ast.AsyncFunctionDef and item.name in DIAGNOSTICS_FUNCTIONS
for item in ast.walk(module)
)
def validate(
config: Config, integration: Integration, *, rules_done: set[str]
) -> list[str] | None:
"""Validate that the integration implements diagnostics."""
diagnostics_file = integration.path / "diagnostics.py"
if not diagnostics_file.exists():
return [
"Integration does implement diagnostics platform "
"(is missing diagnostics.py)",
]
diagnostics = ast_parse_module(diagnostics_file)
if not _has_diagnostics_function(diagnostics):
return [
f"Integration is missing one of {DIAGNOSTICS_FUNCTIONS} "
f"in {diagnostics_file}"
]
return None

View File

@@ -0,0 +1,62 @@
"""Enforce that the integration supports discovery.
https://developers.home-assistant.io/docs/core/integration-quality-scale/rules/discovery/
"""
import ast
from script.hassfest import ast_parse_module
from script.hassfest.model import Config, Integration
MANIFEST_KEYS = [
"bluetooth",
"dhcp",
"homekit",
"mqtt",
"ssdp",
"usb",
"zeroconf",
]
CONFIG_FLOW_STEPS = {
"async_step_bluetooth",
"async_step_discovery",
"async_step_dhcp",
"async_step_hassio",
"async_step_homekit",
"async_step_mqtt",
"async_step_ssdp",
"async_step_usb",
"async_step_zeroconf",
}
def _has_discovery_function(module: ast.Module) -> bool:
"""Test if the module defines at least one of the discovery functions."""
return any(
type(item) is ast.AsyncFunctionDef and item.name in CONFIG_FLOW_STEPS
for item in ast.walk(module)
)
def validate(
config: Config, integration: Integration, *, rules_done: set[str]
) -> list[str] | None:
"""Validate that the integration implements diagnostics."""
config_flow_file = integration.path / "config_flow.py"
if not config_flow_file.exists():
return ["Integration is missing config_flow.py"]
# Check manifest
if any(key in integration.manifest for key in MANIFEST_KEYS):
return None
# Fallback => check config_flow step
config_flow = ast_parse_module(config_flow_file)
if not (_has_discovery_function(config_flow)):
return [
f"Integration is missing one of {CONFIG_FLOW_STEPS} "
f"in {config_flow_file}"
]
return None

View File

@@ -0,0 +1,38 @@
"""Enforce that the integration sets PARALLEL_UPDATES constant.
https://developers.home-assistant.io/docs/core/integration-quality-scale/rules/parallel-updates
"""
import ast
from homeassistant.const import Platform
from script.hassfest import ast_parse_module
from script.hassfest.model import Config, Integration
def _has_parallel_updates_defined(module: ast.Module) -> bool:
"""Test if the module defines `PARALLEL_UPDATES` constant."""
return any(
type(item) is ast.Assign and item.targets[0].id == "PARALLEL_UPDATES"
for item in module.body
)
def validate(
config: Config, integration: Integration, *, rules_done: set[str]
) -> list[str] | None:
"""Validate that the integration sets PARALLEL_UPDATES constant."""
errors = []
for platform in Platform:
module_file = integration.path / f"{platform}.py"
if not module_file.exists():
continue
module = ast_parse_module(module_file)
if not _has_parallel_updates_defined(module):
errors.append(
f"Integration does not set `PARALLEL_UPDATES` in {module_file}"
)
return errors

View File

@@ -0,0 +1,33 @@
"""Enforce that the integration implements reauthentication flow.
https://developers.home-assistant.io/docs/core/integration-quality-scale/rules/reauthentication-flow/
"""
import ast
from script.hassfest import ast_parse_module
from script.hassfest.model import Config, Integration
def _has_step_reauth_function(module: ast.Module) -> bool:
"""Test if the module defines `async_step_reauth` function."""
return any(
type(item) is ast.AsyncFunctionDef and item.name == "async_step_reauth"
for item in ast.walk(module)
)
def validate(
config: Config, integration: Integration, *, rules_done: set[str]
) -> list[str] | None:
"""Validate that the integration has a reauthentication flow."""
config_flow_file = integration.path / "config_flow.py"
config_flow = ast_parse_module(config_flow_file)
if not _has_step_reauth_function(config_flow):
return [
"Integration does not support a reauthentication flow "
f"(is missing `async_step_reauth` in {config_flow_file})"
]
return None

View File

@@ -0,0 +1,33 @@
"""Enforce that the integration implements reconfiguration flow.
https://developers.home-assistant.io/docs/core/integration-quality-scale/rules/reconfiguration-flow/
"""
import ast
from script.hassfest import ast_parse_module
from script.hassfest.model import Config, Integration
def _has_step_reconfigure_function(module: ast.Module) -> bool:
"""Test if the module defines a function."""
return any(
type(item) is ast.AsyncFunctionDef and item.name == "async_step_reconfigure"
for item in ast.walk(module)
)
def validate(
config: Config, integration: Integration, *, rules_done: set[str]
) -> list[str] | None:
"""Validate that the integration has a reconfiguration flow."""
config_flow_file = integration.path / "config_flow.py"
config_flow = ast_parse_module(config_flow_file)
if not _has_step_reconfigure_function(config_flow):
return [
"Integration does not support a reconfiguration flow "
f"(is missing `async_step_reconfigure` in {config_flow_file})"
]
return None

View File

@@ -0,0 +1,130 @@
"""Enforce that the integration uses ConfigEntry.runtime_data to store runtime data.
https://developers.home-assistant.io/docs/core/integration-quality-scale/rules/runtime-data
"""
import ast
import re
from homeassistant.const import Platform
from script.hassfest import ast_parse_module
from script.hassfest.model import Config, Integration
_ANNOTATION_MATCH = re.compile(r"^[A-Za-z]+ConfigEntry$")
_FUNCTIONS: dict[str, dict[str, int]] = {
"__init__": { # based on ComponentProtocol
"async_migrate_entry": 2,
"async_remove_config_entry_device": 2,
"async_remove_entry": 2,
"async_setup_entry": 2,
"async_unload_entry": 2,
},
"diagnostics": { # based on DiagnosticsProtocol
"async_get_config_entry_diagnostics": 2,
"async_get_device_diagnostics": 2,
},
}
for platform in Platform: # based on EntityPlatformModule
_FUNCTIONS[platform.value] = {
"async_setup_entry": 2,
}
def _sets_runtime_data(
async_setup_entry_function: ast.AsyncFunctionDef, config_entry_argument: ast.arg
) -> bool:
"""Check that `entry.runtime` gets set within `async_setup_entry`."""
for node in ast.walk(async_setup_entry_function):
if (
isinstance(node, ast.Attribute)
and isinstance(node.value, ast.Name)
and node.value.id == config_entry_argument.arg
and node.attr == "runtime_data"
and isinstance(node.ctx, ast.Store)
):
return True
return False
def _get_async_function(module: ast.Module, name: str) -> ast.AsyncFunctionDef | None:
"""Get async function."""
for item in module.body:
if isinstance(item, ast.AsyncFunctionDef) and item.name == name:
return item
return None
def _check_function_annotation(
function: ast.AsyncFunctionDef, position: int
) -> str | None:
"""Ensure function uses CustomConfigEntry type annotation."""
if len(function.args.args) < position:
return f"{function.name} has incorrect signature"
argument = function.args.args[position - 1]
if not (
(annotation := argument.annotation)
and isinstance(annotation, ast.Name)
and _ANNOTATION_MATCH.match(annotation.id)
):
return f"([+ strict-typing]) {function.name} does not use typed ConfigEntry"
return None
def _check_typed_config_entry(integration: Integration) -> list[str]:
"""Ensure integration uses CustomConfigEntry type annotation."""
errors: list[str] = []
# Check body level function annotations
for file, functions in _FUNCTIONS.items():
module_file = integration.path / f"{file}.py"
if not module_file.exists():
continue
module = ast_parse_module(module_file)
for function, position in functions.items():
if not (async_function := _get_async_function(module, function)):
continue
if error := _check_function_annotation(async_function, position):
errors.append(f"{error} in {module_file}")
# Check config_flow annotations
config_flow_file = integration.path / "config_flow.py"
config_flow = ast_parse_module(config_flow_file)
for node in config_flow.body:
if not isinstance(node, ast.ClassDef):
continue
if any(
isinstance(async_function, ast.FunctionDef)
and async_function.name == "async_get_options_flow"
and (error := _check_function_annotation(async_function, 1))
for async_function in node.body
):
errors.append(f"{error} in {config_flow_file}")
return errors
def validate(
config: Config, integration: Integration, *, rules_done: set[str]
) -> list[str] | None:
"""Validate correct use of ConfigEntry.runtime_data."""
init_file = integration.path / "__init__.py"
init = ast_parse_module(init_file)
# Should not happen, but better to be safe
if not (async_setup_entry := _get_async_function(init, "async_setup_entry")):
return [f"Could not find `async_setup_entry` in {init_file}"]
if len(async_setup_entry.args.args) != 2:
return [f"async_setup_entry has incorrect signature in {init_file}"]
config_entry_argument = async_setup_entry.args.args[1]
errors: list[str] = []
if not _sets_runtime_data(async_setup_entry, config_entry_argument):
errors.append(
"Integration does not set entry.runtime_data in async_setup_entry"
f"({init_file})"
)
# Extra checks, if strict-typing is marked as done
if "strict-typing" in rules_done:
errors.extend(_check_typed_config_entry(integration))
return errors

View File

@@ -0,0 +1,67 @@
"""Enforce that the integration has strict typing enabled.
https://developers.home-assistant.io/docs/core/integration-quality-scale/rules/strict-typing/
"""
from functools import lru_cache
from importlib import metadata
from pathlib import Path
import re
from script.hassfest.model import Config, Integration
_STRICT_TYPING_FILE = Path(".strict-typing")
_COMPONENT_REGEX = r"homeassistant.components.([^.]+).*"
@lru_cache
def _strict_typing_components(strict_typing_file: Path) -> set[str]:
return set(
{
match.group(1)
for line in strict_typing_file.read_text(encoding="utf-8").splitlines()
if (match := re.match(_COMPONENT_REGEX, line)) is not None
}
)
def _check_requirements_are_typed(integration: Integration) -> list[str]:
"""Check if all requirements are typed."""
invalid_requirements = []
for requirement in integration.requirements:
requirement_name, requirement_version = requirement.split("==")
# Remove any extras
requirement_name = requirement_name.split("[")[0]
try:
distribution = metadata.distribution(requirement_name)
except metadata.PackageNotFoundError:
# Package not installed locally
continue
if distribution.version != requirement_version:
# Version out of date locally
continue
if not any(file for file in distribution.files if file.name == "py.typed"):
# no py.typed file
invalid_requirements.append(requirement)
return invalid_requirements
def validate(
config: Config, integration: Integration, *, rules_done: set[str]
) -> list[str] | None:
"""Validate that the integration has strict typing enabled."""
strict_typing_file = config.root / _STRICT_TYPING_FILE
if integration.domain not in _strict_typing_components(strict_typing_file):
return [
"Integration does not have strict typing enabled "
"(is missing from .strict-typing)"
]
if untyped_requirements := _check_requirements_are_typed(integration):
return [
f"Requirements {untyped_requirements} do not conform PEP 561 (https://peps.python.org/pep-0561/)",
"They should be typed and have a 'py.typed' file",
]
return None

View File

@@ -0,0 +1,89 @@
"""Enforce that the integration raises correctly during initialisation.
https://developers.home-assistant.io/docs/core/integration-quality-scale/rules/test-before-setup/
"""
import ast
from script.hassfest import ast_parse_module
from script.hassfest.model import Config, Integration
_VALID_EXCEPTIONS = {
"ConfigEntryNotReady",
"ConfigEntryAuthFailed",
"ConfigEntryError",
}
def _get_exception_name(expression: ast.expr) -> str:
"""Get the name of the exception being raised."""
if expression is None:
# Bare raise
return None
if isinstance(expression, ast.Name):
# Raise Exception
return expression.id
if isinstance(expression, ast.Call):
# Raise Exception()
return _get_exception_name(expression.func)
if isinstance(expression, ast.Attribute):
# Raise namespace.???
return _get_exception_name(expression.value)
raise AssertionError(
f"Raise is neither Attribute nor Call nor Name: {type(expression)}"
)
def _raises_exception(integration: Integration) -> bool:
"""Check that a valid exception is raised."""
for module_file in integration.path.rglob("*.py"):
module = ast_parse_module(module_file)
for node in ast.walk(module):
if (
isinstance(node, ast.Raise)
and _get_exception_name(node.exc) in _VALID_EXCEPTIONS
):
return True
return False
def _calls_first_refresh(async_setup_entry_function: ast.AsyncFunctionDef) -> bool:
"""Check that a async_config_entry_first_refresh within `async_setup_entry`."""
for node in ast.walk(async_setup_entry_function):
if (
isinstance(node, ast.Call)
and isinstance(node.func, ast.Attribute)
and node.func.attr == "async_config_entry_first_refresh"
):
return True
return False
def _get_setup_entry_function(module: ast.Module) -> ast.AsyncFunctionDef | None:
"""Get async_setup_entry function."""
for item in module.body:
if isinstance(item, ast.AsyncFunctionDef) and item.name == "async_setup_entry":
return item
return None
def validate(
config: Config, integration: Integration, *, rules_done: set[str]
) -> list[str] | None:
"""Validate correct use of ConfigEntry.runtime_data."""
init_file = integration.path / "__init__.py"
init = ast_parse_module(init_file)
# Should not happen, but better to be safe
if not (async_setup_entry := _get_setup_entry_function(init)):
return [f"Could not find `async_setup_entry` in {init_file}"]
if not (_calls_first_refresh(async_setup_entry) or _raises_exception(integration)):
return [f"Integration does not raise one of {_VALID_EXCEPTIONS}"]
return None

View File

@@ -0,0 +1,52 @@
"""Enforce that the integration prevents duplicates from being configured.
https://developers.home-assistant.io/docs/core/integration-quality-scale/rules/unique-config-entry/
"""
import ast
from script.hassfest import ast_parse_module
from script.hassfest.model import Config, Integration
def _has_method_call(module: ast.Module, name: str) -> bool:
"""Test if the module calls a specific method."""
return any(
type(item.func) is ast.Attribute and item.func.attr == name
for item in ast.walk(module)
if isinstance(item, ast.Call)
)
def _has_abort_entries_match(module: ast.Module) -> bool:
"""Test if the module calls `_async_abort_entries_match`."""
return _has_method_call(module, "_async_abort_entries_match")
def _has_abort_unique_id_configured(module: ast.Module) -> bool:
"""Test if the module calls defines (and checks for) a unique_id."""
return _has_method_call(module, "async_set_unique_id") and _has_method_call(
module, "_abort_if_unique_id_configured"
)
def validate(
config: Config, integration: Integration, *, rules_done: set[str]
) -> list[str] | None:
"""Validate that the integration prevents duplicate devices."""
if integration.manifest.get("single_config_entry"):
return None
config_flow_file = integration.path / "config_flow.py"
config_flow = ast_parse_module(config_flow_file)
if not (
_has_abort_entries_match(config_flow)
or _has_abort_unique_id_configured(config_flow)
):
return [
"Integration doesn't prevent the same device or service from being "
f"set up twice in {config_flow_file}"
]
return None

View File

@@ -0,0 +1,269 @@
"""Validate requirements."""
from __future__ import annotations
from collections import deque
from functools import cache
import json
import os
import re
import subprocess
import sys
from typing import Any
from awesomeversion import AwesomeVersion, AwesomeVersionStrategy
from tqdm import tqdm
import homeassistant.util.package as pkg_util
from script.gen_requirements_all import (
EXCLUDED_REQUIREMENTS_ALL,
normalize_package_name,
)
from .model import Config, Integration
PACKAGE_REGEX = re.compile(
r"^(?:--.+\s)?([-_,\.\w\d\[\]]+)(==|>=|<=|~=|!=|<|>|===)*(.*)$"
)
PIP_REGEX = re.compile(r"^(--.+\s)?([-_\.\w\d]+.*(?:==|>=|<=|~=|!=|<|>|===)?.*$)")
PIP_VERSION_RANGE_SEPARATOR = re.compile(r"^(==|>=|<=|~=|!=|<|>|===)?(.*)$")
def validate(integrations: dict[str, Integration], config: Config) -> None:
"""Handle requirements for integrations."""
# Check if we are doing format-only validation.
if not config.requirements:
for integration in integrations.values():
validate_requirements_format(integration)
return
# check for incompatible requirements
disable_tqdm = bool(config.specific_integrations or os.environ.get("CI"))
for integration in tqdm(integrations.values(), disable=disable_tqdm):
validate_requirements(integration)
def validate_requirements_format(integration: Integration) -> bool:
"""Validate requirements format.
Returns if valid.
"""
start_errors = len(integration.errors)
for req in integration.requirements:
if " " in req:
integration.add_error(
"requirements",
f'Requirement "{req}" contains a space',
)
continue
if not (match := PACKAGE_REGEX.match(req)):
integration.add_error(
"requirements",
f'Requirement "{req}" does not match package regex pattern',
)
continue
pkg, sep, version = match.groups()
if integration.core and sep != "==":
integration.add_error(
"requirements",
f'Requirement {req} need to be pinned "<pkg name>==<version>".',
)
continue
if not version:
continue
if integration.core:
for part in version.split(";", 1)[0].split(","):
version_part = PIP_VERSION_RANGE_SEPARATOR.match(part)
if (
version_part
and AwesomeVersion(version_part.group(2)).strategy
== AwesomeVersionStrategy.UNKNOWN
):
integration.add_error(
"requirements",
f"Unable to parse package version ({version}) for {pkg}.",
)
continue
return len(integration.errors) == start_errors
def validate_requirements(integration: Integration) -> None:
"""Validate requirements."""
if not validate_requirements_format(integration):
return
integration_requirements = set()
integration_packages = set()
for req in integration.requirements:
package = normalize_package_name(req)
if not package:
integration.add_error(
"requirements",
f"Failed to normalize package name from requirement {req}",
)
return
if package in EXCLUDED_REQUIREMENTS_ALL:
continue
integration_requirements.add(req)
integration_packages.add(package)
if integration.disabled:
return
install_ok = install_requirements(integration, integration_requirements)
if not install_ok:
return
all_integration_requirements = get_requirements(integration, integration_packages)
if integration_requirements and not all_integration_requirements:
integration.add_error(
"requirements",
f"Failed to resolve requirements {integration_requirements}",
)
return
# Check for requirements incompatible with standard library.
standard_library_violations = set()
for req in all_integration_requirements:
if req in sys.stdlib_module_names:
standard_library_violations.add(req)
if standard_library_violations:
integration.add_error(
"requirements",
(
f"Package {req} has dependencies {standard_library_violations} which "
"are not compatible with the Python standard library"
),
)
@cache
def get_pipdeptree() -> dict[str, dict[str, Any]]:
"""Get pipdeptree output. Cached on first invocation.
{
"flake8-docstring": {
"key": "flake8-docstrings",
"package_name": "flake8-docstrings",
"installed_version": "1.5.0"
"dependencies": {"flake8"}
}
}
"""
deptree = {}
for item in json.loads(
subprocess.run(
["pipdeptree", "-w", "silence", "--json"],
check=True,
capture_output=True,
text=True,
).stdout
):
deptree[item["package"]["key"]] = {
**item["package"],
"dependencies": {dep["key"] for dep in item["dependencies"]},
}
return deptree
def get_requirements(integration: Integration, packages: set[str]) -> set[str]:
"""Return all (recursively) requirements for an integration."""
deptree = get_pipdeptree()
all_requirements = set()
to_check = deque(packages)
while to_check:
package = to_check.popleft()
if package in all_requirements:
continue
all_requirements.add(package)
item = deptree.get(package)
if item is None:
# Only warn if direct dependencies could not be resolved
if package in packages:
integration.add_error(
"requirements", f"Failed to resolve requirements for {package}"
)
continue
to_check.extend(item["dependencies"])
return all_requirements
def install_requirements(integration: Integration, requirements: set[str]) -> bool:
"""Install integration requirements.
Return True if successful.
"""
deptree = get_pipdeptree()
for req in requirements:
match = PIP_REGEX.search(req)
if not match:
integration.add_error(
"requirements",
f"Failed to parse requirement {req} before installation",
)
continue
install_args = match.group(1)
requirement_arg = match.group(2)
is_installed = False
normalized = normalize_package_name(requirement_arg)
if normalized and "==" in requirement_arg:
ver = requirement_arg.split("==")[-1]
item = deptree.get(normalized)
is_installed = bool(item and item["installed_version"] == ver)
if not is_installed:
try:
is_installed = pkg_util.is_installed(req)
except ValueError:
is_installed = False
if is_installed:
continue
args = ["uv", "pip", "install", "--quiet"]
if install_args:
args.append(install_args)
args.append(requirement_arg)
try:
result = subprocess.run(args, check=True, capture_output=True, text=True)
except subprocess.SubprocessError:
integration.add_error(
"requirements",
f"Requirement {req} failed to install",
)
else:
# Clear the pipdeptree cache if something got installed
if "Successfully installed" in result.stdout:
get_pipdeptree.cache_clear()
if integration.errors:
return False
return True

View File

@@ -0,0 +1,107 @@
"""Hassfest utils."""
from __future__ import annotations
from collections.abc import Collection, Iterable, Mapping
import shutil
import subprocess
from typing import Any
DEFAULT_GENERATOR = "script.hassfest"
def _wrap_items(
items: Iterable[str],
opener: str,
closer: str,
sort: bool = False,
) -> str:
"""Wrap pre-formatted Python reprs in braces, optionally sorting them."""
# The trailing comma is imperative so Black doesn't format some items
# on one line and some on multiple.
if sort:
items = sorted(items)
joined_items = ", ".join(items)
return f"{opener}{joined_items}{',' if joined_items else ''}{closer}"
def _mapping_to_str(data: Mapping[Any, Any]) -> str:
"""Return a string representation of a mapping."""
return _wrap_items(
(f"{to_string(key)}:{to_string(value)}" for key, value in data.items()),
opener="{",
closer="}",
sort=True,
)
def _collection_to_str(
data: Collection[Any],
opener: str = "[",
closer: str = "]",
sort: bool = False,
) -> str:
"""Return a string representation of a collection."""
items = (to_string(value) for value in data)
return _wrap_items(items, opener, closer, sort=sort)
def to_string(data: Any) -> str:
"""Return a string representation of the input."""
if isinstance(data, dict):
return _mapping_to_str(data)
if isinstance(data, list):
return _collection_to_str(data)
if isinstance(data, set):
return _collection_to_str(data, "{", "}", sort=True)
return repr(data)
def format_python(
content: str,
*,
generator: str = DEFAULT_GENERATOR,
) -> str:
"""Format Python code with Black. Optionally prepend a generator comment."""
if generator:
content = f"""\"\"\"Automatically generated file.
To update, run python3 -m {generator}
\"\"\"
{content}
"""
ruff = shutil.which("ruff")
if not ruff:
raise RuntimeError("ruff not found")
return subprocess.check_output(
[ruff, "format", "-"],
input=content.strip(),
encoding="utf-8",
)
def format_python_namespace(
content: dict[str, Any],
*,
annotations: dict[str, str] | None = None,
generator: str = DEFAULT_GENERATOR,
) -> str:
"""Generate a nicely formatted "namespace" file.
The keys of the `content` dict will be used as variable names.
"""
def _get_annotation(key: str) -> str:
annotation = (annotations or {}).get(key)
return f": {annotation}" if annotation else ""
code = "\n\n".join(
f"{key}{_get_annotation(key)} = {to_string(value)}"
for key, value in sorted(content.items())
)
if annotations:
# If we had any annotations, add __future__ and typing imports.
code = f"from __future__ import annotations\n\nfrom typing import Final\n{code}"
return format_python(code, generator=generator)

View File

@@ -0,0 +1,312 @@
"""Validate dependencies."""
from __future__ import annotations
import contextlib
import json
import pathlib
import re
from typing import Any
import voluptuous as vol
from voluptuous.humanize import humanize_error
from homeassistant.const import CONF_SELECTOR
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_validation as cv, selector, service
from homeassistant.util.yaml import load_yaml_dict
from .model import Config, Integration
def exists(value: Any) -> Any:
"""Check if value exists."""
if value is None:
raise vol.Invalid("Value cannot be None")
return value
def unique_field_validator(fields: Any) -> Any:
"""Validate the inputs don't have duplicate keys under different sections."""
all_fields = set()
for key, value in fields.items():
if value and "fields" in value:
for key in value["fields"]:
if key in all_fields:
raise vol.Invalid(f"Duplicate use of field {key} in service.")
all_fields.add(key)
else:
if key in all_fields:
raise vol.Invalid(f"Duplicate use of field {key} in service.")
all_fields.add(key)
return fields
CORE_INTEGRATION_FIELD_SCHEMA = vol.Schema(
{
vol.Optional("example"): exists,
vol.Optional("default"): exists,
vol.Optional("required"): bool,
vol.Optional("advanced"): bool,
vol.Optional(CONF_SELECTOR): selector.validate_selector,
vol.Optional("filter"): {
vol.Exclusive("attribute", "field_filter"): {
vol.Required(str): [vol.All(str, service.validate_attribute_option)],
},
vol.Exclusive("supported_features", "field_filter"): [
vol.All(str, service.validate_supported_feature)
],
},
}
)
CORE_INTEGRATION_SECTION_SCHEMA = vol.Schema(
{
vol.Optional("collapsed"): bool,
vol.Required("fields"): vol.Schema({str: CORE_INTEGRATION_FIELD_SCHEMA}),
}
)
CUSTOM_INTEGRATION_FIELD_SCHEMA = CORE_INTEGRATION_FIELD_SCHEMA.extend(
{
vol.Optional("description"): str,
vol.Optional("name"): str,
}
)
CUSTOM_INTEGRATION_SECTION_SCHEMA = vol.Schema(
{
vol.Optional("description"): str,
vol.Optional("name"): str,
vol.Optional("collapsed"): bool,
vol.Required("fields"): vol.Schema({str: CUSTOM_INTEGRATION_FIELD_SCHEMA}),
}
)
CORE_INTEGRATION_SERVICE_SCHEMA = vol.Any(
vol.Schema(
{
vol.Optional("target"): vol.Any(
selector.TargetSelector.CONFIG_SCHEMA, None
),
vol.Optional("fields"): vol.All(
vol.Schema(
{
str: vol.Any(
CORE_INTEGRATION_FIELD_SCHEMA,
CORE_INTEGRATION_SECTION_SCHEMA,
)
}
),
unique_field_validator,
),
}
),
None,
)
CUSTOM_INTEGRATION_SERVICE_SCHEMA = vol.Any(
vol.Schema(
{
vol.Optional("description"): str,
vol.Optional("name"): str,
vol.Optional("target"): vol.Any(
selector.TargetSelector.CONFIG_SCHEMA, None
),
vol.Optional("fields"): vol.All(
vol.Schema(
{
str: vol.Any(
CUSTOM_INTEGRATION_FIELD_SCHEMA,
CUSTOM_INTEGRATION_SECTION_SCHEMA,
)
}
),
unique_field_validator,
),
}
),
None,
)
CORE_INTEGRATION_SERVICES_SCHEMA = vol.Schema(
{
vol.Remove(vol.All(str, service.starts_with_dot)): object,
cv.slug: CORE_INTEGRATION_SERVICE_SCHEMA,
}
)
CUSTOM_INTEGRATION_SERVICES_SCHEMA = vol.Schema(
{cv.slug: CUSTOM_INTEGRATION_SERVICE_SCHEMA}
)
VALIDATE_AS_CUSTOM_INTEGRATION = {
# Adding translations would be a breaking change
"foursquare",
}
def grep_dir(path: pathlib.Path, glob_pattern: str, search_pattern: str) -> bool:
"""Recursively go through a dir and it's children and find the regex."""
pattern = re.compile(search_pattern)
for fil in path.glob(glob_pattern):
if not fil.is_file():
continue
if pattern.search(fil.read_text()):
return True
return False
def validate_services(config: Config, integration: Integration) -> None: # noqa: C901
"""Validate services."""
try:
data = load_yaml_dict(str(integration.path / "services.yaml"))
except FileNotFoundError:
# Find if integration uses services
has_services = grep_dir(
integration.path,
"**/*.py",
r"(hass\.services\.(register|async_register))|async_register_entity_service|async_register_admin_service",
)
if has_services:
integration.add_error(
"services", "Registers services but has no services.yaml"
)
return
except HomeAssistantError:
integration.add_error("services", "Invalid services.yaml")
return
try:
if (
integration.core
and integration.domain not in VALIDATE_AS_CUSTOM_INTEGRATION
):
services = CORE_INTEGRATION_SERVICES_SCHEMA(data)
else:
services = CUSTOM_INTEGRATION_SERVICES_SCHEMA(data)
except vol.Invalid as err:
integration.add_error(
"services", f"Invalid services.yaml: {humanize_error(data, err)}"
)
return
icons_file = integration.path / "icons.json"
icons = {}
if icons_file.is_file():
with contextlib.suppress(ValueError):
icons = json.loads(icons_file.read_text())
service_icons = icons.get("services", {})
# Try loading translation strings
if integration.core:
strings_file = integration.path / "strings.json"
else:
# For custom integrations, use the en.json file
strings_file = integration.path / "translations/en.json"
strings = {}
if strings_file.is_file():
with contextlib.suppress(ValueError):
strings = json.loads(strings_file.read_text())
error_msg_suffix = "in the translations file"
if not integration.core:
error_msg_suffix = f"and is not {error_msg_suffix}"
# For each service in the integration:
# 1. Check if the service description is set, if not,
# check if it's in the strings file else add an error.
# 2. Check if the service has an icon set in icons.json.
# raise an error if not.,
for service_name, service_schema in services.items():
if integration.core and service_name not in service_icons:
# This is enforced for Core integrations only
integration.add_error(
"services",
f"Service {service_name} has no icon in icons.json.",
)
if service_schema is None:
continue
if "name" not in service_schema:
try:
strings["services"][service_name]["name"]
except KeyError:
integration.add_error(
"services",
f"Service {service_name} has no name {error_msg_suffix}",
)
if "description" not in service_schema:
try:
strings["services"][service_name]["description"]
except KeyError:
integration.add_error(
"services",
f"Service {service_name} has no description {error_msg_suffix}",
)
# The same check is done for the description in each of the fields of the
# service schema.
for field_name, field_schema in service_schema.get("fields", {}).items():
if "fields" in field_schema:
# This is a section
continue
if "name" not in field_schema:
try:
strings["services"][service_name]["fields"][field_name]["name"]
except KeyError:
integration.add_error(
"services",
f"Service {service_name} has a field {field_name} with no name {error_msg_suffix}",
)
if "description" not in field_schema:
try:
strings["services"][service_name]["fields"][field_name][
"description"
]
except KeyError:
integration.add_error(
"services",
f"Service {service_name} has a field {field_name} with no description {error_msg_suffix}",
)
if "selector" in field_schema:
with contextlib.suppress(KeyError):
translation_key = field_schema["selector"]["select"][
"translation_key"
]
try:
strings["selector"][translation_key]
except KeyError:
integration.add_error(
"services",
f"Service {service_name} has a field {field_name} with a selector with a translation key {translation_key} that is not in the translations file",
)
# The same check is done for the description in each of the sections of the
# service schema.
for section_name, section_schema in service_schema.get("fields", {}).items():
if "fields" not in section_schema:
# This is not a section
continue
try:
strings["services"][service_name]["sections"][section_name]["name"]
except KeyError:
integration.add_error(
"services",
f"Service {service_name} has a section {section_name} with no name {error_msg_suffix}",
)
def validate(integrations: dict[str, Integration], config: Config) -> None:
"""Handle dependencies for integrations."""
# check services.yaml is cool
for integration in integrations.values():
validate_services(config, integration)

View File

@@ -0,0 +1,47 @@
"""Generate ssdp file."""
from __future__ import annotations
from collections import defaultdict
from .model import Config, Integration
from .serializer import format_python_namespace
def generate_and_validate(integrations: dict[str, Integration]) -> str:
"""Validate and generate ssdp data."""
data = defaultdict(list)
for domain in sorted(integrations):
ssdp = integrations[domain].manifest.get("ssdp")
if not ssdp:
continue
for matcher in ssdp:
data[domain].append(matcher)
return format_python_namespace({"SSDP": data})
def validate(integrations: dict[str, Integration], config: Config) -> None:
"""Validate ssdp file."""
ssdp_path = config.root / "homeassistant/generated/ssdp.py"
config.cache["ssdp"] = content = generate_and_validate(integrations)
if config.specific_integrations:
return
if ssdp_path.read_text() != content:
config.add_error(
"ssdp",
"File ssdp.py is not up to date. Run python3 -m script.hassfest",
fixable=True,
)
def generate(integrations: dict[str, Integration], config: Config) -> None:
"""Generate ssdp file."""
ssdp_path = config.root / "homeassistant/generated/ssdp.py"
ssdp_path.write_text(f"{config.cache['ssdp']}")

View File

@@ -0,0 +1,552 @@
"""Validate integration translation files."""
from __future__ import annotations
from functools import partial
import json
import re
from typing import Any
import voluptuous as vol
from voluptuous.humanize import humanize_error
import homeassistant.helpers.config_validation as cv
from script.translations import upload
from .model import Config, Integration
UNDEFINED = 0
REQUIRED = 1
REMOVED = 2
RE_REFERENCE = r"\[\%key:(.+)\%\]"
RE_TRANSLATION_KEY = re.compile(r"^(?!.+[_-]{2})(?![_-])[a-z0-9-_]+(?<![_-])$")
RE_COMBINED_REFERENCE = re.compile(r"(.+\[%)|(%\].+)")
RE_PLACEHOLDER_IN_SINGLE_QUOTES = re.compile(r"'{\w+}'")
# Only allow translation of integration names if they contain non-brand names
ALLOW_NAME_TRANSLATION = {
"cert_expiry",
"cpuspeed",
"emulated_roku",
"faa_delays",
"garages_amsterdam",
"generic",
"google_travel_time",
"holiday",
"homekit_controller",
"islamic_prayer_times",
"local_calendar",
"local_ip",
"local_todo",
"nmap_tracker",
"rpi_power",
"swiss_public_transport",
"waze_travel_time",
"zodiac",
}
REMOVED_TITLE_MSG = (
"config.title key has been moved out of config and into the root of strings.json. "
"Starting Home Assistant 0.109 you only need to define this key in the root "
"if the title needs to be different than the name of your integration in the "
"manifest."
)
MOVED_TRANSLATIONS_DIRECTORY_MSG = (
"The '.translations' directory has been moved, the new name is 'translations', "
"starting with Home Assistant 0.112 your translations will no longer "
"load if you do not move/rename this "
)
def allow_name_translation(integration: Integration) -> bool:
"""Validate that the translation name is not the same as the integration name."""
# Only enforce for core because custom integrations can't be
# added to allow list.
return (
not integration.core
or integration.domain in ALLOW_NAME_TRANSLATION
or integration.quality_scale == "internal"
)
def check_translations_directory_name(integration: Integration) -> None:
"""Check that the correct name is used for the translations directory."""
legacy_translations = integration.path / ".translations"
translations = integration.path / "translations"
if translations.is_dir():
# No action required
return
if legacy_translations.is_dir():
integration.add_error("translations", MOVED_TRANSLATIONS_DIRECTORY_MSG)
def find_references(
strings: dict[str, Any],
prefix: str,
found: list[dict[str, str]],
) -> None:
"""Find references."""
for key, value in strings.items():
if isinstance(value, dict):
find_references(value, f"{prefix}::{key}", found)
continue
if match := re.match(RE_REFERENCE, value):
found.append({"source": f"{prefix}::{key}", "ref": match.groups()[0]})
def removed_title_validator(
config: Config,
integration: Integration,
value: Any,
) -> Any:
"""Mark removed title."""
if not config.specific_integrations:
raise vol.Invalid(REMOVED_TITLE_MSG)
# Don't mark it as an error yet for custom components to allow backwards compat.
integration.add_warning("translations", REMOVED_TITLE_MSG)
return value
def translation_key_validator(value: str) -> str:
"""Validate value is valid translation key."""
if RE_TRANSLATION_KEY.match(value) is None:
raise vol.Invalid(
f"Invalid translation key '{value}', need to be [a-z0-9-_]+ and"
" cannot start or end with a hyphen or underscore."
)
return value
def translation_value_validator(value: Any) -> str:
"""Validate that the value is a valid translation.
- prevents string with HTML
- prevents strings with single quoted placeholders
- prevents combined translations
"""
string_value = cv.string_with_no_html(value)
string_value = string_no_single_quoted_placeholders(string_value)
if RE_COMBINED_REFERENCE.search(string_value):
raise vol.Invalid("the string should not contain combined translations")
if string_value != string_value.strip():
raise vol.Invalid("the string should not contain leading or trailing spaces")
return string_value
def string_no_single_quoted_placeholders(value: str) -> str:
"""Validate that the value does not contain placeholders inside single quotes."""
if RE_PLACEHOLDER_IN_SINGLE_QUOTES.search(value):
raise vol.Invalid(
"the string should not contain placeholders inside single quotes"
)
return value
def gen_data_entry_schema(
*,
config: Config,
integration: Integration,
flow_title: int,
require_step_title: bool,
mandatory_description: str | None = None,
) -> vol.All:
"""Generate a data entry schema."""
step_title_class = vol.Required if require_step_title else vol.Optional
schema = {
vol.Optional("flow_title"): translation_value_validator,
vol.Required("step"): {
str: {
step_title_class("title"): translation_value_validator,
vol.Optional("description"): translation_value_validator,
vol.Optional("data"): {str: translation_value_validator},
vol.Optional("data_description"): {str: translation_value_validator},
vol.Optional("menu_options"): {str: translation_value_validator},
vol.Optional("submit"): translation_value_validator,
vol.Optional("sections"): {
str: {
vol.Optional("data"): {str: translation_value_validator},
vol.Optional("data_description"): {
str: translation_value_validator
},
vol.Optional("description"): translation_value_validator,
vol.Optional("name"): translation_value_validator,
},
},
}
},
vol.Optional("error"): {str: translation_value_validator},
vol.Optional("abort"): {str: translation_value_validator},
vol.Optional("progress"): {str: translation_value_validator},
vol.Optional("create_entry"): {str: translation_value_validator},
}
if flow_title == REQUIRED:
schema[vol.Required("title")] = translation_value_validator
elif flow_title == REMOVED:
schema[vol.Optional("title", msg=REMOVED_TITLE_MSG)] = partial(
removed_title_validator, config, integration
)
def data_description_validator(value: dict[str, Any]) -> dict[str, Any]:
"""Validate data description."""
for step_info in value["step"].values():
if "data_description" not in step_info:
continue
for key in step_info["data_description"]:
if key not in step_info["data"]:
raise vol.Invalid(f"data_description key {key} is not in data")
return value
validators = [vol.Schema(schema), data_description_validator]
if mandatory_description is not None:
def validate_description_set(value: dict[str, Any]) -> dict[str, Any]:
"""Validate description is set."""
steps = value["step"]
if mandatory_description not in steps:
raise vol.Invalid(f"{mandatory_description} needs to be defined")
if "description" not in steps[mandatory_description]:
raise vol.Invalid(f"Step {mandatory_description} needs a description")
return value
validators.append(validate_description_set)
if not allow_name_translation(integration):
def name_validator(value: dict[str, Any]) -> dict[str, Any]:
"""Validate name."""
for step_id, info in value["step"].items():
if info.get("title") == integration.name:
raise vol.Invalid(
f"Do not set title of step {step_id} if it's a brand name "
"or add exception to ALLOW_NAME_TRANSLATION"
)
return value
validators.append(name_validator)
return vol.All(*validators)
def gen_issues_schema(config: Config, integration: Integration) -> dict[str, Any]:
"""Generate the issues schema."""
return {
str: vol.All(
cv.has_at_least_one_key("description", "fix_flow"),
vol.Schema(
{
vol.Required("title"): translation_value_validator,
vol.Exclusive(
"description", "fixable"
): translation_value_validator,
vol.Exclusive("fix_flow", "fixable"): gen_data_entry_schema(
config=config,
integration=integration,
flow_title=UNDEFINED,
require_step_title=False,
),
},
),
)
}
_EXCEPTIONS_SCHEMA = {
vol.Optional("exceptions"): cv.schema_with_slug_keys(
{vol.Optional("message"): translation_value_validator},
slug_validator=cv.slug,
),
}
def gen_strings_schema(config: Config, integration: Integration) -> vol.Schema:
"""Generate a strings schema."""
return vol.Schema(
{
vol.Optional("title"): translation_value_validator,
vol.Optional("config"): gen_data_entry_schema(
config=config,
integration=integration,
flow_title=REMOVED,
require_step_title=False,
mandatory_description=(
"user" if integration.integration_type == "helper" else None
),
),
vol.Optional("options"): gen_data_entry_schema(
config=config,
integration=integration,
flow_title=UNDEFINED,
require_step_title=False,
),
vol.Optional("selector"): cv.schema_with_slug_keys(
{
"options": cv.schema_with_slug_keys(
translation_value_validator,
slug_validator=translation_key_validator,
)
},
slug_validator=vol.Any("_", cv.slug),
),
vol.Optional("device_automation"): {
vol.Optional("action_type"): {str: translation_value_validator},
vol.Optional("condition_type"): {str: translation_value_validator},
vol.Optional("trigger_type"): {str: translation_value_validator},
vol.Optional("trigger_subtype"): {str: translation_value_validator},
vol.Optional("extra_fields"): {str: translation_value_validator},
vol.Optional("extra_fields_descriptions"): {
str: translation_value_validator
},
},
vol.Optional("system_health"): {
vol.Optional("info"): cv.schema_with_slug_keys(
translation_value_validator,
slug_validator=translation_key_validator,
),
},
vol.Optional("config_panel"): cv.schema_with_slug_keys(
cv.schema_with_slug_keys(
translation_value_validator,
slug_validator=translation_key_validator,
),
slug_validator=vol.Any("_", cv.slug),
),
vol.Optional("application_credentials"): {
vol.Optional("description"): translation_value_validator,
},
vol.Optional("issues"): gen_issues_schema(config, integration),
vol.Optional("entity_component"): cv.schema_with_slug_keys(
{
vol.Optional("name"): str,
vol.Optional("state"): cv.schema_with_slug_keys(
translation_value_validator,
slug_validator=translation_key_validator,
),
vol.Optional("state_attributes"): cv.schema_with_slug_keys(
{
vol.Optional("name"): str,
vol.Optional("state"): cv.schema_with_slug_keys(
translation_value_validator,
slug_validator=translation_key_validator,
),
},
slug_validator=translation_key_validator,
),
},
slug_validator=vol.Any("_", cv.slug),
),
vol.Optional("device"): cv.schema_with_slug_keys(
{
vol.Optional("name"): translation_value_validator,
},
slug_validator=translation_key_validator,
),
vol.Optional("entity"): cv.schema_with_slug_keys(
cv.schema_with_slug_keys(
{
vol.Optional("name"): translation_value_validator,
vol.Optional("state"): cv.schema_with_slug_keys(
translation_value_validator,
slug_validator=translation_key_validator,
),
vol.Optional("state_attributes"): cv.schema_with_slug_keys(
{
vol.Optional("name"): translation_value_validator,
vol.Optional("state"): cv.schema_with_slug_keys(
translation_value_validator,
slug_validator=translation_key_validator,
),
},
slug_validator=translation_key_validator,
),
vol.Optional(
"unit_of_measurement"
): translation_value_validator,
},
slug_validator=translation_key_validator,
),
slug_validator=cv.slug,
),
**_EXCEPTIONS_SCHEMA,
vol.Optional("services"): cv.schema_with_slug_keys(
{
vol.Required("name"): translation_value_validator,
vol.Required("description"): translation_value_validator,
vol.Optional("fields"): cv.schema_with_slug_keys(
{
vol.Required("name"): str,
vol.Required("description"): translation_value_validator,
vol.Optional("example"): translation_value_validator,
},
slug_validator=translation_key_validator,
),
vol.Optional("sections"): cv.schema_with_slug_keys(
{
vol.Required("name"): str,
vol.Optional("description"): translation_value_validator,
},
slug_validator=translation_key_validator,
),
},
slug_validator=translation_key_validator,
),
vol.Optional("conversation"): {
vol.Required("agent"): {
vol.Required("done"): translation_value_validator,
},
},
vol.Optional("common"): vol.Schema({cv.slug: translation_value_validator}),
}
)
def gen_auth_schema(config: Config, integration: Integration) -> vol.Schema:
"""Generate auth schema."""
return vol.Schema(
{
vol.Optional("mfa_setup"): {
str: gen_data_entry_schema(
config=config,
integration=integration,
flow_title=REQUIRED,
require_step_title=True,
)
},
vol.Optional("issues"): gen_issues_schema(config, integration),
**_EXCEPTIONS_SCHEMA,
}
)
def gen_ha_hardware_schema(config: Config, integration: Integration):
"""Generate auth schema."""
return vol.Schema(
{
str: {
vol.Optional("options"): gen_data_entry_schema(
config=config,
integration=integration,
flow_title=UNDEFINED,
require_step_title=False,
)
}
}
)
ONBOARDING_SCHEMA = vol.Schema(
{
vol.Required("area"): {str: translation_value_validator},
vol.Required("dashboard"): {str: {"title": translation_value_validator}},
}
)
def validate_translation_file( # noqa: C901
config: Config,
integration: Integration,
all_strings: dict[str, Any] | None,
) -> None:
"""Validate translation files for integration."""
if config.specific_integrations:
check_translations_directory_name(integration)
strings_files = [integration.path / "strings.json"]
# Also validate translations for custom integrations
if config.specific_integrations:
# Only English needs to be always complete
strings_files.append(integration.path / "translations/en.json")
references: list[dict[str, str]] = []
if integration.domain == "auth":
strings_schema = gen_auth_schema(config, integration)
elif integration.domain == "onboarding":
strings_schema = ONBOARDING_SCHEMA
elif integration.domain == "homeassistant_hardware":
strings_schema = gen_ha_hardware_schema(config, integration)
else:
strings_schema = gen_strings_schema(config, integration)
for strings_file in strings_files:
if not strings_file.is_file():
continue
name = str(strings_file.relative_to(integration.path))
try:
strings = json.loads(strings_file.read_text())
except ValueError as err:
integration.add_error("translations", f"Invalid JSON in {name}: {err}")
continue
try:
strings_schema(strings)
except vol.Invalid as err:
integration.add_error(
"translations", f"Invalid {name}: {humanize_error(strings, err)}"
)
else:
if strings_file.name == "strings.json":
find_references(strings, name, references)
if (title := strings.get("title")) is not None:
integration.translated_name = True
if title == integration.name and not allow_name_translation(
integration
):
integration.add_error(
"translations",
"Don't specify title in translation strings if it's a brand "
"name or add exception to ALLOW_NAME_TRANSLATION",
)
if config.specific_integrations:
return
if not all_strings: # Nothing to validate against
return
# Validate references
for reference in references:
parts = reference["ref"].split("::")
search = all_strings
key = parts.pop(0)
while parts and key in search:
search = search[key]
key = parts.pop(0)
if parts or key not in search:
integration.add_error(
"translations",
f"{reference['source']} contains invalid reference {reference['ref']}: Could not find {key}",
)
elif match := re.match(RE_REFERENCE, search[key]):
integration.add_error(
"translations",
f"Lokalise supports only one level of references: \"{reference['source']}\" should point to directly to \"{match.groups()[0]}\"",
)
def validate(integrations: dict[str, Integration], config: Config) -> None:
"""Handle JSON files inside integrations."""
if config.specific_integrations:
all_strings = None
else:
all_strings = upload.generate_upload_data() # type: ignore[no-untyped-call]
for integration in integrations.values():
validate_translation_file(config, integration, all_strings)

View File

@@ -0,0 +1,49 @@
"""Generate usb file."""
from __future__ import annotations
from .model import Config, Integration
from .serializer import format_python_namespace
def generate_and_validate(integrations: dict[str, Integration]) -> str:
"""Validate and generate usb data."""
match_list = []
for domain in sorted(integrations):
match_types = integrations[domain].manifest.get("usb", [])
if not match_types:
continue
match_list.extend(
{
"domain": domain,
**{k: v for k, v in entry.items() if k != "known_devices"},
}
for entry in match_types
)
return format_python_namespace({"USB": match_list})
def validate(integrations: dict[str, Integration], config: Config) -> None:
"""Validate usb file."""
usb_path = config.root / "homeassistant/generated/usb.py"
config.cache["usb"] = content = generate_and_validate(integrations)
if config.specific_integrations:
return
if usb_path.read_text() != content:
config.add_error(
"usb",
"File usb.py is not up to date. Run python3 -m script.hassfest",
fixable=True,
)
def generate(integrations: dict[str, Integration], config: Config) -> None:
"""Generate usb file."""
usb_path = config.root / "homeassistant/generated/usb.py"
usb_path.write_text(f"{config.cache['usb']}")

View File

@@ -0,0 +1,104 @@
"""Generate zeroconf file."""
from __future__ import annotations
from collections import defaultdict
from homeassistant.loader import (
async_process_zeroconf_match_dict,
homekit_always_discover,
)
from .model import Config, Integration
from .serializer import format_python_namespace
def generate_and_validate(integrations: dict[str, Integration]) -> str:
"""Validate and generate zeroconf data."""
service_type_dict = defaultdict(list)
homekit_dict: dict[str, dict[str, str]] = {}
for domain in sorted(integrations):
integration = integrations[domain]
service_types = integration.manifest.get("zeroconf", [])
homekit = integration.manifest.get("homekit", {})
homekit_models = homekit.get("models", [])
if not (service_types or homekit_models):
continue
for entry in service_types:
data = {"domain": domain}
if isinstance(entry, dict):
typ = entry["type"]
data.update(async_process_zeroconf_match_dict(entry))
else:
typ = entry
service_type_dict[typ].append(data)
for model in homekit_models:
if model in homekit_dict:
integration.add_error(
"zeroconf",
f"Integrations {domain} and {homekit_dict[model]} "
"have overlapping HomeKit models",
)
break
homekit_dict[model] = {
"domain": domain,
"always_discover": homekit_always_discover(
integration.manifest["iot_class"]
),
}
# HomeKit models are matched on starting string, make sure none overlap.
warned = set()
for key, value in homekit_dict.items():
if key in warned:
continue
# n^2 yoooo
for key_2, value_2 in homekit_dict.items():
if key == key_2 or key_2 in warned:
continue
if key.startswith(key_2) or key_2.startswith(key):
integration.add_error(
"zeroconf",
f"Integrations {value} and {value_2} "
"have overlapping HomeKit models",
)
warned.add(key)
warned.add(key_2)
break
return format_python_namespace(
{
"HOMEKIT": {key: homekit_dict[key] for key in homekit_dict},
"ZEROCONF": {key: service_type_dict[key] for key in service_type_dict},
}
)
def validate(integrations: dict[str, Integration], config: Config) -> None:
"""Validate zeroconf file."""
zeroconf_path = config.root / "homeassistant/generated/zeroconf.py"
config.cache["zeroconf"] = content = generate_and_validate(integrations)
if config.specific_integrations:
return
if zeroconf_path.read_text() != content:
config.add_error(
"zeroconf",
"File zeroconf.py is not up to date. Run python3 -m script.hassfest",
fixable=True,
)
def generate(integrations: dict[str, Integration], config: Config) -> None:
"""Generate zeroconf file."""
zeroconf_path = config.root / "homeassistant/generated/zeroconf.py"
zeroconf_path.write_text(f"{config.cache['zeroconf']}")

View File

@@ -0,0 +1,66 @@
#!/usr/bin/env python3
"""Inspect all component SCHEMAS."""
import importlib
from pathlib import Path
import pkgutil
from homeassistant.config import _identify_config_schema
from homeassistant.scripts.check_config import color
def explore_module(package):
"""Explore the modules."""
module = importlib.import_module(package)
if not hasattr(module, "__path__"):
return []
for _, name, _ in pkgutil.iter_modules(module.__path__, f"{package}."):
yield name
def main():
"""Run the script."""
if not Path("requirements_all.txt").is_file():
print("Run this from HA root dir")
return
msg = {}
def add_msg(key, item):
"""Add a message."""
if key not in msg:
msg[key] = []
msg[key].append(item)
for package in explore_module("homeassistant.components"):
module = importlib.import_module(package)
module_name = getattr(module, "DOMAIN", module.__name__)
if hasattr(module, "PLATFORM_SCHEMA"):
if hasattr(module, "CONFIG_SCHEMA"):
add_msg(
"WARNING",
f"Module {module_name} contains PLATFORM and CONFIG schemas",
)
add_msg("PLATFORM SCHEMA", module_name)
continue
if not hasattr(module, "CONFIG_SCHEMA"):
add_msg("NO SCHEMA", module_name)
continue
schema_type, schema = _identify_config_schema(module)
add_msg(
f"CONFIG_SCHEMA {schema_type}",
f"{module_name} {color('cyan', str(schema)[:60])}",
)
for key in sorted(msg):
print(f"\n{key}")
for val in msg[key]:
print(f" - {val}")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,52 @@
"""Install requirements for a given integration."""
import argparse
from pathlib import Path
import subprocess
import sys
from .gen_requirements_all import gather_recursive_requirements
from .util import valid_integration
def get_arguments() -> argparse.Namespace:
"""Get parsed passed in arguments."""
parser = argparse.ArgumentParser(
description="Install requirements for a given integration"
)
parser.add_argument(
"integration", type=valid_integration, help="Integration to target."
)
return parser.parse_args()
def main() -> int | None:
"""Install requirements for a given integration."""
if not Path("requirements_all.txt").is_file():
print("Run from project root")
return 1
args = get_arguments()
requirements = gather_recursive_requirements(args.integration)
cmd = [
"uv",
"pip",
"install",
"-c",
"homeassistant/package_constraints.txt",
"-U",
*requirements,
]
print(" ".join(cmd))
subprocess.run(
cmd,
check=True,
)
return None
if __name__ == "__main__":
sys.exit(main())

View File

@@ -0,0 +1,391 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Home Assistant integration manifest",
"description": "The manifest for a Home Assistant integration",
"type": "object",
"if": {
"properties": { "integration_type": { "const": "virtual" } },
"required": ["integration_type"]
},
"then": {
"oneOf": [
{
"properties": {
"domain": {
"description": "The domain identifier of the integration.\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#domain",
"examples": ["mobile_app"],
"type": "string",
"pattern": "[0-9a-z_]+"
},
"name": {
"description": "The friendly name of the integration.",
"type": "string"
},
"integration_type": {
"description": "The integration type.\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#integration-type",
"const": "virtual"
},
"iot_standards": {
"description": "The IoT standards which supports devices or services of this virtual integration.\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#iot-standards",
"type": "array",
"minItems": 1,
"items": {
"type": "string",
"enum": ["homekit", "zigbee", "zwave"]
}
}
},
"additionalProperties": false,
"required": ["domain", "name", "integration_type", "iot_standards"]
},
{
"properties": {
"domain": {
"description": "The domain identifier of the integration.\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#domain",
"examples": ["mobile_app"],
"type": "string",
"pattern": "[0-9a-z_]+"
},
"name": {
"description": "The friendly name of the integration.",
"type": "string"
},
"integration_type": {
"description": "The integration type.\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#integration-type",
"const": "virtual"
},
"supported_by": {
"description": "The integration which supports devices or services of this virtual integration.\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#supported-by",
"type": "string"
}
},
"additionalProperties": false,
"required": ["domain", "name", "integration_type", "supported_by"]
}
]
},
"else": {
"properties": {
"domain": {
"description": "The domain identifier of the integration.\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#domain",
"examples": ["mobile_app"],
"type": "string",
"pattern": "[0-9a-z_]+"
},
"name": {
"description": "The friendly name of the integration.",
"type": "string"
},
"integration_type": {
"description": "The integration type.\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#integration-type",
"type": "string",
"default": "hub",
"enum": [
"device",
"entity",
"hardware",
"helper",
"hub",
"service",
"system"
]
},
"config_flow": {
"description": "Whether the integration is configurable from the UI.\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#config-flow",
"type": "boolean"
},
"mqtt": {
"description": "A list of topics to subscribe for the discovery of devices via MQTT.\nThis requires to specify \"mqtt\" in either the \"dependencies\" or \"after_dependencies\".\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#mqtt",
"type": "array",
"items": {
"type": "string"
},
"uniqueItems": true
},
"zeroconf": {
"description": "A list containing service domains to search for devices to discover via Zeroconf. Items can either be strings, which discovers all devices in the specific service domain, and/or objects which include filters. (useful for generic service domains like _http._tcp.local.)\nA device is discovered if it matches one of the items, but inside the individual item all properties have to be matched.\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#zeroconf",
"type": "array",
"minItems": 1,
"items": {
"anyOf": [
{
"type": "string",
"pattern": "^.*\\.local\\.$",
"description": "Service domain to search for devices."
},
{
"type": "object",
"properties": {
"type": {
"description": "The service domain to search for devices.",
"examples": ["_http._tcp.local."],
"type": "string",
"pattern": "^.*\\.local\\.$"
},
"name": {
"description": "The name or name pattern of the devices to filter.",
"type": "string"
},
"properties": {
"description": "The properties of the Zeroconf advertisement to filter.",
"type": "object",
"additionalProperties": { "type": "string" }
}
},
"required": ["type"],
"additionalProperties": false
}
]
},
"uniqueItems": true
},
"ssdp": {
"description": "A list of matchers to find devices discoverable via SSDP/UPnP. In order to be discovered, the device has to match all properties of any of the matchers.\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#ssdp",
"type": "array",
"minItems": 1,
"items": {
"description": "A matcher for the SSDP discovery.",
"type": "object",
"properties": {
"st": {
"type": "string"
},
"deviceType": {
"type": "string"
},
"manufacturer": {
"type": "string"
},
"modelDescription": {
"type": "string"
}
},
"additionalProperties": { "type": "string" }
}
},
"bluetooth": {
"description": "A list of matchers to find devices discoverable via Bluetooth. In order to be discovered, the device has to match all properties of any of the matchers.\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#bluetooth",
"type": "array",
"minItems": 1,
"items": {
"description": "A matcher for the bluetooth discovery",
"type": "object",
"properties": {
"connectable": {
"description": "Whether the device needs to be connected to or it works with just advertisement data.",
"type": "boolean"
},
"local_name": {
"description": "The name or a name pattern of the device to match.",
"type": "string",
"pattern": "^([^*]+|[^*]{3,}[*].*)$"
},
"service_uuid": {
"description": "The 128-bit service data UUID to match.",
"type": "string",
"pattern": "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
},
"service_data_uuid": {
"description": "The 16-bit service data UUID to match, converted into the corresponding 128-bit UUID by replacing the 3rd and 4th byte of `00000000-0000-1000-8000-00805f9b34fb` with the 16-bit UUID.",
"examples": ["0000fd3d-0000-1000-8000-00805f9b34fb"],
"type": "string",
"pattern": "0000[0-9a-f]{4}-0000-1000-8000-00805f9b34fb"
},
"manufacturer_id": {
"description": "The Manufacturer ID to match.",
"type": "integer"
},
"manufacturer_data_start": {
"description": "The start bytes of the manufacturer data to match.",
"type": "array",
"minItems": 1,
"items": {
"type": "integer",
"minimum": 0,
"maximum": 255
}
}
},
"additionalProperties": false
},
"uniqueItems": true
},
"homekit": {
"description": "A list of model names to find devices which are discoverable via HomeKit. A device is discovered if the model name of the device starts with any of the specified model names.\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#homekit",
"type": "object",
"properties": {
"models": {
"description": "The model names to search for.",
"type": "array",
"items": {
"type": "string"
},
"uniqueItems": true
}
},
"required": ["models"],
"additionalProperties": false
},
"dhcp": {
"description": "A list of matchers to find devices discoverable via DHCP. In order to be discovered, the device has to match all properties of any of the matchers.\nYou can specify an item with \"registered_devices\" set to true to check for devices with MAC addresses specified in the device registry.\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#dhcp",
"type": "array",
"items": {
"anyOf": [
{
"type": "object",
"properties": {
"registered_devices": {
"description": "Whether the MAC addresses of devices in the device registry should be used for discovery, useful if the discovery is used to update the IP address of already registered devices.",
"const": true
}
},
"additionalProperties": false
},
{
"type": "object",
"properties": {
"hostname": {
"description": "The hostname or hostname pattern to match.",
"type": "string"
},
"macaddress": {
"description": "The MAC address or MAC address pattern to match.",
"type": "string",
"maxLength": 12
}
},
"additionalProperties": false
}
]
},
"uniqueItems": true
},
"usb": {
"description": "A list of matchers to find devices discoverable via USB. In order to be discovered, the device has to match all properties of any of the matchers.\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#usb",
"type": "array",
"uniqueItems": true,
"items": {
"type": "object",
"additionalProperties": false,
"properties": {
"vid": {
"description": "The vendor ID to match.",
"type": "string",
"pattern": "[0-9A-F]{4}"
},
"pid": {
"description": "The product ID to match.",
"type": "string",
"pattern": "[0-9A-F]{4}"
},
"description": {
"description": "The USB device description to match.",
"type": "string"
},
"manufacturer": {
"description": "The manufacturer to match.",
"type": "string"
},
"serial_number": {
"description": "The serial number to match.",
"type": "string"
},
"known_devices": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
},
"documentation": {
"description": "The website containing the documentation for the integration. It has to be in the format \"https://www.home-assistant.io/integrations/[domain]\"\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#documentation",
"type": "string",
"pattern": "^https://www.home-assistant.io/integrations/[0-9a-z_]+$",
"format": "uri"
},
"quality_scale": {
"description": "The quality scale of the integration.\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#integration-quality-scale",
"type": "string",
"enum": ["bronze", "silver", "gold", "platinum", "internal", "legacy"]
},
"requirements": {
"description": "The PyPI package requirements for the integration. The package has to be pinned to a specific version.\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#requirements",
"type": "array",
"items": {
"type": "string",
"pattern": ".+==.+"
},
"uniqueItems": true
},
"dependencies": {
"description": "A list of integrations which need to be loaded before this integration can be set up.\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#dependencies",
"type": "array",
"items": {
"type": "string"
},
"minItems": 1,
"uniqueItems": true
},
"after_dependencies": {
"description": "A list of integrations which need to be loaded before this integration is set up when it is configured. The integration will still be set up when the \"after_dependencies\" are not configured.\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#after-dependencies",
"type": "array",
"items": {
"type": "string"
},
"minItems": 1,
"uniqueItems": true
},
"codeowners": {
"description": "A list of GitHub usernames or GitHub team names of the integration owners.\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#code-owners",
"type": "array",
"minItems": 0,
"items": {
"type": "string",
"pattern": "^@.+$"
},
"uniqueItems": true
},
"loggers": {
"description": "A list of logger names used by the requirements.\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#loggers",
"type": "array",
"minItems": 1,
"items": {
"type": "string"
},
"uniqueItems": true
},
"disabled": {
"description": "The reason for the integration being disabled.",
"type": "string"
},
"iot_class": {
"description": "The IoT class of the integration, describing how the integration connects to the device or service.\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#iot-class",
"type": "string",
"enum": [
"assumed_state",
"cloud_polling",
"cloud_push",
"local_polling",
"local_push",
"calculated"
]
},
"single_config_entry": {
"description": "Whether the integration only supports a single config entry.\nhttps://developers.home-assistant.io/docs/creating_integration_manifest/#single-config-entry-only",
"const": true
}
},
"additionalProperties": false,
"required": ["domain", "name", "codeowners", "documentation"],
"dependencies": {
"mqtt": {
"anyOf": [
{ "required": ["dependencies"] },
{ "required": ["after_dependencies"] }
]
}
}
}
}

View File

@@ -0,0 +1,77 @@
"""Helper script to update language list from the frontend source."""
import json
from pathlib import Path
import sys
import requests
from .hassfest.serializer import format_python_namespace
tag = sys.argv[1] if len(sys.argv) > 1 else "dev"
req = requests.get(
f"https://raw.githubusercontent.com/home-assistant/frontend/{tag}/src/translations/translationMetadata.json"
)
data = json.loads(req.content)
languages = set(data.keys())
# Languages which can be used for entity IDs.
# Languages in the set are those which use a writing system based on the Latin
# script. Languages not in this set will instead base the entity ID on English.
# Note: Although vietnamese writing is based on the Latin script, it's too ambiguous
# after accents and diacritics have been removed by slugify
NATIVE_ENTITY_IDS = {
"af", # Afrikaans
"bs", # Bosanski
"ca", # Català
"cs", # Čeština
"cy", # Cymraeg
"da", # Dansk
"de", # Deutsch
"en", # English
"en-GB", # English (GB)
"eo", # Esperanto
"es", # Español
"es-419", # Español (Latin America)
"et", # Eesti
"eu", # Euskara
"fi", # Suomi
"fr", # Français
"fy", # Frysk
"gl", # Galego
"gsw", # Schwiizerdütsch
"hr", # Hrvatski
"hu", # Magyar
"id", # Indonesia
"is", # Íslenska
"it", # Italiano
"ka", # Kartuli
"lb", # Lëtzebuergesch
"lt", # Lietuvių
"lv", # Latviešu
"nb", # Nederlands
"nl", # Norsk Bokmål
"nn", # Norsk Nynorsk"
"pl", # Polski
"pt", # Português
"pt-BR", # Português (BR)
"ro", # Română
"sk", # Slovenčina
"sl", # Slovenščina
"sr-Latn", # Srpski
"sv", # Svenska
"tr", # Türkçe
}
Path("homeassistant/generated/languages.py").write_text(
format_python_namespace(
{
"DEFAULT_LANGUAGE": "en",
"LANGUAGES": languages,
"NATIVE_ENTITY_IDS": NATIVE_ENTITY_IDS,
},
generator="script.languages [frontend_tag]",
)
)

View File

@@ -0,0 +1,413 @@
"""Tool to check the licenses."""
from __future__ import annotations
from argparse import ArgumentParser, Namespace
from collections.abc import Sequence
from dataclasses import dataclass
from importlib import metadata
import json
from pathlib import Path
import sys
from typing import TypedDict, cast
from awesomeversion import AwesomeVersion
from license_expression import (
AND,
OR,
ExpressionError,
LicenseExpression,
LicenseSymbol,
get_spdx_licensing,
)
licensing = get_spdx_licensing()
class PackageMetadata(TypedDict):
"""Package metadata."""
name: str
version: str
license_expression: str | None
license_metadata: str | None
license_classifier: list[str]
@dataclass
class PackageDefinition:
"""Package definition."""
license: str
license_expression: str | None
license_metadata: str | None
license_classifier: list[str]
name: str
version: AwesomeVersion
@classmethod
def from_dict(cls, data: PackageMetadata) -> PackageDefinition:
"""Create a package definition from PackageMetadata."""
if not (license_str := "; ".join(data["license_classifier"])):
license_str = data["license_metadata"] or "UNKNOWN"
return cls(
license=license_str,
license_expression=data["license_expression"],
license_metadata=data["license_metadata"],
license_classifier=data["license_classifier"],
name=data["name"],
version=AwesomeVersion(data["version"]),
)
# Incomplete list of OSI approved SPDX identifiers
# Add more as needed, see https://spdx.org/licenses/
OSI_APPROVED_LICENSES_SPDX = {
"0BSD",
"AFL-2.1",
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"Apache-2.0",
"BSD-1-Clause",
"BSD-2-Clause",
"BSD-3-Clause",
"EPL-1.0",
"EPL-2.0",
"GPL-2.0-only",
"GPL-2.0-or-later",
"GPL-3.0-only",
"GPL-3.0-or-later",
"HPND",
"ISC",
"LGPL-2.1-only",
"LGPL-2.1-or-later",
"LGPL-3.0-only",
"LGPL-3.0-or-later",
"MIT",
"MIT-CMU",
"MPL-1.1",
"MPL-2.0",
"PSF-2.0",
"Unlicense",
"Zlib",
"ZPL-2.1",
}
OSI_APPROVED_LICENSES = {
"Academic Free License (AFL)",
"Apache Software License",
"Apple Public Source License",
"Artistic License",
"Attribution Assurance License",
"BSD License",
"Boost Software License 1.0 (BSL-1.0)",
"CEA CNRS Inria Logiciel Libre License, version 2.1 (CeCILL-2.1)",
"Common Development and Distribution License 1.0 (CDDL-1.0)",
"Common Public License",
"Eclipse Public License 1.0 (EPL-1.0)",
"Eclipse Public License 2.0 (EPL-2.0)",
"Educational Community License, Version 2.0 (ECL-2.0)",
"Eiffel Forum License",
"European Union Public Licence 1.0 (EUPL 1.0)",
"European Union Public Licence 1.1 (EUPL 1.1)",
"European Union Public Licence 1.2 (EUPL 1.2)",
"GNU Affero General Public License v3",
"GNU Affero General Public License v3 or later (AGPLv3+)",
"GNU Free Documentation License (FDL)",
"GNU General Public License (GPL)",
"GNU General Public License v2 (GPLv2)",
"GNU General Public License v2 or later (GPLv2+)",
"GNU General Public License v3 (GPLv3)",
"GNU General Public License v3 or later (GPLv3+)",
"GNU Lesser General Public License v2 (LGPLv2)",
"GNU Lesser General Public License v2 or later (LGPLv2+)",
"GNU Lesser General Public License v3 (LGPLv3)",
"GNU Lesser General Public License v3 or later (LGPLv3+)",
"GNU Library or Lesser General Public License (LGPL)",
"Historical Permission Notice and Disclaimer (HPND)",
"IBM Public License",
"ISC License (ISCL)",
"Intel Open Source License",
"Jabber Open Source License",
"MIT License",
"MIT No Attribution License (MIT-0)",
"MITRE Collaborative Virtual Workspace License (CVW)",
"MirOS License (MirOS)",
"Motosoto License",
"Mozilla Public License 1.0 (MPL)",
"Mozilla Public License 1.1 (MPL 1.1)",
"Mozilla Public License 2.0 (MPL 2.0)",
"Mulan Permissive Software License v2 (MulanPSL-2.0)",
"NASA Open Source Agreement v1.3 (NASA-1.3)",
"Nethack General Public License",
"Nokia Open Source License",
"Open Group Test Suite License",
"Open Software License 3.0 (OSL-3.0)",
"PostgreSQL License",
"Python License (CNRI Python License)",
"Python Software Foundation License",
"Qt Public License (QPL)",
"Ricoh Source Code Public License",
"SIL Open Font License 1.1 (OFL-1.1)",
"Sleepycat License",
"Sun Industry Standards Source License (SISSL)",
"Sun Public License",
"The Unlicense (Unlicense)",
"Universal Permissive License (UPL)",
"University of Illinois/NCSA Open Source License",
"Vovida Software License 1.0",
"W3C License",
"X.Net License",
"Zero-Clause BSD (0BSD)",
"Zope Public License",
"zlib/libpng License",
# End license classifier
"Apache License",
"MIT",
"MPL2",
"Apache 2",
"LGPL v3",
"BSD",
"GNU-3.0",
"GPLv3",
"Eclipse Public License v2.0",
"ISC",
"GNU General Public License v3",
"GPLv2",
}
EXCEPTIONS = {
"PyMicroBot", # https://github.com/spycle/pyMicroBot/pull/3
"PySwitchmate", # https://github.com/Danielhiversen/pySwitchmate/pull/16
"PyXiaomiGateway", # https://github.com/Danielhiversen/PyXiaomiGateway/pull/201
"aioecowitt", # https://github.com/home-assistant-libs/aioecowitt/pull/180
"chacha20poly1305", # LGPL
"commentjson", # https://github.com/vaidik/commentjson/pull/55
"crownstone-cloud", # https://github.com/crownstone/crownstone-lib-python-cloud/pull/5
"crownstone-core", # https://github.com/crownstone/crownstone-lib-python-core/pull/6
"crownstone-sse", # https://github.com/crownstone/crownstone-lib-python-sse/pull/2
"crownstone-uart", # https://github.com/crownstone/crownstone-lib-python-uart/pull/12
"eliqonline", # https://github.com/molobrakos/eliqonline/pull/17
"enocean", # https://github.com/kipe/enocean/pull/142
"imutils", # https://github.com/PyImageSearch/imutils/pull/292
"iso4217", # Public domain
"kiwiki_client", # https://github.com/c7h/kiwiki_client/pull/6
"ld2410-ble", # https://github.com/930913/ld2410-ble/pull/7
"maxcube-api", # https://github.com/uebelack/python-maxcube-api/pull/48
"neurio", # https://github.com/jordanh/neurio-python/pull/13
"nsw-fuel-api-client", # https://github.com/nickw444/nsw-fuel-api-client/pull/14
"pigpio", # https://github.com/joan2937/pigpio/pull/608
"pymitv", # MIT
"pybbox", # https://github.com/HydrelioxGitHub/pybbox/pull/5
"pyeconet", # https://github.com/w1ll1am23/pyeconet/pull/41
"pysabnzbd", # https://github.com/jeradM/pysabnzbd/pull/6
"pyvera", # https://github.com/maximvelichko/pyvera/pull/164
"repoze.lru",
"sharp_aquos_rc", # https://github.com/jmoore987/sharp_aquos_rc/pull/14
"tapsaff", # https://github.com/bazwilliams/python-taps-aff/pull/5
}
TODO = {
"aiocache": AwesomeVersion(
"0.12.3"
), # https://github.com/aio-libs/aiocache/blob/master/LICENSE all rights reserved?
}
EXCEPTIONS_AND_TODOS = EXCEPTIONS.union(TODO)
def check_licenses(args: CheckArgs) -> int:
"""Check licenses are OSI approved."""
exit_code = 0
raw_licenses = json.loads(Path(args.path).read_text())
license_status = {
pkg.name: (pkg, check_license_status(pkg))
for data in raw_licenses
if (pkg := PackageDefinition.from_dict(data))
}
for name, version in TODO.items():
pkg, status = license_status.get(name, (None, None))
if pkg is None or not (version < pkg.version):
continue
assert status is not None
if status is True:
print(
"Approved license detected for "
f"{pkg.name}@{pkg.version}: {get_license_str(pkg)}\n"
"Please remove the package from the TODO list.\n"
)
else:
print(
"We could not detect an OSI-approved license for "
f"{pkg.name}@{pkg.version}: {get_license_str(pkg)}\n"
"Please update the package version on the TODO list.\n"
)
exit_code = 1
for pkg, status in license_status.values():
if status is False and pkg.name not in EXCEPTIONS_AND_TODOS:
print(
"We could not detect an OSI-approved license for "
f"{pkg.name}@{pkg.version}: {get_license_str(pkg)}\n"
)
exit_code = 1
if status is True and pkg.name in EXCEPTIONS:
print(
"Approved license detected for "
f"{pkg.name}@{pkg.version}: {get_license_str(pkg)}\n"
"Please remove the package from the EXCEPTIONS list.\n"
)
exit_code = 1
for name in EXCEPTIONS_AND_TODOS.difference(license_status):
print(
f"Package {name} is tracked, but not used. "
"Please remove it from the licenses.py file.\n"
)
exit_code = 1
return exit_code
def check_license_status(package: PackageDefinition) -> bool:
"""Check if package licenses is OSI approved."""
if package.license_expression:
# Prefer 'License-Expression' if it exists
return check_license_expression(package.license_expression) or False
if (
package.license_metadata
and (check := check_license_expression(package.license_metadata)) is not None
):
# Check license metadata if it's a valid SPDX license expression
return check
for approved_license in OSI_APPROVED_LICENSES:
if approved_license in package.license:
return True
return False
def check_license_expression(license_str: str) -> bool | None:
"""Check if license expression is a valid and approved SPDX license string."""
if license_str == "UNKNOWN" or "\n" in license_str:
# Ignore common errors for license metadata values
return None
try:
expr = licensing.parse(license_str, validate=True)
except ExpressionError:
return None
return check_spdx_license(expr)
def check_spdx_license(expr: LicenseExpression) -> bool:
"""Check a SPDX license expression."""
if isinstance(expr, LicenseSymbol):
return expr.key in OSI_APPROVED_LICENSES_SPDX
if isinstance(expr, OR):
return any(check_spdx_license(arg) for arg in expr.args)
if isinstance(expr, AND):
return all(check_spdx_license(arg) for arg in expr.args)
return False
def get_license_str(package: PackageDefinition) -> str:
"""Return license string."""
return (
f"{package.license_expression} -- {package.license_metadata} "
f"-- {package.license_classifier}"
)
def extract_licenses(args: ExtractArgs) -> int:
"""Extract license data for installed packages."""
licenses = sorted(
[get_package_metadata(dist) for dist in list(metadata.distributions())],
key=lambda dist: dist["name"],
)
Path(args.output_file).write_text(json.dumps(licenses, indent=2))
return 0
def get_package_metadata(dist: metadata.Distribution) -> PackageMetadata:
"""Get package metadata for distribution."""
return {
"name": dist.name,
"version": dist.version,
"license_expression": dist.metadata.get("License-Expression"),
"license_metadata": dist.metadata.get("License"),
"license_classifier": extract_license_classifier(
dist.metadata.get_all("Classifier")
),
}
def extract_license_classifier(classifiers: list[str] | None) -> list[str]:
"""Extract license from list of classifiers.
E.g. 'License :: OSI Approved :: MIT License' -> 'MIT License'.
Filter out bare 'License :: OSI Approved'.
"""
return [
license_classifier
for classifier in classifiers or ()
if classifier.startswith("License")
and (license_classifier := classifier.rpartition(" :: ")[2])
and license_classifier != "OSI Approved"
]
class ExtractArgs(Namespace):
"""Extract arguments."""
output_file: str
class CheckArgs(Namespace):
"""Check arguments."""
path: str
def main(argv: Sequence[str] | None = None) -> int:
"""Run the main script."""
parser = ArgumentParser()
subparsers = parser.add_subparsers(title="Subcommands", required=True)
parser_extract = subparsers.add_parser("extract")
parser_extract.set_defaults(action="extract")
parser_extract.add_argument(
"--output-file",
default="licenses.json",
help="Path to store the licenses file",
)
parser_check = subparsers.add_parser("check")
parser_check.set_defaults(action="check")
parser_check.add_argument(
"path",
nargs="?",
metavar="PATH",
default="licenses.json",
help="Path to json licenses file",
)
argv = argv or sys.argv[1:]
args = parser.parse_args(argv)
if args.action == "extract":
args = cast(ExtractArgs, args)
return extract_licenses(args)
if args.action == "check":
args = cast(CheckArgs, args)
if (exit_code := check_licenses(args)) == 0:
print("All licenses are approved!")
return exit_code
return 0
if __name__ == "__main__":
sys.exit(main())

28
home-assistant/script/lint Executable file
View File

@@ -0,0 +1,28 @@
#!/bin/sh
# Execute lint to spot code mistakes.
cd "$(dirname "$0")/.."
export files="$(git diff $(git merge-base upstream/dev HEAD) --diff-filter=d --name-only | grep -e '\.py$')"
echo '================================================='
echo '= FILES CHANGED ='
echo '================================================='
if [ -z "$files" ] ; then
echo "No python file changed.\n"
exit
fi
printf "%s\n" $files
echo "=============="
echo "LINT with ruff"
echo "=============="
pre-commit run ruff --files $files
echo "================"
echo "LINT with pylint"
echo "================"
pylint_files=$(echo "$files" | grep -v '^tests.*')
if [ -z "$pylint_files" ] ; then
echo "Only test files changed. Skipping\n"
exit
fi
pylint $pylint_files
echo

View File

@@ -0,0 +1,251 @@
#!/usr/bin/env python3
"""Quickly check if branch is up to PR standards.
This is NOT a full CI/linting replacement, only a quick check during development.
"""
import asyncio
from collections import namedtuple
from contextlib import suppress
import itertools
import os
from pathlib import Path
import re
import shlex
import sys
try:
from colorlog.escape_codes import escape_codes
except ImportError:
escape_codes = None
RE_ASCII = re.compile(r"\033\[[^m]*m")
Error = namedtuple("Error", ["file", "line", "col", "msg", "skip"]) # noqa: PYI024
PASS = "green"
FAIL = "bold_red"
def printc(the_color, *args):
"""Color print helper."""
msg = " ".join(args)
if not escape_codes:
print(msg)
return
try:
print(escape_codes[the_color] + msg + escape_codes["reset"])
except KeyError as err:
print(msg)
raise ValueError(f"Invalid color {the_color}") from err
def validate_requirements_ok():
"""Validate requirements, returns True of ok."""
# pylint: disable-next=import-outside-toplevel
from gen_requirements_all import main as req_main
return req_main(True) == 0
async def read_stream(stream, display):
"""Read from stream line by line until EOF, display, and capture lines."""
output = []
while True:
line = await stream.readline()
if not line:
break
output.append(line)
display(line.decode()) # assume it doesn't block
return b"".join(output)
async def async_exec(*args, display=False):
"""Execute, return code & log."""
argsp = []
for arg in args:
if Path(arg).is_file():
argsp.append(f"\\\n {shlex.quote(arg)}")
else:
argsp.append(shlex.quote(arg))
printc("cyan", *argsp)
try:
kwargs = {
"stdout": asyncio.subprocess.PIPE,
"stderr": asyncio.subprocess.STDOUT,
}
if display:
kwargs["stderr"] = asyncio.subprocess.PIPE
proc = await asyncio.create_subprocess_exec(*args, **kwargs)
except FileNotFoundError:
printc(FAIL, f"Could not execute {args[0]}. Did you install test requirements?")
raise
if not display:
# Reading stdout into log
stdout, _ = await proc.communicate()
else:
# read child's stdout/stderr concurrently (capture and display)
stdout, _ = await asyncio.gather(
read_stream(proc.stdout, sys.stdout.write),
read_stream(proc.stderr, sys.stderr.write),
)
exit_code = await proc.wait()
stdout = stdout.decode("utf-8")
return exit_code, stdout
async def git():
"""Exec git."""
if len(sys.argv) > 2 and sys.argv[1] == "--":
return sys.argv[2:]
_, log = await async_exec("git", "merge-base", "upstream/dev", "HEAD")
merge_base = log.splitlines()[0]
_, log = await async_exec("git", "diff", merge_base, "--name-only")
return log.splitlines()
async def pylint(files):
"""Exec pylint."""
_, log = await async_exec("pylint", "-f", "parseable", "--persistent=n", *files)
res = []
for line in log.splitlines():
line = line.split(":")
if len(line) < 3:
continue
_fn = line[0].replace("\\", "/")
res.append(Error(_fn, line[1], "", line[2].strip(), _fn.startswith("tests/")))
return res
async def ruff(files):
"""Exec ruff."""
_, log = await async_exec("pre-commit", "run", "ruff", "--files", *files)
res = []
for line in log.splitlines():
line = line.split(":")
if len(line) < 4:
continue
_fn = line[0].replace("\\", "/")
res.append(Error(_fn, line[1], line[2], line[3].strip(), False))
return res
async def lint(files):
"""Perform lint."""
files = [file for file in files if Path(file).is_file()]
res = sorted(
itertools.chain(
*await asyncio.gather(
pylint(files),
ruff(files),
)
),
key=lambda item: item.file,
)
if res:
print("Lint errors:")
else:
printc(PASS, "Lint passed")
lint_ok = True
for err in res:
err_msg = f"{err.file} {err.line}:{err.col} {err.msg}"
# tests/* does not have to pass lint
if err.skip:
print(err_msg)
else:
printc(FAIL, err_msg)
lint_ok = False
return lint_ok
async def main():
"""Run the main loop."""
# Ensure we are in the homeassistant root
os.chdir(Path(__file__).parent.parent)
files = await git()
if not files:
print(
"No changed files found. Please ensure you have added your "
"changes with git add & git commit"
)
return
pyfiles = [file for file in files if file.endswith(".py")]
print("=============================")
printc("bold", "CHANGED FILES:\n", "\n ".join(pyfiles))
print("=============================")
skip_lint = len(sys.argv) > 1 and sys.argv[1] == "--skiplint"
if skip_lint:
printc(FAIL, "LINT DISABLED")
elif not await lint(pyfiles):
printc(FAIL, "Please fix your lint issues before continuing")
return
test_files = set()
gen_req = False
for fname in pyfiles:
if fname.startswith("homeassistant/components/"):
gen_req = True # requirements script for components
# Find test files...
if fname.startswith("tests/"):
if "/test_" in fname and Path(fname).is_file():
# All test helpers should be excluded
test_files.add(fname)
else:
parts = fname.split("/")
parts[0] = "tests"
if parts[-1] == "__init__.py":
parts[-1] = "test_init.py"
elif parts[-1] == "__main__.py":
parts[-1] = "test_main.py"
else:
parts[-1] = f"test_{parts[-1]}"
fname = "/".join(parts)
if Path(fname).is_file():
test_files.add(fname)
if gen_req:
print("=============================")
if validate_requirements_ok():
printc(PASS, "script/gen_requirements.py passed")
else:
printc(FAIL, "Please run script/gen_requirements.py")
return
print("=============================")
if not test_files:
print("No test files identified")
return
code, _ = await async_exec(
"python3",
"-b",
"-m",
"pytest",
"-vv",
"--force-sugar",
"--",
*test_files,
display=True,
)
print("=============================")
if code == 0:
printc(PASS, "Yay! This will most likely pass CI")
else:
printc(FAIL, "Tests not passing")
if skip_lint:
printc(FAIL, "LINT DISABLED")
if __name__ == "__main__":
with suppress(FileNotFoundError, KeyboardInterrupt):
asyncio.run(main())

View File

@@ -0,0 +1,26 @@
"""Helper script to update supported languages for Microsoft text-to-speech (TTS)."""
from pathlib import Path
from lxml import html
import requests
from .hassfest.serializer import format_python_namespace
URL = "https://docs.microsoft.com/en-us/azure/cognitive-services/speech-service/language-support"
XPATH_QUERY = "//section[@data-tab='tts']/table[1]/tbody/tr/td[1]/code/text()"
req = requests.get(URL)
req.raise_for_status()
tree = html.fromstring(req.content)
supported_languages_raw = tree.xpath(XPATH_QUERY)
supported_languages = {s.lower() for s in supported_languages_raw}
Path("homeassistant/generated/microsoft_tts.py").write_text(
format_python_namespace(
{
"SUPPORTED_LANGUAGES": supported_languages,
},
generator="script.microsoft_tts",
)
)

View File

@@ -0,0 +1,25 @@
#!/bin/sh
# Run monkeytype on test suite or optionally on a test module or directory.
# Stop on errors
set -e
cd "$(dirname "$0")/.."
command -v pytest >/dev/null 2>&1 || {
echo >&2 "This script requires pytest but it's not installed." \
"Aborting. Try: uv pip install pytest"; exit 1; }
command -v monkeytype >/dev/null 2>&1 || {
echo >&2 "This script requires monkeytype but it's not installed." \
"Aborting. Try: uv pip install monkeytype"; exit 1; }
if [ $# -eq 0 ]
then
echo "Run monkeytype on test suite"
monkeytype run "`command -v pytest`"
exit
fi
echo "Run monkeytype on tests in $1"
monkeytype run "`command -v pytest`" "$1"

View File

@@ -0,0 +1,7 @@
# This extend our general Ruff rules specifically for tests
extend = "../pyproject.toml"
[lint.isort]
forced-separate = [
"tests",
]

View File

@@ -0,0 +1,30 @@
#!/usr/bin/env sh
set -eu
# Used in venv activate script.
# Would be an error if undefined.
OSTYPE="${OSTYPE-}"
# Activate pyenv and virtualenv if present, then run the specified command
# pyenv, pyenv-virtualenv
if [ -s .python-version ]; then
PYENV_VERSION=$(head -n 1 .python-version)
export PYENV_VERSION
fi
if [ -n "${VIRTUAL_ENV-}" ] && [ -f "${VIRTUAL_ENV}/bin/activate" ]; then
. "${VIRTUAL_ENV}/bin/activate"
else
# other common virtualenvs
my_path=$(git rev-parse --show-toplevel)
for venv in venv .venv .; do
if [ -f "${my_path}/${venv}/bin/activate" ]; then
. "${my_path}/${venv}/bin/activate"
break
fi
done
fi
exec "$@"

View File

@@ -0,0 +1 @@
"""Scaffold new integration."""

View File

@@ -0,0 +1,121 @@
"""Validate manifests."""
import argparse
from pathlib import Path
import subprocess
import sys
from script.util import valid_integration
from . import docs, error, gather_info, generate
TEMPLATES = [
p.name for p in (Path(__file__).parent / "templates").glob("*") if p.is_dir()
]
def get_arguments() -> argparse.Namespace:
"""Get parsed passed in arguments."""
parser = argparse.ArgumentParser(description="Home Assistant Scaffolder")
parser.add_argument("template", type=str, choices=TEMPLATES)
parser.add_argument(
"--develop", action="store_true", help="Automatically fill in info"
)
parser.add_argument(
"--integration", type=valid_integration, help="Integration to target."
)
return parser.parse_args()
def main() -> int:
"""Scaffold an integration."""
if not Path("requirements_all.txt").is_file():
print("Run from project root")
return 1
args = get_arguments()
info = gather_info.gather_info(args)
print()
# If we are calling scaffold on a non-existing integration,
# We're going to first make it. If we're making an integration,
# we will also make a config flow to go with it.
if info.is_new:
generate.generate("integration", info)
# If it's a new integration and it's not a config flow,
# create a config flow too.
if not args.template.startswith("config_flow"):
if info.helper:
template = "config_flow_helper"
elif info.oauth2:
template = "config_flow_oauth2"
elif info.authentication or not info.discoverable:
template = "config_flow"
else:
template = "config_flow_discovery"
generate.generate(template, info)
# If we wanted a new integration, we've already done our work.
if args.template != "integration":
generate.generate(args.template, info)
pipe_null = {} if args.develop else {"stdout": subprocess.DEVNULL}
print("Running hassfest to pick up new information.")
subprocess.run(["python", "-m", "script.hassfest"], **pipe_null, check=True)
print()
print("Running gen_requirements_all to pick up new information.")
subprocess.run(
["python", "-m", "script.gen_requirements_all"], **pipe_null, check=True
)
print()
print("Running script/translations_develop to pick up new translation strings.")
subprocess.run(
[
"python",
"-m",
"script.translations",
"develop",
"--integration",
info.domain,
],
**pipe_null,
check=True,
)
print()
if args.develop:
print("Running tests")
print(f"$ python3 -b -m pytest -vvv tests/components/{info.domain}")
subprocess.run(
[
"python3",
"-b",
"-m",
"pytest",
"-vvv",
f"tests/components/{info.domain}",
],
check=True,
)
print()
docs.print_relevant_docs(args.template, info)
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except error.ExitApp as err:
print()
print(f"Fatal Error: {err.reason}")
sys.exit(err.exit_code)

View File

@@ -0,0 +1,6 @@
"""Constants for scaffolding."""
from pathlib import Path
COMPONENT_DIR = Path("homeassistant/components")
TESTS_DIR = Path("tests/components")

View File

@@ -0,0 +1,91 @@
"""Print links to relevant docs."""
from .model import Info
DATA = {
"backup": {
"title": "Backup",
"docs": "https://developers.home-assistant.io/docs/core/platform/backup",
},
"config_flow": {
"title": "Config Flow",
"docs": "https://developers.home-assistant.io/docs/en/config_entries_config_flow_handler.html",
},
"config_flow_helper": {
"title": "Helper Config Flow",
"docs": "https://developers.home-assistant.io/docs/en/config_entries_config_flow_handler.html#helper",
},
"config_flow_discovery": {
"title": "Discoverable Config Flow",
"docs": "https://developers.home-assistant.io/docs/en/config_entries_config_flow_handler.html#discoverable-integrations-that-require-no-authentication",
},
"config_flow_oauth2": {
"title": "OAuth2 Config Flow",
"docs": "https://developers.home-assistant.io/docs/en/next/config_entries_config_flow_handler.html#configuration-via-oauth2",
},
"device_action": {
"title": "Device Action",
"docs": "https://developers.home-assistant.io/docs/en/device_automation_action.html",
},
"device_condition": {
"title": "Device Condition",
"docs": "https://developers.home-assistant.io/docs/en/device_automation_condition.html",
},
"device_trigger": {
"title": "Device Trigger",
"docs": "https://developers.home-assistant.io/docs/en/device_automation_trigger.html",
},
"integration": {
"title": "Integration",
"docs": "https://developers.home-assistant.io/docs/en/creating_integration_file_structure.html",
},
"reproduce_state": {
"title": "Reproduce State",
"docs": "https://developers.home-assistant.io/docs/core/platform/reproduce_state",
"extra": "You will now need to update the code to make sure that every attribute that can occur in the state will cause the right service to be called.",
},
"significant_change": {
"title": "Significant Change",
"docs": "https://developers.home-assistant.io/docs/core/platform/significant_change",
"extra": "You will now need to update the code to make sure that entities with different device classes are correctly considered.",
},
}
def print_relevant_docs(template: str, info: Info) -> None:
"""Print relevant docs."""
data = DATA[template]
print()
print("**************************")
print()
print()
print(f"{data['title']} code has been generated")
print()
if info.files_added:
print("Added the following files:")
for file in info.files_added:
print(f"- {file}")
print()
if info.tests_added:
print("Added the following tests:")
for file in info.tests_added:
print(f"- {file}")
print()
if info.examples_added:
print(
"Because some files already existed, we added the following example files. Please copy the relevant code to the existing files."
)
for file in info.examples_added:
print(f"- {file}")
print()
print(
"The next step is to look at the files and deal with all areas marked as TODO."
)
if "extra" in data:
print()
print(data["extra"])

View File

@@ -0,0 +1,10 @@
"""Errors for scaffolding."""
class ExitApp(Exception):
"""Exception to indicate app should exit."""
def __init__(self, reason, exit_code=1):
"""Initialize the exit app exception."""
self.reason = reason
self.exit_code = exit_code

View File

@@ -0,0 +1,186 @@
"""Gather info for scaffolding."""
import json
from homeassistant.util import slugify
from script.hassfest.manifest import SUPPORTED_IOT_CLASSES
from .const import COMPONENT_DIR
from .error import ExitApp
from .model import Info
CHECK_EMPTY = ["Cannot be empty", lambda value: value]
def gather_info(arguments) -> Info:
"""Gather info."""
if arguments.integration:
info = {"domain": arguments.integration}
elif arguments.develop:
print("Running in developer mode. Automatically filling in info.")
print()
info = {"domain": "develop"}
else:
info = _gather_info(
{
"domain": {
"prompt": "What is the domain?",
"validators": [
CHECK_EMPTY,
[
"Domains cannot contain spaces or special characters.",
lambda value: value == slugify(value),
],
],
}
}
)
info["is_new"] = not (COMPONENT_DIR / info["domain"] / "manifest.json").exists()
if not info["is_new"]:
return _load_existing_integration(info["domain"])
if arguments.develop:
info.update(
{
"name": "Develop Hub",
"codeowner": "@developer",
"requirement": "aiodevelop==1.2.3",
"oauth2": True,
"iot_class": "local_polling",
}
)
else:
info.update(gather_new_integration(arguments.template == "integration"))
return Info(**info)
YES_NO = {
"validators": [["Type either 'yes' or 'no'", lambda value: value in ("yes", "no")]],
"converter": lambda value: value == "yes",
}
def gather_new_integration(determine_auth: bool) -> Info:
"""Gather info about new integration from user."""
fields = {
"name": {
"prompt": "What is the name of your integration?",
"validators": [CHECK_EMPTY],
},
"codeowner": {
"prompt": "What is your GitHub handle?",
"validators": [
CHECK_EMPTY,
[
'GitHub handles need to start with an "@"',
lambda value: value.startswith("@"),
],
],
},
"requirement": {
"prompt": "What PyPI package and version do you depend on? Leave blank for none.",
"validators": [
[
"Versions should be pinned using '=='.",
lambda value: not value or "==" in value,
]
],
},
"iot_class": {
"prompt": (
f"""How will your integration gather data?
Valid values are {', '.join(SUPPORTED_IOT_CLASSES)}
More info @ https://developers.home-assistant.io/docs/creating_integration_manifest#iot-class
"""
),
"validators": [
[
f"You need to pick one of {', '.join(SUPPORTED_IOT_CLASSES)}",
lambda value: value in SUPPORTED_IOT_CLASSES,
]
],
},
}
if determine_auth:
fields.update(
{
"authentication": {
"prompt": "Does Home Assistant need the user to authenticate to control the device/service? (yes/no)",
"default": "yes",
**YES_NO,
},
"discoverable": {
"prompt": "Is the device/service discoverable on the local network? (yes/no)",
"default": "no",
**YES_NO,
},
"helper": {
"prompt": "Is this a helper integration? (yes/no)",
"default": "no",
**YES_NO,
},
"oauth2": {
"prompt": "Can the user authenticate the device using OAuth2? (yes/no)",
"default": "no",
**YES_NO,
},
}
)
return _gather_info(fields)
def _load_existing_integration(domain) -> Info:
"""Load an existing integration."""
if not (COMPONENT_DIR / domain).exists():
raise ExitApp("Integration does not exist", 1)
manifest = json.loads((COMPONENT_DIR / domain / "manifest.json").read_text())
return Info(domain=domain, name=manifest["name"], is_new=False)
def _gather_info(fields) -> dict:
"""Gather info from user."""
answers = {}
for key, info in fields.items():
hint = None
while key not in answers:
if hint is not None:
print()
print(f"Error: {hint}")
try:
print()
msg = info["prompt"]
if "default" in info:
msg += f" [{info['default']}]"
value = input(f"{msg}\n> ")
except (KeyboardInterrupt, EOFError) as err:
raise ExitApp("Interrupted!", 1) from err
value = value.strip()
if value == "" and "default" in info:
value = info["default"]
hint = None
for validator_hint, validator in info["validators"]:
if not validator(value):
hint = validator_hint
break
if hint is None:
if "converter" in info:
value = info["converter"](value)
answers[key] = value
return answers

View File

@@ -0,0 +1,201 @@
"""Generate an integration."""
from pathlib import Path
from .model import Info
TEMPLATE_DIR = Path(__file__).parent / "templates"
TEMPLATE_INTEGRATION = TEMPLATE_DIR / "integration"
TEMPLATE_TESTS = TEMPLATE_DIR / "tests"
def generate(template: str, info: Info) -> None:
"""Generate a template."""
print(f"Scaffolding {template} for the {info.domain} integration...")
_ensure_tests_dir_exists(info)
_generate(TEMPLATE_DIR / template / "integration", info.integration_dir, info)
_generate(TEMPLATE_DIR / template / "tests", info.tests_dir, info)
_custom_tasks(template, info)
print()
def _generate(src_dir: Path, target_dir: Path, info: Info) -> None:
"""Generate an integration."""
replaces = {"NEW_DOMAIN": info.domain, "NEW_NAME": info.name}
if not target_dir.exists():
target_dir.mkdir()
for source_file in src_dir.glob("**/*"):
content = source_file.read_text()
for to_search, to_replace in replaces.items():
content = content.replace(to_search, to_replace)
target_file = target_dir / source_file.relative_to(src_dir)
# If the target file exists, create our template as EXAMPLE_<filename>.
# Exception: If we are creating a new integration, we can end up running integration base
# and a config flows on top of one another. In that case, we want to override the files.
if not info.is_new and target_file.exists():
new_name = f"EXAMPLE_{target_file.name}"
print(f"File {target_file} already exists, creating {new_name} instead.")
target_file = target_file.parent / new_name
info.examples_added.add(target_file)
elif src_dir.name == "integration":
info.files_added.add(target_file)
else:
info.tests_added.add(target_file)
print(f"Writing {target_file}")
target_file.write_text(content)
def _ensure_tests_dir_exists(info: Info) -> None:
"""Ensure a test dir exists."""
if info.tests_dir.exists():
return
info.tests_dir.mkdir()
print(f"Writing {info.tests_dir / '__init__.py'}")
(info.tests_dir / "__init__.py").write_text(
f'"""Tests for the {info.name} integration."""\n'
)
def _append(path: Path, text):
"""Append some text to a path."""
path.write_text(path.read_text() + text)
def _custom_tasks(template, info: Info) -> None:
"""Handle custom tasks for templates."""
if template == "integration":
changes = {"codeowners": [info.codeowner], "iot_class": info.iot_class}
if info.requirement:
changes["requirements"] = [info.requirement]
info.update_manifest(**changes)
elif template == "device_trigger":
info.update_strings(
device_automation={
**info.strings().get("device_automation", {}),
"trigger_type": {
"turned_on": "{entity_name} turned on",
"turned_off": "{entity_name} turned off",
},
}
)
elif template == "device_condition":
info.update_strings(
device_automation={
**info.strings().get("device_automation", {}),
"condition_type": {
"is_on": "{entity_name} is on",
"is_off": "{entity_name} is off",
},
}
)
elif template == "device_action":
info.update_strings(
device_automation={
**info.strings().get("device_automation", {}),
"action_type": {
"turn_on": "Turn on {entity_name}",
"turn_off": "Turn off {entity_name}",
},
}
)
elif template == "config_flow":
info.update_manifest(config_flow=True)
info.update_strings(
config={
"step": {
"user": {
"data": {
"host": "[%key:common::config_flow::data::host%]",
"username": "[%key:common::config_flow::data::username%]",
"password": "[%key:common::config_flow::data::password%]",
},
}
},
"error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
"invalid_auth": "[%key:common::config_flow::error::invalid_auth%]",
"unknown": "[%key:common::config_flow::error::unknown%]",
},
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]"
},
},
)
elif template == "config_flow_discovery":
info.update_manifest(config_flow=True)
info.update_strings(
config={
"step": {
"confirm": {
"description": "[%key:common::config_flow::description::confirm_setup%]",
}
},
"abort": {
"single_instance_allowed": "[%key:common::config_flow::abort::single_instance_allowed%]",
"no_devices_found": "[%key:common::config_flow::abort::no_devices_found%]",
},
},
)
elif template == "config_flow_helper":
info.update_manifest(config_flow=True, integration_type="helper")
info.update_strings(
config={
"step": {
"user": {
"description": "New NEW_NAME Sensor",
"data": {"entity_id": "Input sensor", "name": "Name"},
},
},
},
options={
"step": {
"init": {
"data": {
"entity_id": "[%key:component::NEW_DOMAIN::config::step::user::description%]"
},
},
},
},
)
elif template == "config_flow_oauth2":
info.update_manifest(config_flow=True, dependencies=["application_credentials"])
info.update_strings(
config={
"step": {
"pick_implementation": {
"title": "[%key:common::config_flow::title::oauth2_pick_implementation%]"
}
},
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_account%]",
"already_in_progress": "[%key:common::config_flow::abort::already_in_progress%]",
"oauth_error": "[%key:common::config_flow::abort::oauth2_error%]",
"oauth_failed": "[%key:common::config_flow::abort::oauth2_failed%]",
"oauth_timeout": "[%key:common::config_flow::abort::oauth2_timeout%]",
"oauth_unauthorized": "[%key:common::config_flow::abort::oauth2_unauthorized%]",
"missing_configuration": "[%key:common::config_flow::abort::oauth2_missing_configuration%]",
"authorize_url_timeout": "[%key:common::config_flow::abort::oauth2_authorize_url_timeout%]",
"no_url_available": "[%key:common::config_flow::abort::oauth2_no_url_available%]",
"user_rejected_authorize": "[%key:common::config_flow::abort::oauth2_user_rejected_authorize%]",
},
"create_entry": {
"default": "[%key:common::config_flow::create_entry::authenticated%]"
},
},
)

View File

@@ -0,0 +1,74 @@
"""Models for scaffolding."""
from __future__ import annotations
import json
from pathlib import Path
import attr
from .const import COMPONENT_DIR, TESTS_DIR
@attr.s
class Info:
"""Info about new integration."""
domain: str = attr.ib()
name: str = attr.ib()
is_new: bool = attr.ib()
codeowner: str = attr.ib(default=None)
requirement: str = attr.ib(default=None)
iot_class: str = attr.ib(default=None)
authentication: str = attr.ib(default=None)
discoverable: str = attr.ib(default=None)
oauth2: str = attr.ib(default=None)
helper: str = attr.ib(default=None)
files_added: set[Path] = attr.ib(factory=set)
tests_added: set[Path] = attr.ib(factory=set)
examples_added: set[Path] = attr.ib(factory=set)
@property
def integration_dir(self) -> Path:
"""Return directory if integration."""
return COMPONENT_DIR / self.domain
@property
def tests_dir(self) -> Path:
"""Return test directory."""
return TESTS_DIR / self.domain
@property
def manifest_path(self) -> Path:
"""Path to the manifest."""
return COMPONENT_DIR / self.domain / "manifest.json"
def manifest(self) -> dict:
"""Return integration manifest."""
return json.loads(self.manifest_path.read_text())
def update_manifest(self, **kwargs) -> None:
"""Update the integration manifest."""
print(f"Updating {self.domain} manifest: {kwargs}")
self.manifest_path.write_text(
json.dumps({**self.manifest(), **kwargs}, indent=2) + "\n"
)
@property
def strings_path(self) -> Path:
"""Path to the strings."""
return COMPONENT_DIR / self.domain / "strings.json"
def strings(self) -> dict:
"""Return integration strings."""
if not self.strings_path.exists():
return {}
return json.loads(self.strings_path.read_text())
def update_strings(self, **kwargs) -> None:
"""Update the integration strings."""
print(f"Updating {self.domain} strings: {list(kwargs)}")
self.strings_path.write_text(
json.dumps({**self.strings(), **kwargs}, indent=2) + "\n"
)

View File

@@ -0,0 +1,11 @@
"""Backup platform for the NEW_NAME integration."""
from homeassistant.core import HomeAssistant
async def async_pre_backup(hass: HomeAssistant) -> None:
"""Perform operations before a backup starts."""
async def async_post_backup(hass: HomeAssistant) -> None:
"""Perform operations after a backup finishes."""

View File

@@ -0,0 +1,19 @@
"""Test the NEW_NAME backup platform."""
from homeassistant.components.NEW_DOMAIN.backup import (
async_post_backup,
async_pre_backup,
)
from homeassistant.core import HomeAssistant
async def test_async_post_backup(hass: HomeAssistant) -> None:
"""Verify async_post_backup."""
# TODO: verify that the async_post_backup function executes as expected
assert await async_post_backup(hass)
async def test_async_pre_backup(hass: HomeAssistant) -> None:
"""Verify async_pre_backup."""
# TODO: verify that the async_pre_backup function executes as expected
assert await async_pre_backup(hass)

View File

@@ -0,0 +1,35 @@
"""The NEW_NAME integration."""
from __future__ import annotations
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
# TODO List the platforms that you want to support.
# For your initial PR, limit it to 1 platform.
PLATFORMS: list[Platform] = [Platform.LIGHT]
# TODO Create ConfigEntry type alias with API object
# TODO Rename type alias and update all entry annotations
type New_NameConfigEntry = ConfigEntry[MyApi] # noqa: F821
# TODO Update entry annotation
async def async_setup_entry(hass: HomeAssistant, entry: New_NameConfigEntry) -> bool:
"""Set up NEW_NAME from a config entry."""
# TODO 1. Create API instance
# TODO 2. Validate the API connection (and authentication)
# TODO 3. Store an API object for your platforms to access
# entry.runtime_data = MyAPI(...)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
return True
# TODO Update entry annotation
async def async_unload_entry(hass: HomeAssistant, entry: New_NameConfigEntry) -> bool:
"""Unload a config entry."""
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)

View File

@@ -0,0 +1,104 @@
"""Config flow for the NEW_NAME integration."""
from __future__ import annotations
import logging
from typing import Any
import voluptuous as vol
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
# TODO adjust the data schema to the data that you need
STEP_USER_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_HOST): str,
vol.Required(CONF_USERNAME): str,
vol.Required(CONF_PASSWORD): str,
}
)
class PlaceholderHub:
"""Placeholder class to make tests pass.
TODO Remove this placeholder class and replace with things from your PyPI package.
"""
def __init__(self, host: str) -> None:
"""Initialize."""
self.host = host
async def authenticate(self, username: str, password: str) -> bool:
"""Test if we can authenticate with the host."""
return True
async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
"""Validate the user input allows us to connect.
Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user.
"""
# TODO validate the data can be used to set up a connection.
# If your PyPI package is not built with async, pass your methods
# to the executor:
# await hass.async_add_executor_job(
# your_validate_func, data[CONF_USERNAME], data[CONF_PASSWORD]
# )
hub = PlaceholderHub(data[CONF_HOST])
if not await hub.authenticate(data[CONF_USERNAME], data[CONF_PASSWORD]):
raise InvalidAuth
# If you cannot connect:
# throw CannotConnect
# If the authentication is wrong:
# InvalidAuth
# Return info that you want to store in the config entry.
return {"title": "Name of the device"}
class ConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for NEW_NAME."""
VERSION = 1
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the initial step."""
errors: dict[str, str] = {}
if user_input is not None:
try:
info = await validate_input(self.hass, user_input)
except CannotConnect:
errors["base"] = "cannot_connect"
except InvalidAuth:
errors["base"] = "invalid_auth"
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
return self.async_create_entry(title=info["title"], data=user_input)
return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
)
class CannotConnect(HomeAssistantError):
"""Error to indicate we cannot connect."""
class InvalidAuth(HomeAssistantError):
"""Error to indicate there is invalid auth."""

View File

@@ -0,0 +1,3 @@
"""Constants for the NEW_NAME integration."""
DOMAIN = "NEW_DOMAIN"

View File

@@ -0,0 +1,15 @@
"""Common fixtures for the NEW_NAME tests."""
from collections.abc import Generator
from unittest.mock import AsyncMock, patch
import pytest
@pytest.fixture
def mock_setup_entry() -> Generator[AsyncMock]:
"""Override async_setup_entry."""
with patch(
"homeassistant.components.NEW_DOMAIN.async_setup_entry", return_value=True
) as mock_setup_entry:
yield mock_setup_entry

View File

@@ -0,0 +1,145 @@
"""Test the NEW_NAME config flow."""
from unittest.mock import AsyncMock, patch
from homeassistant import config_entries
from homeassistant.components.NEW_DOMAIN.config_flow import CannotConnect, InvalidAuth
from homeassistant.components.NEW_DOMAIN.const import DOMAIN
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
async def test_form(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> None:
"""Test we get the form."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
with patch(
"homeassistant.components.NEW_DOMAIN.config_flow.PlaceholderHub.authenticate",
return_value=True,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "1.1.1.1",
CONF_USERNAME: "test-username",
CONF_PASSWORD: "test-password",
},
)
await hass.async_block_till_done()
assert result["type"] == FlowResultType.CREATE_ENTRY
assert result["title"] == "Name of the device"
assert result["data"] == {
CONF_HOST: "1.1.1.1",
CONF_USERNAME: "test-username",
CONF_PASSWORD: "test-password",
}
assert len(mock_setup_entry.mock_calls) == 1
async def test_form_invalid_auth(
hass: HomeAssistant, mock_setup_entry: AsyncMock
) -> None:
"""Test we handle invalid auth."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"homeassistant.components.NEW_DOMAIN.config_flow.PlaceholderHub.authenticate",
side_effect=InvalidAuth,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "1.1.1.1",
CONF_USERNAME: "test-username",
CONF_PASSWORD: "test-password",
},
)
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {"base": "invalid_auth"}
# Make sure the config flow tests finish with either an
# FlowResultType.CREATE_ENTRY or FlowResultType.ABORT so
# we can show the config flow is able to recover from an error.
with patch(
"homeassistant.components.NEW_DOMAIN.config_flow.PlaceholderHub.authenticate",
return_value=True,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "1.1.1.1",
CONF_USERNAME: "test-username",
CONF_PASSWORD: "test-password",
},
)
await hass.async_block_till_done()
assert result["type"] == FlowResultType.CREATE_ENTRY
assert result["title"] == "Name of the device"
assert result["data"] == {
CONF_HOST: "1.1.1.1",
CONF_USERNAME: "test-username",
CONF_PASSWORD: "test-password",
}
assert len(mock_setup_entry.mock_calls) == 1
async def test_form_cannot_connect(
hass: HomeAssistant, mock_setup_entry: AsyncMock
) -> None:
"""Test we handle cannot connect error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"homeassistant.components.NEW_DOMAIN.config_flow.PlaceholderHub.authenticate",
side_effect=CannotConnect,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "1.1.1.1",
CONF_USERNAME: "test-username",
CONF_PASSWORD: "test-password",
},
)
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {"base": "cannot_connect"}
# Make sure the config flow tests finish with either an
# FlowResultType.CREATE_ENTRY or FlowResultType.ABORT so
# we can show the config flow is able to recover from an error.
with patch(
"homeassistant.components.NEW_DOMAIN.config_flow.PlaceholderHub.authenticate",
return_value=True,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "1.1.1.1",
CONF_USERNAME: "test-username",
CONF_PASSWORD: "test-password",
},
)
await hass.async_block_till_done()
assert result["type"] == FlowResultType.CREATE_ENTRY
assert result["title"] == "Name of the device"
assert result["data"] == {
CONF_HOST: "1.1.1.1",
CONF_USERNAME: "test-username",
CONF_PASSWORD: "test-password",
}
assert len(mock_setup_entry.mock_calls) == 1

View File

@@ -0,0 +1,35 @@
"""The NEW_NAME integration."""
from __future__ import annotations
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
# TODO List the platforms that you want to support.
# For your initial PR, limit it to 1 platform.
PLATFORMS: list[Platform] = [Platform.BINARY_SENSOR]
# TODO Create ConfigEntry type alias with API object
# Alias name should be prefixed by integration name
type New_NameConfigEntry = ConfigEntry[MyApi] # noqa: F821
# TODO Update entry annotation
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up NEW_NAME from a config entry."""
# TODO 1. Create API instance
# TODO 2. Validate the API connection (and authentication)
# TODO 3. Store an API object for your platforms to access
# entry.runtime_data = MyAPI(...)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
return True
# TODO Update entry annotation
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)

View File

@@ -0,0 +1,18 @@
"""Config flow for the NEW_NAME integration."""
import my_pypi_dependency
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_entry_flow
from .const import DOMAIN
async def _async_has_devices(hass: HomeAssistant) -> bool:
"""Return if there are devices that can be discovered."""
# TODO Check if there are any devices that can be discovered in the network.
devices = await hass.async_add_executor_job(my_pypi_dependency.discover)
return len(devices) > 0
config_entry_flow.register_discovery_flow(DOMAIN, "NEW_NAME", _async_has_devices)

View File

@@ -0,0 +1,3 @@
"""Constants for the NEW_NAME integration."""
DOMAIN = "NEW_DOMAIN"

View File

@@ -0,0 +1,33 @@
"""The NEW_NAME integration."""
from __future__ import annotations
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up NEW_NAME from a config entry."""
# TODO Optionally store an object for your platforms to access
# entry.runtime_data = ...
# TODO Optionally validate config entry options before setting up platform
await hass.config_entries.async_forward_entry_setups(entry, (Platform.SENSOR,))
# TODO Remove if the integration does not have an options flow
entry.async_on_unload(entry.add_update_listener(config_entry_update_listener))
return True
# TODO Remove if the integration does not have an options flow
async def config_entry_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Update listener, called when the config entry options are changed."""
await hass.config_entries.async_reload(entry.entry_id)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
return await hass.config_entries.async_unload_platforms(entry, (Platform.SENSOR,))

View File

@@ -0,0 +1,53 @@
"""Config flow for the NEW_NAME integration."""
from __future__ import annotations
from collections.abc import Mapping
from typing import Any, cast
import voluptuous as vol
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.const import CONF_ENTITY_ID
from homeassistant.helpers import selector
from homeassistant.helpers.schema_config_entry_flow import (
SchemaConfigFlowHandler,
SchemaFlowFormStep,
SchemaFlowMenuStep,
)
from .const import DOMAIN
OPTIONS_SCHEMA = vol.Schema(
{
vol.Required(CONF_ENTITY_ID): selector.EntitySelector(
selector.EntitySelectorConfig(domain=SENSOR_DOMAIN)
),
}
)
CONFIG_SCHEMA = vol.Schema(
{
vol.Required("name"): selector.TextSelector(),
}
).extend(OPTIONS_SCHEMA.schema)
CONFIG_FLOW: dict[str, SchemaFlowFormStep | SchemaFlowMenuStep] = {
"user": SchemaFlowFormStep(CONFIG_SCHEMA)
}
OPTIONS_FLOW: dict[str, SchemaFlowFormStep | SchemaFlowMenuStep] = {
"init": SchemaFlowFormStep(OPTIONS_SCHEMA)
}
class ConfigFlowHandler(SchemaConfigFlowHandler, domain=DOMAIN):
"""Handle a config or options flow for NEW_NAME."""
config_flow = CONFIG_FLOW
# TODO remove the options_flow if the integration does not have an options flow
options_flow = OPTIONS_FLOW
def async_config_entry_title(self, options: Mapping[str, Any]) -> str:
"""Return config entry title."""
return cast(str, options["name"]) if "name" in options else ""

View File

@@ -0,0 +1,3 @@
"""Constants for the NEW_NAME integration."""
DOMAIN = "NEW_DOMAIN"

View File

@@ -0,0 +1,39 @@
"""Sensor platform for NEW_NAME integration."""
from __future__ import annotations
from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_ENTITY_ID
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.entity_platform import AddEntitiesCallback
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Initialize NEW_NAME config entry."""
registry = er.async_get(hass)
# Validate + resolve entity registry id to entity_id
entity_id = er.async_validate_entity_id(
registry, config_entry.options[CONF_ENTITY_ID]
)
# TODO Optionally validate config entry options before creating entity
name = config_entry.title
unique_id = config_entry.entry_id
async_add_entities([NEW_DOMAINSensorEntity(unique_id, name, entity_id)])
class NEW_DOMAINSensorEntity(SensorEntity):
"""NEW_DOMAIN Sensor."""
def __init__(self, unique_id: str, name: str, wrapped_entity_id: str) -> None:
"""Initialize NEW_DOMAIN Sensor."""
super().__init__()
self._wrapped_entity_id = wrapped_entity_id
self._attr_name = name
self._attr_unique_id = unique_id

View File

@@ -0,0 +1,15 @@
"""Common fixtures for the NEW_NAME tests."""
from collections.abc import Generator
from unittest.mock import AsyncMock, patch
import pytest
@pytest.fixture
def mock_setup_entry() -> Generator[AsyncMock]:
"""Override async_setup_entry."""
with patch(
"homeassistant.components.NEW_DOMAIN.async_setup_entry", return_value=True
) as mock_setup_entry:
yield mock_setup_entry

View File

@@ -0,0 +1,117 @@
"""Test the NEW_NAME config flow."""
from unittest.mock import AsyncMock
import pytest
from homeassistant import config_entries
from homeassistant.components.NEW_DOMAIN.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry
pytestmark = pytest.mark.usefixtures("mock_setup_entry")
@pytest.mark.parametrize("platform", ["sensor"])
async def test_config_flow(
hass: HomeAssistant, mock_setup_entry: AsyncMock, platform
) -> None:
"""Test the config flow."""
input_sensor_entity_id = "sensor.input"
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"name": "My NEW_DOMAIN", "entity_id": input_sensor_entity_id},
)
await hass.async_block_till_done()
assert result["type"] == FlowResultType.CREATE_ENTRY
assert result["title"] == "My NEW_DOMAIN"
assert result["data"] == {}
assert result["options"] == {
"entity_id": input_sensor_entity_id,
"name": "My NEW_DOMAIN",
}
assert len(mock_setup_entry.mock_calls) == 1
config_entry = hass.config_entries.async_entries(DOMAIN)[0]
assert config_entry.data == {}
assert config_entry.options == {
"entity_id": input_sensor_entity_id,
"name": "My NEW_DOMAIN",
}
assert config_entry.title == "My NEW_DOMAIN"
def get_suggested(schema, key):
"""Get suggested value for key in voluptuous schema."""
for k in schema:
if k == key:
if k.description is None or "suggested_value" not in k.description:
return None
return k.description["suggested_value"]
# Wanted key absent from schema
raise KeyError(f"Key `{key}` is missing from schema")
@pytest.mark.parametrize("platform", ["sensor"])
async def test_options(hass: HomeAssistant, platform) -> None:
"""Test reconfiguring."""
input_sensor_1_entity_id = "sensor.input1"
input_sensor_2_entity_id = "sensor.input2"
# Setup the config entry
config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
options={
"entity_id": input_sensor_1_entity_id,
"name": "My NEW_DOMAIN",
},
title="My NEW_DOMAIN",
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
result = await hass.config_entries.options.async_init(config_entry.entry_id)
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "init"
schema = result["data_schema"].schema
assert get_suggested(schema, "entity_id") == input_sensor_1_entity_id
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input={
"entity_id": input_sensor_2_entity_id,
},
)
assert result["type"] == FlowResultType.CREATE_ENTRY
assert result["data"] == {
"entity_id": input_sensor_2_entity_id,
"name": "My NEW_DOMAIN",
}
assert config_entry.data == {}
assert config_entry.options == {
"entity_id": input_sensor_2_entity_id,
"name": "My NEW_DOMAIN",
}
assert config_entry.title == "My NEW_DOMAIN"
# Check config entry is reloaded with new options
await hass.async_block_till_done()
# Check the entity was updated, no new entity was created
assert len(hass.states.async_all()) == 1
# TODO Check the state of the entity has changed as expected
state = hass.states.get(f"{platform}.my_NEW_DOMAIN")
assert state.attributes == {}

View File

@@ -0,0 +1,51 @@
"""Test the NEW_NAME integration."""
import pytest
from homeassistant.components.NEW_DOMAIN.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry
@pytest.mark.parametrize("platform", ["sensor"])
async def test_setup_and_remove_config_entry(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
platform: str,
) -> None:
"""Test setting up and removing a config entry."""
input_sensor_entity_id = "sensor.input"
NEW_DOMAIN_entity_id = f"{platform}.my_NEW_DOMAIN"
# Setup the config entry
config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
options={
"entity_id": input_sensor_entity_id,
"name": "My NEW_DOMAIN",
},
title="My NEW_DOMAIN",
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
# Check the entity is registered in the entity registry
assert entity_registry.async_get(NEW_DOMAIN_entity_id) is not None
# Check the platform is setup correctly
state = hass.states.get(NEW_DOMAIN_entity_id)
# TODO Check the state of the entity has changed as expected
assert state.state == "unknown"
assert state.attributes == {}
# Remove the config entry
assert await hass.config_entries.async_remove(config_entry.entry_id)
await hass.async_block_till_done()
# Check the state and entity registry entry are removed
assert hass.states.get(NEW_DOMAIN_entity_id) is None
assert entity_registry.async_get(NEW_DOMAIN_entity_id) is None

View File

@@ -0,0 +1,48 @@
"""The NEW_NAME integration."""
from __future__ import annotations
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import aiohttp_client, config_entry_oauth2_flow
from . import api
# TODO List the platforms that you want to support.
# For your initial PR, limit it to 1 platform.
PLATFORMS: list[Platform] = [Platform.LIGHT]
# TODO Create ConfigEntry type alias with ConfigEntryAuth or AsyncConfigEntryAuth object
# TODO Rename type alias and update all entry annotations
type New_NameConfigEntry = ConfigEntry[api.AsyncConfigEntryAuth]
# # TODO Update entry annotation
async def async_setup_entry(hass: HomeAssistant, entry: New_NameConfigEntry) -> bool:
"""Set up NEW_NAME from a config entry."""
implementation = (
await config_entry_oauth2_flow.async_get_config_entry_implementation(
hass, entry
)
)
session = config_entry_oauth2_flow.OAuth2Session(hass, entry, implementation)
# If using a requests-based API lib
entry.runtime_data = api.ConfigEntryAuth(hass, session)
# If using an aiohttp-based API lib
entry.runtime_data = api.AsyncConfigEntryAuth(
aiohttp_client.async_get_clientsession(hass), session
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
return True
# TODO Update entry annotation
async def async_unload_entry(hass: HomeAssistant, entry: New_NameConfigEntry) -> bool:
"""Unload a config entry."""
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)

View File

@@ -0,0 +1,54 @@
"""API for NEW_NAME bound to Home Assistant OAuth."""
from asyncio import run_coroutine_threadsafe
from aiohttp import ClientSession
import my_pypi_package
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_entry_oauth2_flow
# TODO the following two API examples are based on our suggested best practices
# for libraries using OAuth2 with requests or aiohttp. Delete the one you won't use.
# For more info see the docs at https://developers.home-assistant.io/docs/api_lib_auth/#oauth2.
class ConfigEntryAuth(my_pypi_package.AbstractAuth):
"""Provide NEW_NAME authentication tied to an OAuth2 based config entry."""
def __init__(
self,
hass: HomeAssistant,
oauth_session: config_entry_oauth2_flow.OAuth2Session,
) -> None:
"""Initialize NEW_NAME Auth."""
self.hass = hass
self.session = oauth_session
super().__init__(self.session.token)
def refresh_tokens(self) -> str:
"""Refresh and return new NEW_NAME tokens using Home Assistant OAuth2 session."""
run_coroutine_threadsafe(
self.session.async_ensure_token_valid(), self.hass.loop
).result()
return self.session.token["access_token"]
class AsyncConfigEntryAuth(my_pypi_package.AbstractAuth):
"""Provide NEW_NAME authentication tied to an OAuth2 based config entry."""
def __init__(
self,
websession: ClientSession,
oauth_session: config_entry_oauth2_flow.OAuth2Session,
) -> None:
"""Initialize NEW_NAME auth."""
super().__init__(websession)
self._oauth_session = oauth_session
async def async_get_access_token(self) -> str:
"""Return a valid access token."""
await self._oauth_session.async_ensure_token_valid()
return self._oauth_session.token["access_token"]

View File

@@ -0,0 +1,14 @@
"""Application credentials platform for the NEW_NAME integration."""
from homeassistant.components.application_credentials import AuthorizationServer
from homeassistant.core import HomeAssistant
from .const import OAUTH2_AUTHORIZE, OAUTH2_TOKEN
async def async_get_authorization_server(hass: HomeAssistant) -> AuthorizationServer:
"""Return authorization server."""
return AuthorizationServer(
authorize_url=OAUTH2_AUTHORIZE,
token_url=OAUTH2_TOKEN,
)

View File

@@ -0,0 +1,20 @@
"""Config flow for NEW_NAME."""
import logging
from homeassistant.helpers import config_entry_oauth2_flow
from .const import DOMAIN
class OAuth2FlowHandler(
config_entry_oauth2_flow.AbstractOAuth2FlowHandler, domain=DOMAIN
):
"""Config flow to handle NEW_NAME OAuth2 authentication."""
DOMAIN = DOMAIN
@property
def logger(self) -> logging.Logger:
"""Return logger."""
return logging.getLogger(__name__)

View File

@@ -0,0 +1,7 @@
"""Constants for the NEW_NAME integration."""
DOMAIN = "NEW_DOMAIN"
# TODO Update with your own urls
OAUTH2_AUTHORIZE = "https://www.example.com/auth/authorize"
OAUTH2_TOKEN = "https://www.example.com/auth/token"

View File

@@ -0,0 +1,82 @@
"""Test the NEW_NAME config flow."""
from unittest.mock import patch
import pytest
from homeassistant import config_entries
from homeassistant.components.application_credentials import (
ClientCredential,
async_import_client_credential,
)
from homeassistant.components.NEW_DOMAIN.const import (
DOMAIN,
OAUTH2_AUTHORIZE,
OAUTH2_TOKEN,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_entry_oauth2_flow
from homeassistant.setup import async_setup_component
CLIENT_ID = "1234"
CLIENT_SECRET = "5678"
@pytest.fixture
async def setup_credentials(hass: HomeAssistant) -> None:
"""Fixture to setup credentials."""
assert await async_setup_component(hass, "application_credentials", {})
await async_import_client_credential(
hass,
DOMAIN,
ClientCredential(CLIENT_ID, CLIENT_SECRET),
)
async def test_full_flow(
hass: HomeAssistant,
hass_client_no_auth,
aioclient_mock,
current_request_with_host,
setup_credentials,
) -> None:
"""Check full flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
state = config_entry_oauth2_flow._encode_jwt( # noqa: SLF001
hass,
{
"flow_id": result["flow_id"],
"redirect_uri": "https://example.com/auth/external/callback",
},
)
assert result["url"] == (
f"{OAUTH2_AUTHORIZE}?response_type=code&client_id={CLIENT_ID}"
"&redirect_uri=https://example.com/auth/external/callback"
f"&state={state}"
)
client = await hass_client_no_auth()
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
assert resp.status == 200
assert resp.headers["content-type"] == "text/html; charset=utf-8"
aioclient_mock.post(
OAUTH2_TOKEN,
json={
"refresh_token": "mock-refresh-token",
"access_token": "mock-access-token",
"type": "Bearer",
"expires_in": 60,
},
)
with patch(
"homeassistant.components.NEW_DOMAIN.async_setup_entry", return_value=True
) as mock_setup:
await hass.config_entries.flow.async_configure(result["flow_id"])
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
assert len(mock_setup.mock_calls) == 1

View File

@@ -0,0 +1,78 @@
"""Provides device actions for NEW_NAME."""
from __future__ import annotations
import voluptuous as vol
from homeassistant.const import (
ATTR_ENTITY_ID,
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_ENTITY_ID,
CONF_TYPE,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
)
from homeassistant.core import Context, HomeAssistant
from homeassistant.helpers import config_validation as cv, entity_registry as er
from . import DOMAIN
# TODO specify your supported action types.
ACTION_TYPES = {"turn_on", "turn_off"}
ACTION_SCHEMA = cv.DEVICE_ACTION_BASE_SCHEMA.extend(
{
vol.Required(CONF_TYPE): vol.In(ACTION_TYPES),
vol.Required(CONF_ENTITY_ID): cv.entity_domain(DOMAIN),
}
)
async def async_get_actions(
hass: HomeAssistant, device_id: str
) -> list[dict[str, str]]:
"""List device actions for NEW_NAME devices."""
registry = er.async_get(hass)
actions = []
# TODO Read this comment and remove it.
# This example shows how to iterate over the entities of this device
# that match this integration. If your actions instead rely on
# calling services, do something like:
# zha_device = await _async_get_zha_device(hass, device_id)
# return zha_device.device_actions
# Get all the integrations entities for this device
for entry in er.async_entries_for_device(registry, device_id):
if entry.domain != DOMAIN:
continue
# Add actions for each entity that belongs to this integration
# TODO add your own actions.
base_action = {
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
CONF_ENTITY_ID: entry.entity_id,
}
actions.append({**base_action, CONF_TYPE: "turn_on"})
actions.append({**base_action, CONF_TYPE: "turn_off"})
return actions
async def async_call_action_from_config(
hass: HomeAssistant, config: dict, variables: dict, context: Context | None
) -> None:
"""Execute a device action."""
service_data = {ATTR_ENTITY_ID: config[CONF_ENTITY_ID]}
if config[CONF_TYPE] == "turn_on":
service = SERVICE_TURN_ON
elif config[CONF_TYPE] == "turn_off":
service = SERVICE_TURN_OFF
await hass.services.async_call(
DOMAIN, service, service_data, blocking=True, context=context
)

View File

@@ -0,0 +1,144 @@
"""The tests for NEW_NAME device actions."""
import pytest
from pytest_unordered import unordered
from homeassistant.components import automation
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.components.NEW_DOMAIN import DOMAIN
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.setup import async_setup_component
from tests.common import (
MockConfigEntry,
async_get_device_automations,
async_mock_service,
)
async def test_get_actions(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected actions from a NEW_DOMAIN."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
expected_actions = [
{
"domain": DOMAIN,
"type": action,
"device_id": device_entry.id,
"entity_id": f"{DOMAIN}.test_5678",
}
for action in ["turn_off", "turn_on"]
]
actions = await async_get_device_automations(
hass, DeviceAutomationType.ACTION, device_entry.id
)
assert actions == unordered(expected_actions)
@pytest.mark.parametrize(
("hidden_by", "entity_category"),
[
(er.RegistryEntryHider.INTEGRATION, None),
(er.RegistryEntryHider.USER, None),
(None, EntityCategory.CONFIG),
(None, EntityCategory.DIAGNOSTIC),
],
)
async def test_get_actions_hidden_auxiliary(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
hidden_by: er.RegistryEntryHider | None,
entity_category: EntityCategory | None,
):
"""Test we get the expected actions from a hidden or auxiliary entity."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_registry.async_get_or_create(
DOMAIN,
"test",
"5678",
device_id=device_entry.id,
entity_category=entity_category,
hidden_by=hidden_by,
)
expected_actions = [
{
"domain": DOMAIN,
"type": action,
"device_id": device_entry.id,
"entity_id": f"{DOMAIN}.test_5678",
"metadata": {"secondary": True},
}
for action in ["turn_off", "turn_on", "toggle"]
]
actions = await async_get_device_automations(
hass, DeviceAutomationType.ACTION, device_entry.id
)
assert actions == unordered(expected_actions)
async def test_action(hass: HomeAssistant) -> None:
"""Test for turn_on and turn_off actions."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"platform": "event",
"event_type": "test_event_turn_off",
},
"action": {
"domain": DOMAIN,
"device_id": "abcdefgh",
"entity_id": "NEW_DOMAIN.entity",
"type": "turn_off",
},
},
{
"trigger": {
"platform": "event",
"event_type": "test_event_turn_on",
},
"action": {
"domain": DOMAIN,
"device_id": "abcdefgh",
"entity_id": "NEW_DOMAIN.entity",
"type": "turn_on",
},
},
]
},
)
turn_off_calls = async_mock_service(hass, "NEW_DOMAIN", "turn_off")
turn_on_calls = async_mock_service(hass, "NEW_DOMAIN", "turn_on")
hass.bus.async_fire("test_event_turn_off")
await hass.async_block_till_done()
assert len(turn_off_calls) == 1
assert len(turn_on_calls) == 0
hass.bus.async_fire("test_event_turn_on")
await hass.async_block_till_done()
assert len(turn_off_calls) == 1
assert len(turn_on_calls) == 1

View File

@@ -0,0 +1,79 @@
"""Provide the device conditions for NEW_NAME."""
from __future__ import annotations
import voluptuous as vol
from homeassistant.const import (
ATTR_ENTITY_ID,
CONF_CONDITION,
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_ENTITY_ID,
CONF_TYPE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import (
condition,
config_validation as cv,
entity_registry as er,
)
from homeassistant.helpers.typing import ConfigType, TemplateVarsType
from . import DOMAIN
# TODO specify your supported condition types.
CONDITION_TYPES = {"is_on", "is_off"}
CONDITION_SCHEMA = cv.DEVICE_CONDITION_BASE_SCHEMA.extend(
{
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Required(CONF_TYPE): vol.In(CONDITION_TYPES),
}
)
async def async_get_conditions(
hass: HomeAssistant, device_id: str
) -> list[dict[str, str]]:
"""List device conditions for NEW_NAME devices."""
registry = er.async_get(hass)
conditions = []
# Get all the integrations entities for this device
for entry in er.async_entries_for_device(registry, device_id):
if entry.domain != DOMAIN:
continue
# Add conditions for each entity that belongs to this integration
# TODO add your own conditions.
base_condition = {
CONF_CONDITION: "device",
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
CONF_ENTITY_ID: entry.entity_id,
}
conditions += [{**base_condition, CONF_TYPE: cond} for cond in CONDITION_TYPES]
return conditions
@callback
def async_condition_from_config(
hass: HomeAssistant, config: ConfigType
) -> condition.ConditionCheckerType:
"""Create a function to test a device condition."""
if config[CONF_TYPE] == "is_on":
state = STATE_ON
else:
state = STATE_OFF
@callback
def test_is_state(hass: HomeAssistant, variables: TemplateVarsType) -> bool:
"""Test if an entity is a certain state."""
return condition.state(hass, config[ATTR_ENTITY_ID], state)
return test_is_state

View File

@@ -0,0 +1,114 @@
"""The tests for NEW_NAME device conditions."""
from __future__ import annotations
from pytest_unordered import unordered
from homeassistant.components import automation
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.components.NEW_DOMAIN import DOMAIN
from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry, async_get_device_automations
async def test_get_conditions(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected conditions from a NEW_DOMAIN."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
expected_conditions = [
{
"condition": "device",
"domain": DOMAIN,
"type": "is_off",
"device_id": device_entry.id,
"entity_id": f"{DOMAIN}.test_5678",
},
{
"condition": "device",
"domain": DOMAIN,
"type": "is_on",
"device_id": device_entry.id,
"entity_id": f"{DOMAIN}.test_5678",
},
]
conditions = await async_get_device_automations(
hass, DeviceAutomationType.CONDITION, device_entry.id
)
assert conditions == unordered(expected_conditions)
async def test_if_state(hass: HomeAssistant, service_calls: list[ServiceCall]) -> None:
"""Test for turn_on and turn_off conditions."""
hass.states.async_set("NEW_DOMAIN.entity", STATE_ON)
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {"platform": "event", "event_type": "test_event1"},
"condition": [
{
"condition": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": "NEW_DOMAIN.entity",
"type": "is_on",
}
],
"action": {
"service": "test.automation",
"data_template": {
"some": "is_on - {{ trigger.platform }} - {{ trigger.event.event_type }}"
},
},
},
{
"trigger": {"platform": "event", "event_type": "test_event2"},
"condition": [
{
"condition": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": "NEW_DOMAIN.entity",
"type": "is_off",
}
],
"action": {
"service": "test.automation",
"data_template": {
"some": "is_off - {{ trigger.platform }} - {{ trigger.event.event_type }}"
},
},
},
]
},
)
hass.bus.async_fire("test_event1")
hass.bus.async_fire("test_event2")
await hass.async_block_till_done()
assert len(service_calls) == 1
assert service_calls[0].data["some"] == "is_on - event - test_event1"
hass.states.async_set("NEW_DOMAIN.entity", STATE_OFF)
hass.bus.async_fire("test_event1")
hass.bus.async_fire("test_event2")
await hass.async_block_till_done()
assert len(service_calls) == 2
assert service_calls[1].data["some"] == "is_off - event - test_event2"

View File

@@ -0,0 +1,94 @@
"""Provides device triggers for NEW_NAME."""
from __future__ import annotations
from typing import Any
import voluptuous as vol
from homeassistant.components.device_automation import DEVICE_TRIGGER_BASE_SCHEMA
from homeassistant.components.homeassistant.triggers import state as state_trigger
from homeassistant.const import (
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_ENTITY_ID,
CONF_PLATFORM,
CONF_TYPE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import CALLBACK_TYPE, HomeAssistant
from homeassistant.helpers import config_validation as cv, entity_registry as er
from homeassistant.helpers.trigger import TriggerActionType, TriggerInfo
from homeassistant.helpers.typing import ConfigType
from . import DOMAIN
# TODO specify your supported trigger types.
TRIGGER_TYPES = {"turned_on", "turned_off"}
TRIGGER_SCHEMA = DEVICE_TRIGGER_BASE_SCHEMA.extend(
{
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Required(CONF_TYPE): vol.In(TRIGGER_TYPES),
}
)
async def async_get_triggers(
hass: HomeAssistant, device_id: str
) -> list[dict[str, Any]]:
"""List device triggers for NEW_NAME devices."""
registry = er.async_get(hass)
triggers = []
# TODO Read this comment and remove it.
# This example shows how to iterate over the entities of this device
# that match this integration. If your triggers instead rely on
# events fired by devices without entities, do something like:
# zha_device = await _async_get_zha_device(hass, device_id)
# return zha_device.device_triggers
# Get all the integrations entities for this device
for entry in er.async_entries_for_device(registry, device_id):
if entry.domain != DOMAIN:
continue
# Add triggers for each entity that belongs to this integration
# TODO add your own triggers.
base_trigger = {
CONF_PLATFORM: "device",
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
CONF_ENTITY_ID: entry.entity_id,
}
triggers.append({**base_trigger, CONF_TYPE: "turned_on"})
triggers.append({**base_trigger, CONF_TYPE: "turned_off"})
return triggers
async def async_attach_trigger(
hass: HomeAssistant,
config: ConfigType,
action: TriggerActionType,
trigger_info: TriggerInfo,
) -> CALLBACK_TYPE:
"""Attach a trigger."""
# TODO Implement your own logic to attach triggers.
# Use the existing state or event triggers from the automation integration.
if config[CONF_TYPE] == "turned_on":
to_state = STATE_ON
else:
to_state = STATE_OFF
state_config = {
state_trigger.CONF_PLATFORM: "state",
CONF_ENTITY_ID: config[CONF_ENTITY_ID],
state_trigger.CONF_TO: to_state,
}
state_config = await state_trigger.async_validate_trigger_config(hass, state_config)
return await state_trigger.async_attach_trigger(
hass, state_config, action, trigger_info, platform_type="device"
)

View File

@@ -0,0 +1,124 @@
"""The tests for NEW_NAME device triggers."""
from pytest_unordered import unordered
from homeassistant.components import automation
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.components.NEW_DOMAIN import DOMAIN
from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry, async_get_device_automations
async def test_get_triggers(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected triggers from a NEW_DOMAIN."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
expected_triggers = [
{
"platform": "device",
"domain": DOMAIN,
"type": "turned_off",
"device_id": device_entry.id,
"entity_id": f"{DOMAIN}.test_5678",
},
{
"platform": "device",
"domain": DOMAIN,
"type": "turned_on",
"device_id": device_entry.id,
"entity_id": f"{DOMAIN}.test_5678",
},
]
triggers = await async_get_device_automations(
hass, DeviceAutomationType.TRIGGER, device_entry.id
)
assert triggers == unordered(expected_triggers)
async def test_if_fires_on_state_change(
hass: HomeAssistant, service_calls: list[ServiceCall]
) -> None:
"""Test for turn_on and turn_off triggers firing."""
hass.states.async_set("NEW_DOMAIN.entity", STATE_OFF)
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": "NEW_DOMAIN.entity",
"type": "turned_on",
},
"action": {
"service": "test.automation",
"data_template": {
"some": (
"turn_on - {{ trigger.platform}} - "
"{{ trigger.entity_id}} - {{ trigger.from_state.state}} - "
"{{ trigger.to_state.state}} - {{ trigger.for }} - "
"{{ trigger.id}}"
)
},
},
},
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": "NEW_DOMAIN.entity",
"type": "turned_off",
},
"action": {
"service": "test.automation",
"data_template": {
"some": (
"turn_off - {{ trigger.platform}} - "
"{{ trigger.entity_id}} - {{ trigger.from_state.state}} - "
"{{ trigger.to_state.state}} - {{ trigger.for }} - "
"{{ trigger.id}}"
)
},
},
},
]
},
)
# Fake that the entity is turning on.
hass.states.async_set("NEW_DOMAIN.entity", STATE_ON)
await hass.async_block_till_done()
assert len(service_calls) == 1
assert (
service_calls[0].data["some"]
== "turn_on - device - NEW_DOMAIN.entity - off - on - None - 0"
)
# Fake that the entity is turning off.
hass.states.async_set("NEW_DOMAIN.entity", STATE_OFF)
await hass.async_block_till_done()
assert len(service_calls) == 2
assert (
service_calls[1].data["some"]
== "turn_off - device - NEW_DOMAIN.entity - on - off - None - 0"
)

View File

@@ -0,0 +1,17 @@
"""The NEW_NAME integration."""
from __future__ import annotations
import voluptuous as vol
from homeassistant.core import HomeAssistant
from homeassistant.helpers.typing import ConfigType
from .const import DOMAIN
CONFIG_SCHEMA = vol.Schema({vol.Optional(DOMAIN): {}}, extra=vol.ALLOW_EXTRA)
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the NEW_NAME integration."""
return True

Some files were not shown because too many files have changed in this diff Show More