updated lovelace dashboards and migrate tcp sensors to use serial component with SOCAT
This commit is contained in:
@@ -1,8 +1,9 @@
|
||||
"""Repository."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from asyncio import sleep
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
@@ -15,29 +16,31 @@ from aiogithubapi import (
|
||||
AIOGitHubAPINotModifiedException,
|
||||
GitHubReleaseModel,
|
||||
)
|
||||
from aiogithubapi.const import BASE_API_URL
|
||||
from aiogithubapi.objects.repository import AIOGitHubAPIRepository
|
||||
import attr
|
||||
from homeassistant.helpers import device_registry as dr, issue_registry as ir
|
||||
|
||||
from ..const import DOMAIN
|
||||
from ..enums import ConfigurationType, HacsDispatchEvent, RepositoryFile
|
||||
from ..enums import HacsDispatchEvent, RepositoryFile
|
||||
from ..exceptions import (
|
||||
HacsException,
|
||||
HacsNotModifiedException,
|
||||
HacsRepositoryArchivedException,
|
||||
HacsRepositoryExistException,
|
||||
)
|
||||
from ..utils.backup import Backup, BackupNetDaemon
|
||||
from ..types import DownloadableContent
|
||||
from ..utils.backup import Backup
|
||||
from ..utils.decode import decode_content
|
||||
from ..utils.decorator import concurrent
|
||||
from ..utils.file_system import async_exists, async_remove, async_remove_directory
|
||||
from ..utils.filters import filter_content_return_one_of_type
|
||||
from ..utils.github_graphql_query import GET_REPOSITORY_RELEASES
|
||||
from ..utils.json import json_loads
|
||||
from ..utils.logger import LOGGER
|
||||
from ..utils.path import is_safe
|
||||
from ..utils.queue_manager import QueueManager
|
||||
from ..utils.store import async_remove_store
|
||||
from ..utils.template import render_template
|
||||
from ..utils.url import github_archive, github_release_asset
|
||||
from ..utils.validate import Validate
|
||||
from ..utils.version import (
|
||||
version_left_higher_or_equal_then_right,
|
||||
@@ -83,7 +86,6 @@ TOPIC_FILTER = (
|
||||
"lovelace",
|
||||
"media-player",
|
||||
"mediaplayer",
|
||||
"netdaemon",
|
||||
"plugin",
|
||||
"python_script",
|
||||
"python-script",
|
||||
@@ -112,6 +114,7 @@ REPOSITORY_KEYS_TO_EXPORT = (
|
||||
("last_version", None),
|
||||
("manifest_name", None),
|
||||
("open_issues", 0),
|
||||
("prerelease", None),
|
||||
("stargazers_count", 0),
|
||||
("topics", []),
|
||||
)
|
||||
@@ -163,6 +166,7 @@ class RepositoryData:
|
||||
manifest_name: str = None
|
||||
new: bool = True
|
||||
open_issues: int = 0
|
||||
prerelease: str = None
|
||||
published_tags: list[str] = []
|
||||
releases: bool = False
|
||||
selected_tag: str = None
|
||||
@@ -173,7 +177,7 @@ class RepositoryData:
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name."""
|
||||
if self.category in ["integration", "netdaemon"]:
|
||||
if self.category == "integration":
|
||||
return self.domain
|
||||
return self.full_name.split("/")[-1]
|
||||
|
||||
@@ -195,7 +199,7 @@ class RepositoryData:
|
||||
continue
|
||||
|
||||
if key == "last_fetched" and isinstance(value, float):
|
||||
setattr(self, key, datetime.fromtimestamp(value))
|
||||
setattr(self, key, datetime.fromtimestamp(value, UTC))
|
||||
elif key == "id":
|
||||
setattr(self, key, str(value))
|
||||
elif key == "country":
|
||||
@@ -383,7 +387,9 @@ class HacsRepository:
|
||||
@property
|
||||
def display_available_version(self) -> str:
|
||||
"""Return display_authors"""
|
||||
if self.data.last_version is not None:
|
||||
if self.data.show_beta and self.data.prerelease is not None:
|
||||
available = self.data.prerelease
|
||||
elif self.data.last_version is not None:
|
||||
available = self.data.last_version
|
||||
else:
|
||||
if self.data.last_commit is not None:
|
||||
@@ -404,8 +410,6 @@ class HacsRepository:
|
||||
@property
|
||||
def pending_update(self) -> bool:
|
||||
"""Return True if pending update."""
|
||||
if not self.can_download:
|
||||
return False
|
||||
if self.data.installed:
|
||||
if self.data.selected_tag is not None:
|
||||
if self.data.selected_tag == self.data.default_branch:
|
||||
@@ -500,13 +504,7 @@ class HacsRepository:
|
||||
|
||||
if self.repository_object:
|
||||
self.data.last_updated = self.repository_object.attributes.get("pushed_at", 0)
|
||||
self.data.last_fetched = datetime.utcnow()
|
||||
|
||||
# Set topics
|
||||
self.data.topics = self.data.topics
|
||||
|
||||
# Set description
|
||||
self.data.description = self.data.description
|
||||
self.data.last_fetched = datetime.now(UTC)
|
||||
|
||||
@concurrent(concurrenttasks=10, backoff_time=5)
|
||||
async def common_update(self, ignore_issues=False, force=False, skip_releases=False) -> bool:
|
||||
@@ -554,52 +552,55 @@ class HacsRepository:
|
||||
self.additional_info = await self.async_get_info_file_contents()
|
||||
|
||||
# Set last fetch attribute
|
||||
self.data.last_fetched = datetime.utcnow()
|
||||
self.data.last_fetched = datetime.now(UTC)
|
||||
|
||||
return True
|
||||
|
||||
async def download_zip_files(self, validate) -> None:
|
||||
async def download_zip_files(self, validate: Validate) -> None:
|
||||
"""Download ZIP archive from repository release."""
|
||||
|
||||
try:
|
||||
await self.async_download_zip_file(
|
||||
DownloadableContent(
|
||||
name=self.repository_manifest.filename,
|
||||
url=github_release_asset(
|
||||
repository=self.data.full_name,
|
||||
version=self.ref,
|
||||
filename=self.repository_manifest.filename,
|
||||
),
|
||||
),
|
||||
validate,
|
||||
)
|
||||
# lgtm [py/catch-base-exception] pylint: disable=broad-except
|
||||
except BaseException:
|
||||
validate.errors.append(
|
||||
f"Download of {
|
||||
self.repository_manifest.filename} was not completed"
|
||||
)
|
||||
|
||||
async def async_download_zip_file(
|
||||
self,
|
||||
content: DownloadableContent,
|
||||
validate: Validate,
|
||||
) -> None:
|
||||
"""Download ZIP archive from repository release."""
|
||||
try:
|
||||
contents = None
|
||||
target_ref = self.ref.split("/")[1]
|
||||
|
||||
for release in self.releases.objects:
|
||||
self.logger.debug(
|
||||
"%s ref: %s --- tag: %s", self.string, target_ref, release.tag_name
|
||||
)
|
||||
if release.tag_name == target_ref:
|
||||
contents = release.assets
|
||||
break
|
||||
|
||||
if not contents:
|
||||
validate.errors.append(f"No assets found for release '{self.ref}'")
|
||||
return
|
||||
|
||||
download_queue = QueueManager(hass=self.hacs.hass)
|
||||
|
||||
for content in contents or []:
|
||||
download_queue.add(self.async_download_zip_file(content, validate))
|
||||
|
||||
await download_queue.execute()
|
||||
except BaseException: # lgtm [py/catch-base-exception] pylint: disable=broad-except
|
||||
validate.errors.append("Download was not completed")
|
||||
|
||||
async def async_download_zip_file(self, content, validate) -> None:
|
||||
"""Download ZIP archive from repository release."""
|
||||
try:
|
||||
filecontent = await self.hacs.async_download_file(content.browser_download_url)
|
||||
filecontent = await self.hacs.async_download_file(content["url"])
|
||||
|
||||
if filecontent is None:
|
||||
validate.errors.append(f"[{content.name}] was not downloaded")
|
||||
validate.errors.append(f"Failed to download {content['url']}")
|
||||
return
|
||||
|
||||
temp_dir = await self.hacs.hass.async_add_executor_job(tempfile.mkdtemp)
|
||||
temp_file = f"{temp_dir}/{self.repository_manifest.filename}"
|
||||
|
||||
result = await self.hacs.async_save_file(temp_file, filecontent)
|
||||
with zipfile.ZipFile(temp_file, "r") as zip_file:
|
||||
zip_file.extractall(self.content.path.local)
|
||||
|
||||
def _extract_zip_file():
|
||||
with zipfile.ZipFile(temp_file, "r") as zip_file:
|
||||
zip_file.extractall(self.content.path.local)
|
||||
|
||||
await self.hacs.hass.async_add_executor_job(_extract_zip_file)
|
||||
|
||||
def cleanup_temp_dir():
|
||||
"""Cleanup temp_dir."""
|
||||
@@ -608,32 +609,39 @@ class HacsRepository:
|
||||
shutil.rmtree(temp_dir)
|
||||
|
||||
if result:
|
||||
self.logger.info("%s Download of %s completed", self.string, content.name)
|
||||
self.logger.info("%s Download of %s completed", self.string, content["name"])
|
||||
await self.hacs.hass.async_add_executor_job(cleanup_temp_dir)
|
||||
return
|
||||
|
||||
validate.errors.append(f"[{content.name}] was not downloaded")
|
||||
except BaseException: # lgtm [py/catch-base-exception] pylint: disable=broad-except
|
||||
validate.errors.append(f"[{content['name']}] was not downloaded")
|
||||
# lgtm [py/catch-base-exception] pylint: disable=broad-except
|
||||
except BaseException:
|
||||
validate.errors.append("Download was not completed")
|
||||
|
||||
async def download_content(self) -> None:
|
||||
async def download_content(self, version: string | None = None) -> None:
|
||||
"""Download the content of a directory."""
|
||||
if self.hacs.configuration.experimental:
|
||||
if (
|
||||
not self.repository_manifest.zip_release
|
||||
and not self.data.file_name
|
||||
and self.content.path.remote is not None
|
||||
):
|
||||
self.logger.info("%s Trying experimental download", self.string)
|
||||
try:
|
||||
await self.download_repository_zip()
|
||||
return
|
||||
except HacsException as exception:
|
||||
self.logger.exception(exception)
|
||||
contents: list[FileInformation] | None = None
|
||||
if (
|
||||
not self.repository_manifest.zip_release
|
||||
and not self.data.file_name
|
||||
and self.content.path.remote is not None
|
||||
):
|
||||
self.logger.info("%s Downloading repository archive", self.string)
|
||||
try:
|
||||
await self.download_repository_zip()
|
||||
return
|
||||
except HacsException as exception:
|
||||
self.logger.exception(exception)
|
||||
|
||||
contents = self.gather_files_to_download()
|
||||
if self.repository_manifest.filename:
|
||||
self.logger.debug("%s %s", self.string, self.repository_manifest.filename)
|
||||
|
||||
if self.content.path.remote == "release" and version is not None:
|
||||
contents = await self.release_contents(version)
|
||||
|
||||
if not contents:
|
||||
contents = self.gather_files_to_download()
|
||||
|
||||
if not contents:
|
||||
raise HacsException("No content to download")
|
||||
|
||||
@@ -654,15 +662,17 @@ class HacsRepository:
|
||||
if not ref:
|
||||
raise HacsException("Missing required elements.")
|
||||
|
||||
url = f"{BASE_API_URL}/repos/{self.data.full_name}/zipball/{ref}"
|
||||
|
||||
filecontent = await self.hacs.async_download_file(
|
||||
url,
|
||||
headers={
|
||||
"Authorization": f"token {self.hacs.configuration.token}",
|
||||
"User-Agent": f"HACS/{self.hacs.version}",
|
||||
},
|
||||
github_archive(repository=self.data.full_name, version=ref, variant="tags"),
|
||||
keep_url=True,
|
||||
nolog=True,
|
||||
)
|
||||
|
||||
if filecontent is None:
|
||||
filecontent = await self.hacs.async_download_file(
|
||||
github_archive(repository=self.data.full_name, version=ref, variant="heads"),
|
||||
keep_url=True,
|
||||
)
|
||||
if filecontent is None:
|
||||
raise HacsException(f"[{self}] Failed to download zipball")
|
||||
|
||||
@@ -672,18 +682,26 @@ class HacsRepository:
|
||||
if not result:
|
||||
raise HacsException("Could not save ZIP file")
|
||||
|
||||
with zipfile.ZipFile(temp_file, "r") as zip_file:
|
||||
extractable = []
|
||||
for path in zip_file.filelist:
|
||||
filename = "/".join(path.filename.split("/")[1:])
|
||||
if (
|
||||
filename.startswith(self.content.path.remote)
|
||||
and filename != self.content.path.remote
|
||||
):
|
||||
path.filename = filename.replace(self.content.path.remote, "")
|
||||
extractable.append(path)
|
||||
def _extract_zip_file():
|
||||
with zipfile.ZipFile(temp_file, "r") as zip_file:
|
||||
extractable = []
|
||||
for path in zip_file.filelist:
|
||||
filename = "/".join(path.filename.split("/")[1:])
|
||||
if (
|
||||
filename.startswith(self.content.path.remote)
|
||||
and filename != self.content.path.remote
|
||||
):
|
||||
path.filename = filename.replace(self.content.path.remote, "")
|
||||
if path.filename == "/":
|
||||
# Blank files is not valid, and will start to throw in Python 3.12
|
||||
continue
|
||||
extractable.append(path)
|
||||
|
||||
zip_file.extractall(self.content.path.local, extractable)
|
||||
if len(extractable) == 0:
|
||||
raise HacsException("No content to extract")
|
||||
zip_file.extractall(self.content.path.local, extractable)
|
||||
|
||||
await self.hacs.hass.async_add_executor_job(_extract_zip_file)
|
||||
|
||||
def cleanup_temp_dir():
|
||||
"""Cleanup temp_dir."""
|
||||
@@ -706,18 +724,15 @@ class HacsRepository:
|
||||
)
|
||||
if response:
|
||||
return json_loads(decode_content(response.data.content))
|
||||
except BaseException: # lgtm [py/catch-base-exception] pylint: disable=broad-except
|
||||
# lgtm [py/catch-base-exception] pylint: disable=broad-except
|
||||
except BaseException:
|
||||
pass
|
||||
|
||||
async def async_get_info_file_contents(self) -> str:
|
||||
async def async_get_info_file_contents(self, *, version: str | None = None, **kwargs) -> str:
|
||||
"""Get the content of the info.md file."""
|
||||
|
||||
def _info_file_variants() -> tuple[str, ...]:
|
||||
name: str = (
|
||||
"readme"
|
||||
if self.repository_manifest.render_readme or self.hacs.configuration.experimental
|
||||
else "info"
|
||||
)
|
||||
name: str = "readme"
|
||||
return (
|
||||
f"{name.upper()}.md",
|
||||
f"{name}.md",
|
||||
@@ -732,25 +747,7 @@ class HacsRepository:
|
||||
if not info_files:
|
||||
return ""
|
||||
|
||||
try:
|
||||
response = await self.hacs.async_github_api_method(
|
||||
method=self.hacs.githubapi.repos.contents.get,
|
||||
raise_exception=False,
|
||||
repository=self.data.full_name,
|
||||
path=info_files[0],
|
||||
)
|
||||
if response:
|
||||
return render_template(
|
||||
self.hacs,
|
||||
decode_content(response.data.content)
|
||||
.replace("<svg", "<disabled")
|
||||
.replace("</svg", "</disabled"),
|
||||
self,
|
||||
)
|
||||
except BaseException as exc: # lgtm [py/catch-base-exception] pylint: disable=broad-except
|
||||
self.logger.error("%s %s", self.string, exc)
|
||||
|
||||
return ""
|
||||
return await self.get_documentation(filename=info_files[0], version=version) or ""
|
||||
|
||||
def remove(self) -> None:
|
||||
"""Run remove tasks."""
|
||||
@@ -764,19 +761,7 @@ class HacsRepository:
|
||||
if not await self.remove_local_directory():
|
||||
raise HacsException("Could not uninstall")
|
||||
self.data.installed = False
|
||||
if self.data.category == "integration":
|
||||
if self.data.config_flow:
|
||||
await self.reload_custom_components()
|
||||
else:
|
||||
self.pending_restart = True
|
||||
elif self.data.category == "theme":
|
||||
try:
|
||||
await self.hacs.hass.services.async_call("frontend", "reload_themes", {})
|
||||
except BaseException: # lgtm [py/catch-base-exception] pylint: disable=broad-except
|
||||
pass
|
||||
elif self.data.category == "template":
|
||||
await self.hacs.hass.services.async_call("homeassistant", "reload_custom_templates", {})
|
||||
|
||||
await self._async_post_uninstall()
|
||||
await async_remove_store(self.hacs.hass, f"hacs/{self.data.id}.hacs")
|
||||
|
||||
self.data.installed_version = None
|
||||
@@ -799,7 +784,7 @@ class HacsRepository:
|
||||
|
||||
try:
|
||||
if self.data.category == "python_script":
|
||||
local_path = f"{self.content.path.local}/{self.data.name}.py"
|
||||
local_path = f"{self.content.path.local}/{self.data.file_name}"
|
||||
elif self.data.category == "template":
|
||||
local_path = f"{self.content.path.local}/{self.data.file_name}"
|
||||
elif self.data.category == "theme":
|
||||
@@ -808,8 +793,7 @@ class HacsRepository:
|
||||
f"{self.hacs.configuration.theme_path}/"
|
||||
f"{self.data.name}.yaml"
|
||||
)
|
||||
if os.path.exists(path):
|
||||
os.remove(path)
|
||||
await async_remove(self.hacs.hass, path, missing_ok=True)
|
||||
local_path = self.content.path.local
|
||||
elif self.data.category == "integration":
|
||||
if not self.data.domain:
|
||||
@@ -823,18 +807,18 @@ class HacsRepository:
|
||||
else:
|
||||
local_path = self.content.path.local
|
||||
|
||||
if os.path.exists(local_path):
|
||||
if await async_exists(self.hacs.hass, local_path):
|
||||
if not is_safe(self.hacs, local_path):
|
||||
self.logger.error("%s Path %s is blocked from removal", self.string, local_path)
|
||||
return False
|
||||
self.logger.debug("%s Removing %s", self.string, local_path)
|
||||
|
||||
if self.data.category in ["python_script", "template"]:
|
||||
os.remove(local_path)
|
||||
await async_remove(self.hacs.hass, local_path)
|
||||
else:
|
||||
shutil.rmtree(local_path)
|
||||
await async_remove_directory(self.hacs.hass, local_path)
|
||||
|
||||
while os.path.exists(local_path):
|
||||
while await async_exists(self.hacs.hass, local_path):
|
||||
await sleep(1)
|
||||
else:
|
||||
self.logger.debug(
|
||||
@@ -842,7 +826,8 @@ class HacsRepository:
|
||||
)
|
||||
|
||||
except (
|
||||
BaseException # lgtm [py/catch-base-exception] pylint: disable=broad-except
|
||||
# lgtm [py/catch-base-exception] pylint: disable=broad-except
|
||||
BaseException
|
||||
) as exception:
|
||||
self.logger.debug("%s Removing %s failed with %s", self.string, local_path, exception)
|
||||
return False
|
||||
@@ -888,7 +873,7 @@ class HacsRepository:
|
||||
await self.async_pre_install()
|
||||
self.logger.info("%s Pre installation steps completed", self.string)
|
||||
|
||||
async def async_install(self) -> None:
|
||||
async def async_install(self, *, version: str | None = None, **_) -> None:
|
||||
"""Run install steps."""
|
||||
await self._async_pre_install()
|
||||
self.hacs.async_dispatch(
|
||||
@@ -896,7 +881,7 @@ class HacsRepository:
|
||||
{"repository": self.data.full_name, "progress": 30},
|
||||
)
|
||||
self.logger.info("%s Running installation steps", self.string)
|
||||
await self.async_install_repository()
|
||||
await self.async_install_repository(version=version)
|
||||
self.hacs.async_dispatch(
|
||||
HacsDispatchEvent.REPOSITORY_DOWNLOAD_PROGRESS,
|
||||
{"repository": self.data.full_name, "progress": 90},
|
||||
@@ -911,6 +896,13 @@ class HacsRepository:
|
||||
async def async_post_installation(self) -> None:
|
||||
"""Run post install steps."""
|
||||
|
||||
async def async_post_uninstall(self):
|
||||
"""Run post uninstall steps."""
|
||||
|
||||
async def _async_post_uninstall(self):
|
||||
"""Run post uninstall steps."""
|
||||
await self.async_post_uninstall()
|
||||
|
||||
async def _async_post_install(self) -> None:
|
||||
"""Run post install steps."""
|
||||
self.logger.info("%s Running post installation steps", self.string)
|
||||
@@ -927,39 +919,34 @@ class HacsRepository:
|
||||
)
|
||||
self.logger.info("%s Post installation steps completed", self.string)
|
||||
|
||||
async def async_install_repository(self) -> None:
|
||||
async def async_install_repository(self, *, version: str | None = None, **_) -> None:
|
||||
"""Common installation steps of the repository."""
|
||||
persistent_directory = None
|
||||
await self.update_repository(force=True)
|
||||
await self.update_repository(force=version is None)
|
||||
if self.content.path.local is None:
|
||||
raise HacsException("repository.content.path.local is None")
|
||||
self.validate.errors.clear()
|
||||
|
||||
if not self.can_download:
|
||||
raise HacsException("The version of Home Assistant is not compatible with this version")
|
||||
|
||||
version = self.version_to_download()
|
||||
if version == self.data.default_branch:
|
||||
self.ref = version
|
||||
version_to_install = version or self.version_to_download()
|
||||
if version_to_install == self.data.default_branch:
|
||||
self.ref = version_to_install
|
||||
else:
|
||||
self.ref = f"tags/{version}"
|
||||
self.ref = f"tags/{version_to_install}"
|
||||
|
||||
self.hacs.async_dispatch(
|
||||
HacsDispatchEvent.REPOSITORY_DOWNLOAD_PROGRESS,
|
||||
{"repository": self.data.full_name, "progress": 40},
|
||||
)
|
||||
|
||||
if self.data.installed and self.data.category == "netdaemon":
|
||||
persistent_directory = BackupNetDaemon(hacs=self.hacs, repository=self)
|
||||
await self.hacs.hass.async_add_executor_job(persistent_directory.create)
|
||||
|
||||
elif self.repository_manifest.persistent_directory:
|
||||
if os.path.exists(
|
||||
f"{self.content.path.local}/{self.repository_manifest.persistent_directory}"
|
||||
if self.repository_manifest.persistent_directory:
|
||||
if await async_exists(
|
||||
self.hacs.hass,
|
||||
f"{self.content.path.local}/{self.repository_manifest.persistent_directory}",
|
||||
):
|
||||
persistent_directory = Backup(
|
||||
hacs=self.hacs,
|
||||
local_path=f"{self.content.path.local}/{self.repository_manifest.persistent_directory}",
|
||||
local_path=f"{
|
||||
self.content.path.local}/{self.repository_manifest.persistent_directory}",
|
||||
backup_path=tempfile.gettempdir() + "/hacs_persistent_directory/",
|
||||
)
|
||||
await self.hacs.hass.async_add_executor_job(persistent_directory.create)
|
||||
@@ -970,16 +957,17 @@ class HacsRepository:
|
||||
|
||||
self.hacs.log.debug("%s Local path is set to %s", self.string, self.content.path.local)
|
||||
self.hacs.log.debug("%s Remote path is set to %s", self.string, self.content.path.remote)
|
||||
self.hacs.log.debug("%s Version to install: %s", self.string, version_to_install)
|
||||
|
||||
self.hacs.async_dispatch(
|
||||
HacsDispatchEvent.REPOSITORY_DOWNLOAD_PROGRESS,
|
||||
{"repository": self.data.full_name, "progress": 50},
|
||||
)
|
||||
|
||||
if self.repository_manifest.zip_release and version != self.data.default_branch:
|
||||
if self.repository_manifest.zip_release and self.repository_manifest.filename:
|
||||
await self.download_zip_files(self.validate)
|
||||
else:
|
||||
await self.download_content()
|
||||
await self.download_content(version_to_install)
|
||||
|
||||
self.hacs.async_dispatch(
|
||||
HacsDispatchEvent.REPOSITORY_DOWNLOAD_PROGRESS,
|
||||
@@ -1010,10 +998,10 @@ class HacsRepository:
|
||||
self.data.installed = True
|
||||
self.data.installed_commit = self.data.last_commit
|
||||
|
||||
if version == self.data.default_branch:
|
||||
if version_to_install == self.data.default_branch:
|
||||
self.data.installed_version = None
|
||||
else:
|
||||
self.data.installed_version = version
|
||||
self.data.installed_version = version_to_install
|
||||
|
||||
async def async_get_legacy_repository_object(
|
||||
self,
|
||||
@@ -1071,9 +1059,9 @@ class HacsRepository:
|
||||
)
|
||||
self.repository_object = repository_object
|
||||
if self.data.full_name.lower() != repository_object.full_name.lower():
|
||||
self.hacs.common.renamed_repositories[
|
||||
self.data.full_name
|
||||
] = repository_object.full_name
|
||||
self.hacs.common.renamed_repositories[self.data.full_name] = (
|
||||
repository_object.full_name
|
||||
)
|
||||
if not self.hacs.system.generator:
|
||||
raise HacsRepositoryExistException
|
||||
self.logger.error(
|
||||
@@ -1089,7 +1077,7 @@ class HacsRepository:
|
||||
except HacsRepositoryExistException:
|
||||
raise HacsRepositoryExistException from None
|
||||
except (AIOGitHubAPIException, HacsException) as exception:
|
||||
if not self.hacs.status.startup:
|
||||
if not self.hacs.status.startup or self.hacs.system.generator:
|
||||
self.logger.error("%s %s", self.string, exception)
|
||||
if not ignore_issues:
|
||||
self.validate.errors.append("Repository does not exist.")
|
||||
@@ -1112,15 +1100,28 @@ class HacsRepository:
|
||||
# Get releases.
|
||||
if not skip_releases:
|
||||
try:
|
||||
releases = await self.get_releases(
|
||||
prerelease=self.data.show_beta,
|
||||
returnlimit=self.hacs.configuration.release_limit,
|
||||
)
|
||||
releases = await self.get_releases(prerelease=True, returnlimit=30)
|
||||
if releases:
|
||||
self.data.prerelease = None
|
||||
for release in releases:
|
||||
if release.draft:
|
||||
continue
|
||||
elif release.prerelease:
|
||||
if self.data.prerelease is None:
|
||||
self.data.prerelease = release.tag_name
|
||||
else:
|
||||
self.data.last_version = release.tag_name
|
||||
break
|
||||
|
||||
self.data.releases = True
|
||||
self.releases.objects = releases
|
||||
self.data.published_tags = [x.tag_name for x in self.releases.objects]
|
||||
self.data.last_version = next(iter(self.data.published_tags))
|
||||
|
||||
filtered_releases = [
|
||||
release
|
||||
for release in releases
|
||||
if not release.draft and (self.data.show_beta or not release.prerelease)
|
||||
]
|
||||
self.releases.objects = filtered_releases
|
||||
self.data.published_tags = [x.tag_name for x in filtered_releases]
|
||||
|
||||
except HacsException:
|
||||
self.data.releases = False
|
||||
@@ -1228,6 +1229,25 @@ class HacsRepository:
|
||||
files.append(FileInformation(path.download_url, path.full_path, path.filename))
|
||||
return files
|
||||
|
||||
async def release_contents(self, version: str | None = None) -> list[FileInformation] | None:
|
||||
"""Gather the contents of a release."""
|
||||
release = await self.hacs.async_github_api_method(
|
||||
method=self.hacs.githubapi.generic,
|
||||
endpoint=f"/repos/{self.data.full_name}/releases/tags/{version}",
|
||||
raise_exception=False,
|
||||
)
|
||||
if release is None:
|
||||
return None
|
||||
|
||||
return [
|
||||
FileInformation(
|
||||
url=asset.get("browser_download_url"),
|
||||
path=asset.get("name"),
|
||||
name=asset.get("name"),
|
||||
)
|
||||
for asset in release.data.get("assets", [])
|
||||
]
|
||||
|
||||
@concurrent(concurrenttasks=10)
|
||||
async def dowload_repository_content(self, content: FileInformation) -> None:
|
||||
"""Download content."""
|
||||
@@ -1266,18 +1286,13 @@ class HacsRepository:
|
||||
self.validate.errors.append(f"[{content.name}] was not downloaded.")
|
||||
|
||||
except (
|
||||
BaseException # lgtm [py/catch-base-exception] pylint: disable=broad-except
|
||||
# lgtm [py/catch-base-exception] pylint: disable=broad-except
|
||||
BaseException
|
||||
) as exception:
|
||||
self.validate.errors.append(f"Download was not completed [{exception}]")
|
||||
|
||||
async def async_remove_entity_device(self) -> None:
|
||||
"""Remove the entity device."""
|
||||
if (
|
||||
self.hacs.configuration == ConfigurationType.YAML
|
||||
or not self.hacs.configuration.experimental
|
||||
):
|
||||
return
|
||||
|
||||
device_registry: dr.DeviceRegistry = dr.async_get(hass=self.hacs.hass)
|
||||
device = device_registry.async_get_device(identifiers={(DOMAIN, str(self.data.id))})
|
||||
|
||||
@@ -1303,3 +1318,137 @@ class HacsRepository:
|
||||
return self.data.selected_tag
|
||||
|
||||
return self.data.default_branch or "main"
|
||||
|
||||
async def get_documentation(
|
||||
self,
|
||||
*,
|
||||
filename: str | None = None,
|
||||
version: str | None = None,
|
||||
**kwargs,
|
||||
) -> str | None:
|
||||
"""Get the documentation of the repository."""
|
||||
if filename is None:
|
||||
return None
|
||||
|
||||
if version is not None:
|
||||
target_version = version
|
||||
elif self.data.installed:
|
||||
target_version = self.data.installed_version or self.data.installed_commit
|
||||
else:
|
||||
target_version = self.data.last_version or self.data.last_commit or self.ref
|
||||
|
||||
self.logger.debug(
|
||||
"%s Getting documentation for version=%s,filename=%s",
|
||||
self.string,
|
||||
target_version,
|
||||
filename,
|
||||
)
|
||||
if target_version is None:
|
||||
return None
|
||||
|
||||
result = await self.hacs.async_download_file(
|
||||
f"https://raw.githubusercontent.com/{
|
||||
self.data.full_name}/{target_version}/{filename}",
|
||||
nolog=True,
|
||||
)
|
||||
|
||||
return (
|
||||
result.decode(encoding="utf-8")
|
||||
.replace("<svg", "<disabled")
|
||||
.replace("</svg", "</disabled")
|
||||
if result
|
||||
else None
|
||||
)
|
||||
|
||||
async def get_hacs_json(self, *, version: str, **kwargs) -> HacsManifest | None:
|
||||
"""Get the hacs.json file of the repository."""
|
||||
self.logger.debug("%s Getting hacs.json for version=%s", self.string, version)
|
||||
try:
|
||||
result = await self.hacs.async_download_file(
|
||||
f"https://raw.githubusercontent.com/{
|
||||
self.data.full_name}/{version}/hacs.json",
|
||||
nolog=True,
|
||||
)
|
||||
if result is None:
|
||||
return None
|
||||
return HacsManifest.from_dict(json_loads(result))
|
||||
except Exception: # pylint: disable=broad-except
|
||||
return None
|
||||
|
||||
async def _ensure_download_capabilities(self, ref: str | None, **kwargs: Any) -> None:
|
||||
"""Ensure that the download can be handled."""
|
||||
target_manifest: HacsManifest | None = None
|
||||
if ref is None:
|
||||
if not self.can_download:
|
||||
raise HacsException(
|
||||
f"This {
|
||||
self.data.category.value} is not available for download."
|
||||
)
|
||||
return
|
||||
|
||||
if ref == self.data.last_version:
|
||||
target_manifest = self.repository_manifest
|
||||
else:
|
||||
target_manifest = await self.get_hacs_json(version=ref)
|
||||
|
||||
if target_manifest is None:
|
||||
raise HacsException(
|
||||
f"The version {ref} for this {
|
||||
self.data.category.value} can not be used with HACS."
|
||||
)
|
||||
|
||||
if (
|
||||
target_manifest.homeassistant is not None
|
||||
and self.hacs.core.ha_version < target_manifest.homeassistant
|
||||
):
|
||||
raise HacsException(
|
||||
f"This version requires Home Assistant {
|
||||
target_manifest.homeassistant} or newer."
|
||||
)
|
||||
if target_manifest.hacs is not None and self.hacs.version < target_manifest.hacs:
|
||||
raise HacsException(f"This version requires HACS {
|
||||
target_manifest.hacs} or newer.")
|
||||
|
||||
async def async_download_repository(self, *, ref: str | None = None, **_) -> None:
|
||||
"""Download the content of a repository."""
|
||||
await self._ensure_download_capabilities(ref)
|
||||
self.logger.info("Starting download, %s", ref)
|
||||
if self.display_version_or_commit == "version":
|
||||
self.hacs.async_dispatch(
|
||||
HacsDispatchEvent.REPOSITORY_DOWNLOAD_PROGRESS,
|
||||
{"repository": self.data.full_name, "progress": 10},
|
||||
)
|
||||
if not ref:
|
||||
await self.update_repository(force=True)
|
||||
else:
|
||||
self.ref = ref
|
||||
self.data.selected_tag = ref
|
||||
self.force_branch = ref is not None
|
||||
self.hacs.async_dispatch(
|
||||
HacsDispatchEvent.REPOSITORY_DOWNLOAD_PROGRESS,
|
||||
{"repository": self.data.full_name, "progress": 20},
|
||||
)
|
||||
|
||||
try:
|
||||
await self.async_install(version=ref)
|
||||
except HacsException as exception:
|
||||
raise HacsException(
|
||||
f"Downloading {self.data.full_name} with version {
|
||||
ref or self.data.last_version or self.data.last_commit} failed with ({exception})"
|
||||
) from exception
|
||||
finally:
|
||||
self.data.selected_tag = None
|
||||
self.force_branch = False
|
||||
self.hacs.async_dispatch(
|
||||
HacsDispatchEvent.REPOSITORY_DOWNLOAD_PROGRESS,
|
||||
{"repository": self.data.full_name, "progress": False},
|
||||
)
|
||||
|
||||
async def async_get_releases(self, *, first: int = 30) -> list[GitHubReleaseModel]:
|
||||
"""Get the last x releases of a repository."""
|
||||
response = await self.hacs.async_github_api_method(
|
||||
method=self.hacs.githubapi.repos.releases.list,
|
||||
repository=self.data.full_name,
|
||||
kwargs={"per_page": 30},
|
||||
)
|
||||
return response.data
|
||||
|
||||
Reference in New Issue
Block a user