Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Change log messages in tasks #2330

Merged
merged 2 commits into from
Dec 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions custom_components/hacs/tasks/activate_categories.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ class Task(HacsTask):
stages = [HacsStage.SETUP]

async def async_execute(self) -> None:
"""Execute the task."""
self.hacs.common.categories = set()
for category in (HacsCategory.INTEGRATION, HacsCategory.PLUGIN):
self.hacs.enable_hacs_category(HacsCategory(category))
Expand Down
16 changes: 11 additions & 5 deletions custom_components/hacs/tasks/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

from datetime import timedelta
from logging import Handler
from timeit import default_timer as timer

from homeassistant.core import HomeAssistant
Expand All @@ -20,6 +21,7 @@ class HacsTask(LogMixin):
events: list[str] | None = None
schedule: timedelta | None = None
stages: list[HacsStage] | None = None
_can_run_disabled = False ## Set to True if task can run while disabled

def __init__(self, hacs: HacsBase, hass: HomeAssistant) -> None:
self.hacs = hacs
Expand All @@ -30,16 +32,20 @@ def slug(self) -> str:
"""Return the check slug."""
return self.__class__.__module__.rsplit(".", maxsplit=1)[-1]

def task_logger(self, handler: Handler, msg: str) -> None:
"""Log message from task"""
handler("HacsTask<%s> %s", self.slug, msg)

async def execute_task(self, *_, **__) -> None:
"""Execute the task defined in subclass."""
if self.hacs.system.disabled:
if not self._can_run_disabled and self.hacs.system.disabled:
self.log.warning(
"Skipping task %s, HACS is disabled - %s",
"HacsTask<%s> Skipping task, HACS is disabled - %s",
self.slug,
self.hacs.system.disabled_reason,
)
return
self.log.info("Executing task: %s", self.slug)
self.log.info("HacsTask<%s> Executing task", self.slug)
start_time = timer()

try:
Expand All @@ -48,11 +54,11 @@ async def execute_task(self, *_, **__) -> None:
elif task := getattr(self, "async_execute", None):
await task() # pylint: disable=not-callable
except BaseException as exception: # pylint: disable=broad-except
self.log.error("Task %s failed: %s", self.slug, exception)
self.log.error("HacsTask<%s> failed: %s", self.slug, exception)

else:
self.log.debug(
"Task %s took " "%.2f seconds to complete",
"HacsTask<%s> took " "%.2f seconds to complete",
self.slug,
timer() - start_time,
)
14 changes: 8 additions & 6 deletions custom_components/hacs/tasks/check_constrains.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,23 @@ class Task(HacsTask):
stages = [HacsStage.SETUP]

def execute(self) -> None:
"""Execute the task."""
for location in (
self.hass.config.path("custom_components/custom_updater.py"),
self.hass.config.path("custom_components/custom_updater/__init__.py"),
):
if os.path.exists(location):
self.log.critical(
self.task_logger(
self.log.critical,
"This cannot be used with custom_updater. "
"To use this you need to remove custom_updater form %s",
location,
f"To use this you need to remove custom_updater form {location}",
)

self.hacs.disable_hacs(HacsDisabledReason.CONSTRAINS)

if not version_left_higher_then_right(self.hacs.core.ha_version, MINIMUM_HA_VERSION):
self.log.critical(
"You need HA version %s or newer to use this integration.",
MINIMUM_HA_VERSION,
self.task_logger(
self.log.critical,
f"You need HA version {MINIMUM_HA_VERSION} or newer to use this integration.",
)
self.hacs.disable_hacs(HacsDisabledReason.CONSTRAINS)
3 changes: 2 additions & 1 deletion custom_components/hacs/tasks/clear_old_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@ class Task(HacsTask):
stages = [HacsStage.SETUP]

def execute(self) -> None:
"""Execute the task."""
for storage_file in ("hacs",):
path = f"{self.hacs.core.config_path}/.storage/{storage_file}"
if os.path.isfile(path):
self.log.info("Cleaning up old storage file: %s", path)
self.task_logger(self.log.info, f"Cleaning up old storage file: {path}")
os.remove(path)
3 changes: 2 additions & 1 deletion custom_components/hacs/tasks/hello_world.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,5 @@ class Task(HacsTask):
schedule = timedelta(weeks=52)

def execute(self) -> None:
self.log.debug("Hello World!")
"""Execute the task."""
self.task_logger(self.log.debug, "Hello World!")
8 changes: 6 additions & 2 deletions custom_components/hacs/tasks/load_hacs_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ class Task(HacsTask):
stages = [HacsStage.STARTUP]

async def async_execute(self) -> None:
"""Execute the task."""
try:
repository = self.hacs.get_by_name("hacs/integration")
if repository is None:
Expand All @@ -34,7 +35,10 @@ async def async_execute(self) -> None:
self.hacs.repository = repository.repository_object
except HacsException as exception:
if "403" in f"{exception}":
self.log.critical("GitHub API is ratelimited, or the token is wrong.")
self.task_logger(
self.log.critical,
"GitHub API is ratelimited, or the token is wrong.",
)
else:
self.log.critical("[%s] - Could not load HACS!", exception)
self.task_logger(self.log.critical, f"[{exception}] - Could not load HACS!")
self.hacs.disable_hacs(HacsDisabledReason.LOAD_HACS)
2 changes: 1 addition & 1 deletion custom_components/hacs/tasks/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ async def _load_module(module: str):
self.hass.bus.async_listen_once(event, task.execute_task)

if task.schedule is not None and schedule_tasks:
self.log.debug("Scheduling the %s task to run every %s", task.slug, task.schedule)
self.log.debug("Scheduling HacsTask<%s> to run every %s", task.slug, task.schedule)
self.hacs.recuring_tasks.append(
self.hacs.hass.helpers.event.async_track_time_interval(
task.execute_task, task.schedule
Expand Down
1 change: 1 addition & 0 deletions custom_components/hacs/tasks/restore_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,6 @@ class Task(HacsTask):
stages = [HacsStage.SETUP]

async def async_execute(self) -> None:
"""Execute the task."""
if not await self.hacs.data.restore():
self.hacs.disable_hacs(HacsDisabledReason.RESTORE)
14 changes: 9 additions & 5 deletions custom_components/hacs/tasks/setup_frontend.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,17 @@ class Task(HacsTask):
stages = [HacsStage.SETUP]

async def async_execute(self) -> None:
"""Execute the task."""

# Register themes
self.hass.http.register_static_path(f"{URL_BASE}/themes", self.hass.config.path("themes"))

# Register frontend
if self.hacs.configuration.frontend_repo_url:
self.log.warning("Frontend development mode enabled. Do not run in production!")
self.task_logger(
self.log.warning,
"Frontend development mode enabled. Do not run in production!",
)
self.hass.http.register_view(HacsFrontendDev())
else:
#
Expand All @@ -51,11 +55,11 @@ async def async_execute(self) -> None:

# Register www/community for all other files
use_cache = self.hacs.core.lovelace_mode == "storage"
self.log.info(
"%s mode, cache for /hacsfiles/: %s",
self.hacs.core.lovelace_mode,
use_cache,
self.task_logger(
self.log.info,
f"{self.hacs.core.lovelace_mode} mode, cache for /hacsfiles/: {use_cache}",
)

self.hass.http.register_static_path(
URL_BASE,
self.hass.config.path("www/community"),
Expand Down
1 change: 1 addition & 0 deletions custom_components/hacs/tasks/setup_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ class Task(HacsTask):
stages = [HacsStage.SETUP]

async def async_execute(self) -> None:
"""Execute the task."""
if self.hacs.configuration.config_type == ConfigurationType.YAML:
self.hass.async_create_task(
async_load_platform(self.hass, "sensor", DOMAIN, {}, self.hacs.configuration.config)
Expand Down
2 changes: 1 addition & 1 deletion custom_components/hacs/tasks/setup_websocket_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class Task(HacsTask):
stages = [HacsStage.SETUP]

async def async_execute(self) -> None:
"""Execute this task."""
"""Execute the task."""
async_register_command(self.hass, hacs_settings)
async_register_command(self.hass, hacs_config)
async_register_command(self.hass, hacs_repositories)
Expand Down
1 change: 1 addition & 0 deletions custom_components/hacs/tasks/store_hacs_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,5 @@ class Task(HacsTask):
events = [EVENT_HOMEASSISTANT_FINAL_WRITE]

async def async_execute(self) -> None:
"""Execute the task."""
await self.hacs.data.async_write()
3 changes: 2 additions & 1 deletion custom_components/hacs/tasks/verify_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,6 @@ class Task(HacsTask):
stages = [HacsStage.SETUP]

async def async_execute(self) -> None:
"""Execute the task."""
can_update = await self.hacs.async_can_update()
self.log.debug("Can update %s repositories", can_update)
self.task_logger(self.log.debug, f"Can update {can_update} repositories")
4 changes: 2 additions & 2 deletions tests/tasks/test_hello_world.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ async def test_hello_world_exception(hacs: HacsBase, caplog: pytest.LogCaptureFi
"custom_components.hacs.tasks.hello_world.Task.execute", side_effect=Exception("lore_ipsum")
):
await task.execute_task()
assert "Task hello_world failed: lore_ipsum" in caplog.text
assert "HacsTask<hello_world> failed: lore_ipsum" in caplog.text


@pytest.mark.asyncio
Expand All @@ -41,4 +41,4 @@ async def test_hello_world_disabled(hacs: HacsBase, caplog: pytest.LogCaptureFix
hacs.system.disabled_reason = "lorem_ipsum"

await task.execute_task()
assert "Skipping task hello_world, HACS is disabled - lorem_ipsum" in caplog.text
assert "HacsTask<hello_world> Skipping task, HACS is disabled - lorem_ipsum" in caplog.text