Use a constant to reference homeassistant domain (#113889)

* Use CONF_CORE to reference `homeassistant` domain

* Just use DOMAIN

* USE DOMAIN for `homeasistant` domain in config_schema.py

* Use DOMAIN_HA as constant for homeassistant domain

* Rename CONF_CORE to DOMAIN_HA

* Rename DOMAIN_HA to HA_DOMAIN

* Use relative import

* Use direct imports
This commit is contained in:
Jan Bouwhuis 2024-03-23 19:58:39 +01:00 committed by GitHub
parent c661622332
commit a4f52cc622
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 51 additions and 43 deletions

View File

@ -8,12 +8,14 @@ from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.trigger import TriggerActionType, TriggerInfo from homeassistant.helpers.trigger import TriggerActionType, TriggerInfo
from homeassistant.helpers.typing import ConfigType from homeassistant.helpers.typing import ConfigType
from ..const import DOMAIN
EVENT_START = "start" EVENT_START = "start"
EVENT_SHUTDOWN = "shutdown" EVENT_SHUTDOWN = "shutdown"
TRIGGER_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend( TRIGGER_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend(
{ {
vol.Required(CONF_PLATFORM): "homeassistant", vol.Required(CONF_PLATFORM): DOMAIN,
vol.Required(CONF_EVENT): vol.Any(EVENT_START, EVENT_SHUTDOWN), vol.Required(CONF_EVENT): vol.Any(EVENT_START, EVENT_SHUTDOWN),
} }
) )
@ -36,7 +38,7 @@ async def async_attach_trigger(
{ {
"trigger": { "trigger": {
**trigger_data, **trigger_data,
"platform": "homeassistant", "platform": DOMAIN,
"event": event, "event": event,
"description": "Home Assistant stopping", "description": "Home Assistant stopping",
} }
@ -51,7 +53,7 @@ async def async_attach_trigger(
{ {
"trigger": { "trigger": {
**trigger_data, **trigger_data,
"platform": "homeassistant", "platform": DOMAIN,
"event": event, "event": event,
"description": "Home Assistant starting", "description": "Home Assistant starting",
} }

View File

@ -58,7 +58,7 @@ from .const import (
LEGACY_CONF_WHITELIST_EXTERNAL_DIRS, LEGACY_CONF_WHITELIST_EXTERNAL_DIRS,
__version__, __version__,
) )
from .core import DOMAIN as CONF_CORE, ConfigSource, HomeAssistant, callback from .core import DOMAIN as HA_DOMAIN, ConfigSource, HomeAssistant, callback
from .exceptions import ConfigValidationError, HomeAssistantError from .exceptions import ConfigValidationError, HomeAssistantError
from .generated.currencies import HISTORIC_CURRENCIES from .generated.currencies import HISTORIC_CURRENCIES
from .helpers import config_validation as cv, issue_registry as ir from .helpers import config_validation as cv, issue_registry as ir
@ -247,12 +247,12 @@ CUSTOMIZE_CONFIG_SCHEMA = vol.Schema(
def _raise_issue_if_historic_currency(hass: HomeAssistant, currency: str) -> None: def _raise_issue_if_historic_currency(hass: HomeAssistant, currency: str) -> None:
if currency not in HISTORIC_CURRENCIES: if currency not in HISTORIC_CURRENCIES:
ir.async_delete_issue(hass, "homeassistant", "historic_currency") ir.async_delete_issue(hass, HA_DOMAIN, "historic_currency")
return return
ir.async_create_issue( ir.async_create_issue(
hass, hass,
"homeassistant", HA_DOMAIN,
"historic_currency", "historic_currency",
is_fixable=False, is_fixable=False,
learn_more_url="homeassistant://config/general", learn_more_url="homeassistant://config/general",
@ -264,12 +264,12 @@ def _raise_issue_if_historic_currency(hass: HomeAssistant, currency: str) -> Non
def _raise_issue_if_no_country(hass: HomeAssistant, country: str | None) -> None: def _raise_issue_if_no_country(hass: HomeAssistant, country: str | None) -> None:
if country is not None: if country is not None:
ir.async_delete_issue(hass, "homeassistant", "country_not_configured") ir.async_delete_issue(hass, HA_DOMAIN, "country_not_configured")
return return
ir.async_create_issue( ir.async_create_issue(
hass, hass,
"homeassistant", HA_DOMAIN,
"country_not_configured", "country_not_configured",
is_fixable=False, is_fixable=False,
learn_more_url="homeassistant://config/general", learn_more_url="homeassistant://config/general",
@ -288,7 +288,7 @@ def _raise_issue_if_legacy_templates(
if legacy_templates: if legacy_templates:
ir.async_create_issue( ir.async_create_issue(
hass, hass,
"homeassistant", HA_DOMAIN,
"legacy_templates_true", "legacy_templates_true",
is_fixable=False, is_fixable=False,
breaks_in_ha_version="2024.7.0", breaks_in_ha_version="2024.7.0",
@ -297,12 +297,12 @@ def _raise_issue_if_legacy_templates(
) )
return return
ir.async_delete_issue(hass, "homeassistant", "legacy_templates_true") ir.async_delete_issue(hass, HA_DOMAIN, "legacy_templates_true")
if legacy_templates is False: if legacy_templates is False:
ir.async_create_issue( ir.async_create_issue(
hass, hass,
"homeassistant", HA_DOMAIN,
"legacy_templates_false", "legacy_templates_false",
is_fixable=False, is_fixable=False,
breaks_in_ha_version="2024.7.0", breaks_in_ha_version="2024.7.0",
@ -310,7 +310,7 @@ def _raise_issue_if_legacy_templates(
translation_key="legacy_templates_false", translation_key="legacy_templates_false",
) )
else: else:
ir.async_delete_issue(hass, "homeassistant", "legacy_templates_false") ir.async_delete_issue(hass, HA_DOMAIN, "legacy_templates_false")
def _validate_currency(data: Any) -> Any: def _validate_currency(data: Any) -> Any:
@ -503,12 +503,12 @@ async def async_hass_config_yaml(hass: HomeAssistant) -> dict:
for invalid_domain in invalid_domains: for invalid_domain in invalid_domains:
config.pop(invalid_domain) config.pop(invalid_domain)
core_config = config.get(CONF_CORE, {}) core_config = config.get(HA_DOMAIN, {})
try: try:
await merge_packages_config(hass, config, core_config.get(CONF_PACKAGES, {})) await merge_packages_config(hass, config, core_config.get(CONF_PACKAGES, {}))
except vol.Invalid as exc: except vol.Invalid as exc:
suffix = "" suffix = ""
if annotation := find_annotation(config, [CONF_CORE, CONF_PACKAGES, *exc.path]): if annotation := find_annotation(config, [HA_DOMAIN, CONF_PACKAGES, *exc.path]):
suffix = f" at {_relpath(hass, annotation[0])}, line {annotation[1]}" suffix = f" at {_relpath(hass, annotation[0])}, line {annotation[1]}"
_LOGGER.error( _LOGGER.error(
"Invalid package configuration '%s'%s: %s", CONF_PACKAGES, suffix, exc "Invalid package configuration '%s'%s: %s", CONF_PACKAGES, suffix, exc
@ -731,7 +731,7 @@ def stringify_invalid(
) )
else: else:
message_prefix = f"Invalid config for '{domain}'" message_prefix = f"Invalid config for '{domain}'"
if domain != CONF_CORE and link: if domain != HA_DOMAIN and link:
message_suffix = f", please check the docs at {link}" message_suffix = f", please check the docs at {link}"
else: else:
message_suffix = "" message_suffix = ""
@ -814,7 +814,7 @@ def format_homeassistant_error(
if annotation := find_annotation(config, [domain]): if annotation := find_annotation(config, [domain]):
message_prefix += f" at {_relpath(hass, annotation[0])}, line {annotation[1]}" message_prefix += f" at {_relpath(hass, annotation[0])}, line {annotation[1]}"
message = f"{message_prefix}: {str(exc) or repr(exc)}" message = f"{message_prefix}: {str(exc) or repr(exc)}"
if domain != CONF_CORE and link: if domain != HA_DOMAIN and link:
message += f", please check the docs at {link}" message += f", please check the docs at {link}"
return message return message
@ -933,7 +933,7 @@ async def async_process_ha_core_config(hass: HomeAssistant, config: dict) -> Non
cust_glob = OrderedDict(config[CONF_CUSTOMIZE_GLOB]) cust_glob = OrderedDict(config[CONF_CUSTOMIZE_GLOB])
for name, pkg in config[CONF_PACKAGES].items(): for name, pkg in config[CONF_PACKAGES].items():
if (pkg_cust := pkg.get(CONF_CORE)) is None: if (pkg_cust := pkg.get(HA_DOMAIN)) is None:
continue continue
try: try:
@ -957,7 +957,7 @@ def _log_pkg_error(
) -> None: ) -> None:
"""Log an error while merging packages.""" """Log an error while merging packages."""
message_prefix = f"Setup of package '{package}'" message_prefix = f"Setup of package '{package}'"
if annotation := find_annotation(config, [CONF_CORE, CONF_PACKAGES, package]): if annotation := find_annotation(config, [HA_DOMAIN, CONF_PACKAGES, package]):
message_prefix += f" at {_relpath(hass, annotation[0])}, line {annotation[1]}" message_prefix += f" at {_relpath(hass, annotation[0])}, line {annotation[1]}"
_LOGGER.error("%s failed: %s", message_prefix, message) _LOGGER.error("%s failed: %s", message_prefix, message)
@ -1072,7 +1072,7 @@ async def merge_packages_config(
continue continue
for comp_name, comp_conf in pack_conf.items(): for comp_name, comp_conf in pack_conf.items():
if comp_name == CONF_CORE: if comp_name == HA_DOMAIN:
continue continue
try: try:
domain = cv.domain_key(comp_name) domain = cv.domain_key(comp_name)
@ -1305,7 +1305,7 @@ def async_drop_config_annotations(
# Don't drop annotations from the homeassistant integration because it may # Don't drop annotations from the homeassistant integration because it may
# have configuration for other integrations as packages. # have configuration for other integrations as packages.
if integration.domain in config and integration.domain != CONF_CORE: if integration.domain in config and integration.domain != HA_DOMAIN:
drop_config_annotations_rec(config[integration.domain]) drop_config_annotations_rec(config[integration.domain])
return config return config

View File

@ -12,7 +12,6 @@ import voluptuous as vol
from homeassistant import loader from homeassistant import loader
from homeassistant.config import ( # type: ignore[attr-defined] from homeassistant.config import ( # type: ignore[attr-defined]
CONF_CORE,
CONF_PACKAGES, CONF_PACKAGES,
CORE_CONFIG_SCHEMA, CORE_CONFIG_SCHEMA,
YAML_CONFIG_FILE, YAML_CONFIG_FILE,
@ -23,7 +22,7 @@ from homeassistant.config import ( # type: ignore[attr-defined]
load_yaml_config_file, load_yaml_config_file,
merge_packages_config, merge_packages_config,
) )
from homeassistant.core import HomeAssistant from homeassistant.core import DOMAIN as HA_DOMAIN, HomeAssistant
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.requirements import ( from homeassistant.requirements import (
RequirementsNotFound, RequirementsNotFound,
@ -158,10 +157,10 @@ async def async_check_ha_config_file( # noqa: C901
return result.add_error(f"Error loading {config_path}: {err}") return result.add_error(f"Error loading {config_path}: {err}")
# Extract and validate core [homeassistant] config # Extract and validate core [homeassistant] config
core_config = config.pop(CONF_CORE, {}) core_config = config.pop(HA_DOMAIN, {})
try: try:
core_config = CORE_CONFIG_SCHEMA(core_config) core_config = CORE_CONFIG_SCHEMA(core_config)
result[CONF_CORE] = core_config result[HA_DOMAIN] = core_config
# Merge packages # Merge packages
await merge_packages_config( await merge_packages_config(
@ -169,8 +168,8 @@ async def async_check_ha_config_file( # noqa: C901
) )
except vol.Invalid as err: except vol.Invalid as err:
result.add_error( result.add_error(
format_schema_error(hass, err, CONF_CORE, core_config), format_schema_error(hass, err, HA_DOMAIN, core_config),
CONF_CORE, HA_DOMAIN,
core_config, core_config,
) )
core_config = {} core_config = {}

View File

@ -4,13 +4,15 @@ from __future__ import annotations
import ast import ast
from homeassistant.core import DOMAIN as HA_DOMAIN
from .model import Config, Integration from .model import Config, Integration
CONFIG_SCHEMA_IGNORE = { CONFIG_SCHEMA_IGNORE = {
# Configuration under the homeassistant key is a special case, it's handled by # Configuration under the homeassistant key is a special case, it's handled by
# conf_util.async_process_ha_core_config already during bootstrapping, not by # conf_util.async_process_ha_core_config already during bootstrapping, not by
# a schema in the homeassistant integration. # a schema in the homeassistant integration.
"homeassistant", HA_DOMAIN,
} }

View File

@ -468,7 +468,7 @@ async def test_config_schema_via_packages(hass: HomeAssistant) -> None:
"pack_11": {"rest": {"resource": "http://url1"}}, "pack_11": {"rest": {"resource": "http://url1"}},
"pack_list": {"rest": [{"resource": "http://url2"}]}, "pack_list": {"rest": [{"resource": "http://url2"}]},
} }
config = {hass_config.CONF_CORE: {hass_config.CONF_PACKAGES: packages}} config = {hass_config.HA_DOMAIN: {hass_config.CONF_PACKAGES: packages}}
await hass_config.merge_packages_config(hass, config, packages) await hass_config.merge_packages_config(hass, config, packages)
assert len(config) == 2 assert len(config) == 2

View File

@ -32,7 +32,12 @@ from homeassistant.const import (
CONF_UNIT_SYSTEM_METRIC, CONF_UNIT_SYSTEM_METRIC,
__version__, __version__,
) )
from homeassistant.core import ConfigSource, HomeAssistant, HomeAssistantError from homeassistant.core import (
DOMAIN as HA_DOMAIN,
ConfigSource,
HomeAssistant,
HomeAssistantError,
)
from homeassistant.exceptions import ConfigValidationError from homeassistant.exceptions import ConfigValidationError
from homeassistant.helpers import config_validation as cv, issue_registry as ir from homeassistant.helpers import config_validation as cv, issue_registry as ir
import homeassistant.helpers.check_config as check_config import homeassistant.helpers.check_config as check_config
@ -1041,7 +1046,7 @@ async def test_check_ha_config_file_wrong(mock_check, hass: HomeAssistant) -> No
"hass_config", "hass_config",
[ [
{ {
config_util.CONF_CORE: { HA_DOMAIN: {
config_util.CONF_PACKAGES: { config_util.CONF_PACKAGES: {
"pack_dict": {"input_boolean": {"ib1": None}} "pack_dict": {"input_boolean": {"ib1": None}}
} }
@ -1058,7 +1063,7 @@ async def test_async_hass_config_yaml_merge(
conf = await config_util.async_hass_config_yaml(hass) conf = await config_util.async_hass_config_yaml(hass)
assert merge_log_err.call_count == 0 assert merge_log_err.call_count == 0
assert conf[config_util.CONF_CORE].get(config_util.CONF_PACKAGES) is not None assert conf[HA_DOMAIN].get(config_util.CONF_PACKAGES) is not None
assert len(conf) == 3 assert len(conf) == 3
assert len(conf["input_boolean"]) == 2 assert len(conf["input_boolean"]) == 2
assert len(conf["light"]) == 1 assert len(conf["light"]) == 1
@ -1086,7 +1091,7 @@ async def test_merge(merge_log_err, hass: HomeAssistant) -> None:
}, },
} }
config = { config = {
config_util.CONF_CORE: {config_util.CONF_PACKAGES: packages}, HA_DOMAIN: {config_util.CONF_PACKAGES: packages},
"input_boolean": {"ib2": None}, "input_boolean": {"ib2": None},
"light": {"platform": "test"}, "light": {"platform": "test"},
"automation": [], "automation": [],
@ -1113,7 +1118,7 @@ async def test_merge_try_falsy(merge_log_err, hass: HomeAssistant) -> None:
"pack_list2": {"light": OrderedDict()}, "pack_list2": {"light": OrderedDict()},
} }
config = { config = {
config_util.CONF_CORE: {config_util.CONF_PACKAGES: packages}, HA_DOMAIN: {config_util.CONF_PACKAGES: packages},
"automation": {"do": "something"}, "automation": {"do": "something"},
"light": {"some": "light"}, "light": {"some": "light"},
} }
@ -1136,7 +1141,7 @@ async def test_merge_new(merge_log_err, hass: HomeAssistant) -> None:
"api": {}, "api": {},
}, },
} }
config = {config_util.CONF_CORE: {config_util.CONF_PACKAGES: packages}} config = {HA_DOMAIN: {config_util.CONF_PACKAGES: packages}}
await config_util.merge_packages_config(hass, config, packages) await config_util.merge_packages_config(hass, config, packages)
assert merge_log_err.call_count == 0 assert merge_log_err.call_count == 0
@ -1154,7 +1159,7 @@ async def test_merge_type_mismatch(merge_log_err, hass: HomeAssistant) -> None:
"pack_2": {"light": {"ib1": None}}, # light gets merged - ensure_list "pack_2": {"light": {"ib1": None}}, # light gets merged - ensure_list
} }
config = { config = {
config_util.CONF_CORE: {config_util.CONF_PACKAGES: packages}, HA_DOMAIN: {config_util.CONF_PACKAGES: packages},
"input_boolean": {"ib2": None}, "input_boolean": {"ib2": None},
"input_select": [{"ib2": None}], "input_select": [{"ib2": None}],
"light": [{"platform": "two"}], "light": [{"platform": "two"}],
@ -1170,13 +1175,13 @@ async def test_merge_type_mismatch(merge_log_err, hass: HomeAssistant) -> None:
async def test_merge_once_only_keys(merge_log_err, hass: HomeAssistant) -> None: async def test_merge_once_only_keys(merge_log_err, hass: HomeAssistant) -> None:
"""Test if we have a merge for a comp that may occur only once. Keys.""" """Test if we have a merge for a comp that may occur only once. Keys."""
packages = {"pack_2": {"api": None}} packages = {"pack_2": {"api": None}}
config = {config_util.CONF_CORE: {config_util.CONF_PACKAGES: packages}, "api": None} config = {HA_DOMAIN: {config_util.CONF_PACKAGES: packages}, "api": None}
await config_util.merge_packages_config(hass, config, packages) await config_util.merge_packages_config(hass, config, packages)
assert config["api"] == OrderedDict() assert config["api"] == OrderedDict()
packages = {"pack_2": {"api": {"key_3": 3}}} packages = {"pack_2": {"api": {"key_3": 3}}}
config = { config = {
config_util.CONF_CORE: {config_util.CONF_PACKAGES: packages}, HA_DOMAIN: {config_util.CONF_PACKAGES: packages},
"api": {"key_1": 1, "key_2": 2}, "api": {"key_1": 1, "key_2": 2},
} }
await config_util.merge_packages_config(hass, config, packages) await config_util.merge_packages_config(hass, config, packages)
@ -1185,7 +1190,7 @@ async def test_merge_once_only_keys(merge_log_err, hass: HomeAssistant) -> None:
# Duplicate keys error # Duplicate keys error
packages = {"pack_2": {"api": {"key": 2}}} packages = {"pack_2": {"api": {"key": 2}}}
config = { config = {
config_util.CONF_CORE: {config_util.CONF_PACKAGES: packages}, HA_DOMAIN: {config_util.CONF_PACKAGES: packages},
"api": {"key": 1}, "api": {"key": 1},
} }
await config_util.merge_packages_config(hass, config, packages) await config_util.merge_packages_config(hass, config, packages)
@ -1200,7 +1205,7 @@ async def test_merge_once_only_lists(hass: HomeAssistant) -> None:
} }
} }
config = { config = {
config_util.CONF_CORE: {config_util.CONF_PACKAGES: packages}, HA_DOMAIN: {config_util.CONF_PACKAGES: packages},
"api": {"list_1": ["item_1"]}, "api": {"list_1": ["item_1"]},
} }
await config_util.merge_packages_config(hass, config, packages) await config_util.merge_packages_config(hass, config, packages)
@ -1223,7 +1228,7 @@ async def test_merge_once_only_dictionaries(hass: HomeAssistant) -> None:
} }
} }
config = { config = {
config_util.CONF_CORE: {config_util.CONF_PACKAGES: packages}, HA_DOMAIN: {config_util.CONF_PACKAGES: packages},
"api": {"dict_1": {"key_1": 1, "dict_1.1": {"key_1.1": 1.1}}}, "api": {"dict_1": {"key_1": 1, "dict_1.1": {"key_1.1": 1.1}}},
} }
await config_util.merge_packages_config(hass, config, packages) await config_util.merge_packages_config(hass, config, packages)
@ -1257,7 +1262,7 @@ async def test_merge_duplicate_keys(merge_log_err, hass: HomeAssistant) -> None:
"""Test if keys in dicts are duplicates.""" """Test if keys in dicts are duplicates."""
packages = {"pack_1": {"input_select": {"ib1": None}}} packages = {"pack_1": {"input_select": {"ib1": None}}}
config = { config = {
config_util.CONF_CORE: {config_util.CONF_PACKAGES: packages}, HA_DOMAIN: {config_util.CONF_PACKAGES: packages},
"input_select": {"ib1": 1}, "input_select": {"ib1": 1},
} }
await config_util.merge_packages_config(hass, config, packages) await config_util.merge_packages_config(hass, config, packages)
@ -1417,7 +1422,7 @@ async def test_merge_split_component_definition(hass: HomeAssistant) -> None:
"pack_1": {"light one": {"l1": None}}, "pack_1": {"light one": {"l1": None}},
"pack_2": {"light two": {"l2": None}, "light three": {"l3": None}}, "pack_2": {"light two": {"l2": None}, "light three": {"l3": None}},
} }
config = {config_util.CONF_CORE: {config_util.CONF_PACKAGES: packages}} config = {HA_DOMAIN: {config_util.CONF_PACKAGES: packages}}
await config_util.merge_packages_config(hass, config, packages) await config_util.merge_packages_config(hass, config, packages)
assert len(config) == 4 assert len(config) == 4
@ -2308,7 +2313,7 @@ async def test_packages_schema_validation_error(
] ]
assert error_records == snapshot assert error_records == snapshot
assert len(config[config_util.CONF_CORE][config_util.CONF_PACKAGES]) == 0 assert len(config[HA_DOMAIN][config_util.CONF_PACKAGES]) == 0
def test_extract_domain_configs() -> None: def test_extract_domain_configs() -> None: