Skip to content

Commit

Permalink
Add a cache to is_safe (#3657)
Browse files Browse the repository at this point in the history
* Add a cache to is_safe

fixes #3540

* lint

* config is not frozen

---------

Co-authored-by: Joakim Sørensen <[email protected]>
  • Loading branch information
bdraco and ludeeus authored May 7, 2024
1 parent 4a38aa7 commit 9a0e0ba
Showing 1 changed file with 31 additions and 9 deletions.
40 changes: 31 additions & 9 deletions custom_components/hacs/utils/path.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,43 @@
"""Path utils"""
from __future__ import annotations

from functools import lru_cache
from pathlib import Path
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from ..base import HacsBase
from ..base import HacsBase, HacsConfiguration


@lru_cache(maxsize=1)
def _get_safe_paths(
config_path: str,
appdaemon_path: str,
netdaemon_path: str,
plugin_path: str,
python_script_path: str,
theme_path: str,
) -> set[str]:
"""Get safe paths."""
return {
Path(f"{config_path}/{appdaemon_path}").as_posix(),
Path(f"{config_path}/{netdaemon_path}").as_posix(),
Path(f"{config_path}/{plugin_path}").as_posix(),
Path(f"{config_path}/{python_script_path}").as_posix(),
Path(f"{config_path}/{theme_path}").as_posix(),
Path(f"{config_path}/custom_components/").as_posix(),
Path(f"{config_path}/custom_templates/").as_posix(),
}


def is_safe(hacs: HacsBase, path: str | Path) -> bool:
"""Helper to check if path is safe to remove."""
return Path(path).as_posix() not in (
Path(f"{hacs.core.config_path}/{hacs.configuration.appdaemon_path}").as_posix(),
Path(f"{hacs.core.config_path}/{hacs.configuration.netdaemon_path}").as_posix(),
Path(f"{hacs.core.config_path}/{hacs.configuration.plugin_path}").as_posix(),
Path(f"{hacs.core.config_path}/{hacs.configuration.python_script_path}").as_posix(),
Path(f"{hacs.core.config_path}/{hacs.configuration.theme_path}").as_posix(),
Path(f"{hacs.core.config_path}/custom_components/").as_posix(),
Path(f"{hacs.core.config_path}/custom_templates/").as_posix(),
configuration = hacs.configuration
return Path(path).as_posix() not in _get_safe_paths(
hacs.core.config_path,
configuration.appdaemon_path,
configuration.netdaemon_path,
configuration.plugin_path,
configuration.python_script_path,
configuration.theme_path,
)

0 comments on commit 9a0e0ba

Please sign in to comment.