Update usage of async_entries to use _async_current_entries (#50187)

pull/50483/head^2
J. Nick Koston 2021-05-12 05:47:06 -05:00 committed by GitHub
parent c3eee9800a
commit a4ea9b3cd3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
28 changed files with 40 additions and 67 deletions

View File

@ -19,7 +19,7 @@ class AwairFlowHandler(ConfigFlow, domain=DOMAIN):
async def async_step_import(self, conf: dict): async def async_step_import(self, conf: dict):
"""Import a configuration from config.yaml.""" """Import a configuration from config.yaml."""
if self.hass.config_entries.async_entries(DOMAIN): if self._async_current_entries():
return self.async_abort(reason="already_setup") return self.async_abort(reason="already_setup")
user, error = await self._check_connection(conf[CONF_ACCESS_TOKEN]) user, error = await self._check_connection(conf[CONF_ACCESS_TOKEN])

View File

@ -91,7 +91,7 @@ class BleBoxConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
addr = host_port(user_input) addr = host_port(user_input)
for entry in hass.config_entries.async_entries(DOMAIN): for entry in self._async_current_entries():
if addr == host_port(entry.data): if addr == host_port(entry.data):
host, port = addr host, port = addr
return self.async_abort( return self.async_abort(

View File

@ -23,7 +23,7 @@ class DynaliteFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Import a new bridge as a config entry.""" """Import a new bridge as a config entry."""
LOGGER.debug("Starting async_step_import - %s", import_info) LOGGER.debug("Starting async_step_import - %s", import_info)
host = import_info[CONF_HOST] host = import_info[CONF_HOST]
for entry in self.hass.config_entries.async_entries(DOMAIN): for entry in self._async_current_entries():
if entry.data[CONF_HOST] == host: if entry.data[CONF_HOST] == host:
if entry.data != import_info: if entry.data != import_info:
self.hass.config_entries.async_update_entry(entry, data=import_info) self.hass.config_entries.async_update_entry(entry, data=import_info)

View File

@ -128,7 +128,7 @@ class FritzboxConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
return self.async_abort(reason="already_in_progress") return self.async_abort(reason="already_in_progress")
# update old and user-configured config entries # update old and user-configured config entries
for entry in self.hass.config_entries.async_entries(DOMAIN): for entry in self._async_current_entries():
if entry.data[CONF_HOST] == host: if entry.data[CONF_HOST] == host:
if uuid and not entry.unique_id: if uuid and not entry.unique_id:
self.hass.config_entries.async_update_entry(entry, unique_id=uuid) self.hass.config_entries.async_update_entry(entry, unique_id=uuid)

View File

@ -43,10 +43,6 @@ DATA_SCHEMA = vol.Schema(
async def validate_input(hass: core.HomeAssistant, data): async def validate_input(hass: core.HomeAssistant, data):
"""Validate the user input allows us to connect.""" """Validate the user input allows us to connect."""
for entry in hass.config_entries.async_entries(DOMAIN):
if entry.data[CONF_HOST] == data[CONF_HOST]:
raise AlreadyConfigured
if data[CONF_VERSION] not in SUPPORTED_VERSIONS: if data[CONF_VERSION] not in SUPPORTED_VERSIONS:
raise WrongVersion raise WrongVersion
try: try:
@ -71,13 +67,12 @@ class GlancesFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle the initial step.""" """Handle the initial step."""
errors = {} errors = {}
if user_input is not None: if user_input is not None:
self._async_abort_entries_match({CONF_HOST: user_input[CONF_HOST]})
try: try:
await validate_input(self.hass, user_input) await validate_input(self.hass, user_input)
return self.async_create_entry( return self.async_create_entry(
title=user_input[CONF_NAME], data=user_input title=user_input[CONF_NAME], data=user_input
) )
except AlreadyConfigured:
return self.async_abort(reason="already_configured")
except CannotConnect: except CannotConnect:
errors["base"] = "cannot_connect" errors["base"] = "cannot_connect"
except WrongVersion: except WrongVersion:
@ -121,9 +116,5 @@ class CannotConnect(exceptions.HomeAssistantError):
"""Error to indicate we cannot connect.""" """Error to indicate we cannot connect."""
class AlreadyConfigured(exceptions.HomeAssistantError):
"""Error to indicate host is already configured."""
class WrongVersion(exceptions.HomeAssistantError): class WrongVersion(exceptions.HomeAssistantError):
"""Error to indicate the selected version is wrong.""" """Error to indicate the selected version is wrong."""

View File

@ -15,7 +15,7 @@ from .const import (
DEFAULT_RECONNECT_INTERVAL, DEFAULT_RECONNECT_INTERVAL,
DOMAIN, DOMAIN,
) )
from .errors import AlreadyConfigured, CannotConnect from .errors import CannotConnect
DATA_SCHEMA = vol.Schema( DATA_SCHEMA = vol.Schema(
{ {
@ -40,13 +40,6 @@ async def connect_client(hass, user_input):
async def validate_input(hass: HomeAssistant, user_input): async def validate_input(hass: HomeAssistant, user_input):
"""Validate the user input allows us to connect.""" """Validate the user input allows us to connect."""
for entry in hass.config_entries.async_entries(DOMAIN):
if (
entry.data[CONF_HOST] == user_input[CONF_HOST]
and entry.data[CONF_PORT] == user_input[CONF_PORT]
):
raise AlreadyConfigured
try: try:
client = await connect_client(hass, user_input) client = await connect_client(hass, user_input)
except asyncio.TimeoutError as err: except asyncio.TimeoutError as err:
@ -81,12 +74,13 @@ class SW16FlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle the initial step.""" """Handle the initial step."""
errors = {} errors = {}
if user_input is not None: if user_input is not None:
self._async_abort_entries_match(
{CONF_HOST: user_input[CONF_HOST], CONF_PORT: user_input[CONF_PORT]}
)
try: try:
await validate_input(self.hass, user_input) await validate_input(self.hass, user_input)
address = f"{user_input[CONF_HOST]}:{user_input[CONF_PORT]}" address = f"{user_input[CONF_HOST]}:{user_input[CONF_PORT]}"
return self.async_create_entry(title=address, data=user_input) return self.async_create_entry(title=address, data=user_input)
except AlreadyConfigured:
errors["base"] = "already_configured"
except CannotConnect: except CannotConnect:
errors["base"] = "cannot_connect" errors["base"] = "cannot_connect"

View File

@ -6,9 +6,5 @@ class SW16Exception(HomeAssistantError):
"""Base class for HLK-SW16 exceptions.""" """Base class for HLK-SW16 exceptions."""
class AlreadyConfigured(SW16Exception):
"""HLK-SW16 is already configured."""
class CannotConnect(SW16Exception): class CannotConnect(SW16Exception):
"""Unable to connect to the HLK-SW16.""" """Unable to connect to the HLK-SW16."""

View File

@ -19,7 +19,7 @@ class AqualinkFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
async def async_step_user(self, user_input: ConfigType | None = None): async def async_step_user(self, user_input: ConfigType | None = None):
"""Handle a flow start.""" """Handle a flow start."""
# Supporting a single account. # Supporting a single account.
entries = self.hass.config_entries.async_entries(DOMAIN) entries = self._async_current_entries()
if entries: if entries:
return self.async_abort(reason="single_instance_allowed") return self.async_abort(reason="single_instance_allowed")

View File

@ -30,7 +30,7 @@ class Life360ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
@property @property
def configured_usernames(self): def configured_usernames(self):
"""Return tuple of configured usernames.""" """Return tuple of configured usernames."""
entries = self.hass.config_entries.async_entries(DOMAIN) entries = self._async_current_entries()
if entries: if entries:
return (entry.data[CONF_USERNAME] for entry in entries) return (entry.data[CONF_USERNAME] for entry in entries)
return () return ()

View File

@ -24,7 +24,7 @@ class LiteJetConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
self, user_input: dict[str, Any] | None = None self, user_input: dict[str, Any] | None = None
) -> FlowResult: ) -> FlowResult:
"""Create a LiteJet config entry based upon user input.""" """Create a LiteJet config entry based upon user input."""
if self.hass.config_entries.async_entries(DOMAIN): if self._async_current_entries():
return self.async_abort(reason="single_instance_allowed") return self.async_abort(reason="single_instance_allowed")
errors = {} errors = {}

View File

@ -95,7 +95,7 @@ class LogiCircleFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
async def async_step_auth(self, user_input=None): async def async_step_auth(self, user_input=None):
"""Create an entry for auth.""" """Create an entry for auth."""
if self.hass.config_entries.async_entries(DOMAIN): if self._async_current_entries():
return self.async_abort(reason="external_setup") return self.async_abort(reason="external_setup")
external_error = self.hass.data[DATA_FLOW_IMPL][DOMAIN][EXTERNAL_ERRORS] external_error = self.hass.data[DATA_FLOW_IMPL][DOMAIN][EXTERNAL_ERRORS]

View File

@ -40,7 +40,7 @@ class MikrotikFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a flow initialized by the user.""" """Handle a flow initialized by the user."""
errors = {} errors = {}
if user_input is not None: if user_input is not None:
for entry in self.hass.config_entries.async_entries(DOMAIN): for entry in self._async_current_entries():
if entry.data[CONF_HOST] == user_input[CONF_HOST]: if entry.data[CONF_HOST] == user_input[CONF_HOST]:
return self.async_abort(reason="already_configured") return self.async_abort(reason="already_configured")
if entry.data[CONF_NAME] == user_input[CONF_NAME]: if entry.data[CONF_NAME] == user_input[CONF_NAME]:

View File

@ -218,7 +218,7 @@ class MySensorsConfigFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
return self.async_show_form(step_id="gw_tcp", data_schema=schema, errors=errors) return self.async_show_form(step_id="gw_tcp", data_schema=schema, errors=errors)
def _check_topic_exists(self, topic: str) -> bool: def _check_topic_exists(self, topic: str) -> bool:
for other_config in self.hass.config_entries.async_entries(DOMAIN): for other_config in self._async_current_entries():
if topic == other_config.data.get( if topic == other_config.data.get(
CONF_TOPIC_IN_PREFIX CONF_TOPIC_IN_PREFIX
) or topic == other_config.data.get(CONF_TOPIC_OUT_PREFIX): ) or topic == other_config.data.get(CONF_TOPIC_OUT_PREFIX):
@ -329,7 +329,7 @@ class MySensorsConfigFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
] = self._normalize_persistence_file( ] = self._normalize_persistence_file(
user_input[CONF_PERSISTENCE_FILE] user_input[CONF_PERSISTENCE_FILE]
) )
for other_entry in self.hass.config_entries.async_entries(DOMAIN): for other_entry in self._async_current_entries():
if CONF_PERSISTENCE_FILE not in other_entry.data: if CONF_PERSISTENCE_FILE not in other_entry.data:
continue continue
if real_persistence_path == self._normalize_persistence_file( if real_persistence_path == self._normalize_persistence_file(
@ -338,7 +338,7 @@ class MySensorsConfigFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
errors[CONF_PERSISTENCE_FILE] = "duplicate_persistence_file" errors[CONF_PERSISTENCE_FILE] = "duplicate_persistence_file"
break break
for other_entry in self.hass.config_entries.async_entries(DOMAIN): for other_entry in self._async_current_entries():
if _is_same_device(gw_type, user_input, other_entry): if _is_same_device(gw_type, user_input, other_entry):
errors["base"] = "already_configured" errors["base"] = "already_configured"
break break

View File

@ -112,7 +112,7 @@ class NestFlowHandler(
# Update existing config entry when in the reauth flow. This # Update existing config entry when in the reauth flow. This
# integration only supports one config entry so remove any prior entries # integration only supports one config entry so remove any prior entries
# added before the "single_instance_allowed" check was added # added before the "single_instance_allowed" check was added
existing_entries = self.hass.config_entries.async_entries(DOMAIN) existing_entries = self._async_current_entries()
if existing_entries: if existing_entries:
updated = False updated = False
for entry in existing_entries: for entry in existing_entries:
@ -148,7 +148,7 @@ class NestFlowHandler(
"""Handle a flow initialized by the user.""" """Handle a flow initialized by the user."""
if self.is_sdm_api(): if self.is_sdm_api():
# Reauth will update an existing entry # Reauth will update an existing entry
if self.hass.config_entries.async_entries(DOMAIN) and not self._reauth: if self._async_current_entries() and not self._reauth:
return self.async_abort(reason="single_instance_allowed") return self.async_abort(reason="single_instance_allowed")
return await super().async_step_user(user_input) return await super().async_step_user(user_input)
return await self.async_step_init(user_input) return await self.async_step_init(user_input)
@ -159,7 +159,7 @@ class NestFlowHandler(
flows = self.hass.data.get(DATA_FLOW_IMPL, {}) flows = self.hass.data.get(DATA_FLOW_IMPL, {})
if self.hass.config_entries.async_entries(DOMAIN): if self._async_current_entries():
return self.async_abort(reason="single_instance_allowed") return self.async_abort(reason="single_instance_allowed")
if not flows: if not flows:
@ -229,7 +229,7 @@ class NestFlowHandler(
"""Import existing auth from Nest.""" """Import existing auth from Nest."""
assert not self.is_sdm_api(), "Step only supported for legacy API" assert not self.is_sdm_api(), "Step only supported for legacy API"
if self.hass.config_entries.async_entries(DOMAIN): if self._async_current_entries():
return self.async_abort(reason="single_instance_allowed") return self.async_abort(reason="single_instance_allowed")
config_path = info["nest_conf_path"] config_path = info["nest_conf_path"]

View File

@ -29,7 +29,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle the initial step.""" """Handle the initial step."""
errors = {} errors = {}
config_entry = self.hass.config_entries.async_entries(DOMAIN) config_entry = self._async_current_entries()
if config_entry: if config_entry:
return self.async_abort(reason="single_instance_allowed") return self.async_abort(reason="single_instance_allowed")

View File

@ -45,7 +45,7 @@ class OpenThermGwConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
device = info[CONF_DEVICE] device = info[CONF_DEVICE]
gw_id = cv.slugify(info.get(CONF_ID, name)) gw_id = cv.slugify(info.get(CONF_ID, name))
entries = [e.data for e in self.hass.config_entries.async_entries(DOMAIN)] entries = [e.data for e in self._async_current_entries()]
if gw_id in [e[CONF_ID] for e in entries]: if gw_id in [e[CONF_ID] for e in entries]:
return self._show_form({"base": "id_exists"}) return self._show_form({"base": "id_exists"})

View File

@ -51,7 +51,7 @@ class PointFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
async def async_step_import(self, user_input=None): async def async_step_import(self, user_input=None):
"""Handle external yaml configuration.""" """Handle external yaml configuration."""
if self.hass.config_entries.async_entries(DOMAIN): if self._async_current_entries():
return self.async_abort(reason="already_setup") return self.async_abort(reason="already_setup")
self.flow_impl = DOMAIN self.flow_impl = DOMAIN
@ -62,7 +62,7 @@ class PointFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a flow start.""" """Handle a flow start."""
flows = self.hass.data.get(DATA_FLOW_IMPL, {}) flows = self.hass.data.get(DATA_FLOW_IMPL, {})
if self.hass.config_entries.async_entries(DOMAIN): if self._async_current_entries():
return self.async_abort(reason="already_setup") return self.async_abort(reason="already_setup")
if not flows: if not flows:
@ -84,7 +84,7 @@ class PointFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
async def async_step_auth(self, user_input=None): async def async_step_auth(self, user_input=None):
"""Create an entry for auth.""" """Create an entry for auth."""
if self.hass.config_entries.async_entries(DOMAIN): if self._async_current_entries():
return self.async_abort(reason="external_setup") return self.async_abort(reason="external_setup")
errors = {} errors = {}
@ -123,7 +123,7 @@ class PointFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
async def async_step_code(self, code=None): async def async_step_code(self, code=None):
"""Received code for authentication.""" """Received code for authentication."""
if self.hass.config_entries.async_entries(DOMAIN): if self._async_current_entries():
return self.async_abort(reason="already_setup") return self.async_abort(reason="already_setup")
if code is None: if code is None:

View File

@ -118,7 +118,7 @@ class PlayStation4FlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
self.device_list = [device["host-ip"] for device in devices] self.device_list = [device["host-ip"] for device in devices]
# Check that devices found aren't configured per account. # Check that devices found aren't configured per account.
entries = self.hass.config_entries.async_entries(DOMAIN) entries = self._async_current_entries()
if entries: if entries:
# Retrieve device data from all entries if creds match. # Retrieve device data from all entries if creds match.
conf_devices = [ conf_devices = [

View File

@ -59,6 +59,6 @@ class SomaFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
async def async_step_import(self, user_input=None): async def async_step_import(self, user_input=None):
"""Handle flow start from existing config section.""" """Handle flow start from existing config section."""
if self.hass.config_entries.async_entries(DOMAIN): if self._async_current_entries():
return self.async_abort(reason="already_setup") return self.async_abort(reason="already_setup")
return await self.async_step_creation(user_input) return await self.async_step_creation(user_input)

View File

@ -20,7 +20,7 @@ class SomfyFlowHandler(
async def async_step_user(self, user_input=None): async def async_step_user(self, user_input=None):
"""Handle a flow start.""" """Handle a flow start."""
if self.hass.config_entries.async_entries(DOMAIN): if self._async_current_entries():
return self.async_abort(reason="single_instance_allowed") return self.async_abort(reason="single_instance_allowed")
return await super().async_step_user(user_input) return await super().async_step_user(user_input)

View File

@ -53,7 +53,7 @@ class FlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
async def async_step_user(self, user_input=None): async def async_step_user(self, user_input=None):
"""Let user select host or cloud.""" """Let user select host or cloud."""
if self.hass.config_entries.async_entries(DOMAIN): if self._async_current_entries():
return self.async_abort(reason="already_setup") return self.async_abort(reason="already_setup")
if user_input is not None or len(self._hosts) == 1: if user_input is not None or len(self._hosts) == 1:
@ -125,7 +125,7 @@ class FlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
async def async_step_import(self, user_input): async def async_step_import(self, user_input):
"""Import a config entry.""" """Import a config entry."""
if self.hass.config_entries.async_entries(DOMAIN): if self._async_current_entries():
return self.async_abort(reason="already_setup") return self.async_abort(reason="already_setup")
self._scan_interval = user_input[KEY_SCAN_INTERVAL] self._scan_interval = user_input[KEY_SCAN_INTERVAL]

View File

@ -54,7 +54,7 @@ class TransmissionFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
if user_input is not None: if user_input is not None:
for entry in self.hass.config_entries.async_entries(DOMAIN): for entry in self._async_current_entries():
if ( if (
entry.data[CONF_HOST] == user_input[CONF_HOST] entry.data[CONF_HOST] == user_input[CONF_HOST]
and entry.data[CONF_PORT] == user_input[CONF_PORT] and entry.data[CONF_PORT] == user_input[CONF_PORT]

View File

@ -184,7 +184,7 @@ class UpnpFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
) )
# Handle devices changing their UDN, only allow a single # Handle devices changing their UDN, only allow a single
existing_entries = self.hass.config_entries.async_entries(DOMAIN) existing_entries = self._async_current_entries()
for config_entry in existing_entries: for config_entry in existing_entries:
entry_hostname = config_entry.data.get(CONFIG_ENTRY_HOSTNAME) entry_hostname = config_entry.data.get(CONFIG_ENTRY_HOSTNAME)
if entry_hostname == discovery[DISCOVERY_HOSTNAME]: if entry_hostname == discovery[DISCOVERY_HOSTNAME]:

View File

@ -10,7 +10,6 @@ from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.dispatcher import async_dispatcher_send
from .common import async_process_devices from .common import async_process_devices
from .config_flow import configured_instances
from .const import ( from .const import (
DOMAIN, DOMAIN,
SERVICE_UPDATE_DEVS, SERVICE_UPDATE_DEVS,
@ -46,7 +45,7 @@ async def async_setup(hass, config):
if conf is None: if conf is None:
return True return True
if not configured_instances(hass): if not hass.config_entries.async_entries(DOMAIN):
hass.async_create_task( hass.async_create_task(
hass.config_entries.flow.async_init( hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,

View File

@ -11,12 +11,6 @@ from homeassistant.core import callback
from .const import DOMAIN from .const import DOMAIN
@callback
def configured_instances(hass):
"""Return already configured instances."""
return hass.config_entries.async_entries(DOMAIN)
class VeSyncFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): class VeSyncFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow.""" """Handle a config flow."""
@ -45,7 +39,7 @@ class VeSyncFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
async def async_step_user(self, user_input=None): async def async_step_user(self, user_input=None):
"""Handle a flow start.""" """Handle a flow start."""
if configured_instances(self.hass): if self._async_current_entries():
return self.async_abort(reason="single_instance_allowed") return self.async_abort(reason="single_instance_allowed")
if not user_input: if not user_input:

View File

@ -278,7 +278,7 @@ class VizioConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
async def async_step_import(self, import_config: dict[str, Any]) -> FlowResult: async def async_step_import(self, import_config: dict[str, Any]) -> FlowResult:
"""Import a config entry from configuration.yaml.""" """Import a config entry from configuration.yaml."""
# Check if new config entry matches any existing config entries # Check if new config entry matches any existing config entries
for entry in self.hass.config_entries.async_entries(DOMAIN): for entry in self._async_current_entries():
# If source is ignore bypass host check and continue through loop # If source is ignore bypass host check and continue through loop
if entry.source == SOURCE_IGNORE: if entry.source == SOURCE_IGNORE:
continue continue

View File

@ -59,7 +59,7 @@ class WithingsFlowHandler(
if profile: if profile:
existing_entries = [ existing_entries = [
config_entry config_entry
for config_entry in self.hass.config_entries.async_entries(const.DOMAIN) for config_entry in self._async_current_entries()
if slugify(config_entry.data.get(const.PROFILE)) == slugify(profile) if slugify(config_entry.data.get(const.PROFILE)) == slugify(profile)
] ]

View File

@ -104,9 +104,8 @@ async def test_form(hass):
conf, conf,
) )
assert result4["type"] == "form" assert result4["type"] == "abort"
assert result4["errors"] == {"base": "already_configured"} assert result4["reason"] == "already_configured"
await hass.async_block_till_done()
async def test_import(hass): async def test_import(hass):