Skip to content

Commit

Permalink
feat: Safer config entries migrations
Browse files Browse the repository at this point in the history
  • Loading branch information
davidrapan committed Dec 9, 2024
1 parent 8a39e38 commit 4f20b5c
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 6 deletions.
4 changes: 2 additions & 2 deletions custom_components/solarman/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,8 @@ async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry) ->
bulk_migrate(new_data, new_data, OLD_)
bulk_migrate(new_options, new_options, OLD_)
bulk_inherit(new_options.setdefault(CONF_ADDITIONAL_OPTIONS, {}), new_options, CONF_BATTERY_NOMINAL_VOLTAGE, CONF_BATTERY_LIFE_CYCLE_RATING)
bulk_delete(new_data, OLD_[CONF_SERIAL])
bulk_delete(new_options, OLD_[CONF_SERIAL], OLD_[CONF_HOST], OLD_[CONF_PORT], CONF_BATTERY_NOMINAL_VOLTAGE, CONF_BATTERY_LIFE_CYCLE_RATING)
bulk_safe_delete(new_data, OLD_)
bulk_safe_delete(new_options, OLD_ | to_dict(CONF_BATTERY_NOMINAL_VOLTAGE, CONF_BATTERY_LIFE_CYCLE_RATING))

if not new_options.get(CONF_ADDITIONAL_OPTIONS):
del new_options[CONF_ADDITIONAL_OPTIONS]
Expand Down
14 changes: 11 additions & 3 deletions custom_components/solarman/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ def execute_async(x):
loop = asyncio.get_event_loop()
return loop.run_until_complete(x)

def to_dict(*keys: list):
return {k: k for k in keys}

def filter_by_keys(source: dict, keys: dict | list) -> dict:
return {k: source[k] for k in source.keys() if k in keys}

Expand All @@ -51,9 +54,14 @@ def bulk_migrate(target: dict, source: dict, redirect: dict):
target[k] = v
return target

def bulk_delete(source: dict[Any, Any], *keys: list[Any]):
for k in source.keys() & keys:
del source[k]
def bulk_delete(target: dict[Any, Any], *keys: list[Any]):
for k in target.keys() & keys:
del target[k]

def bulk_safe_delete(target: dict[Any, Any], redirect: dict):
for k in target.keys() & redirect.keys():
if redirect[k] in target:
del target[redirect[k]]

def ensure_list(value):
return value if isinstance(value, list) else [value]
Expand Down
2 changes: 1 addition & 1 deletion custom_components/solarman/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def remove_defaults(user_input: dict[str, Any]):
return user_input

class ConfigFlowHandler(ConfigFlow, domain = DOMAIN):
MINOR_VERSION = 4
MINOR_VERSION = 5
VERSION = 1

async def async_step_user(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult:
Expand Down

0 comments on commit 4f20b5c

Please sign in to comment.