Skip to content

Commit

Permalink
Merge pull request #562 from dermotduffy/pylint-fix-to-master
Browse files Browse the repository at this point in the history
Upgrade pylint/pylint-test and address variety of pylint issues
  • Loading branch information
dermotduffy committed Oct 23, 2023
2 parents bf432a2 + ff24563 commit 4ba816d
Show file tree
Hide file tree
Showing 9 changed files with 43 additions and 56 deletions.
13 changes: 6 additions & 7 deletions custom_components/frigate/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@
"""
from __future__ import annotations

from collections.abc import Callable
from datetime import timedelta
import logging
import re
from typing import Any, Callable, Final
from typing import Any, Final

from awesomeversion import AwesomeVersion

Expand Down Expand Up @@ -70,8 +71,7 @@ def get_frigate_device_identifier(
"""Get a device identifier."""
if camera_name:
return (DOMAIN, f"{entry.entry_id}:{slugify(camera_name)}")
else:
return (DOMAIN, entry.entry_id)
return (DOMAIN, entry.entry_id)


def get_frigate_entity_unique_id(
Expand Down Expand Up @@ -155,10 +155,9 @@ async def async_setup(hass: HomeAssistant, config: Config) -> bool:
"""Set up this integration using YAML is not supported."""
integration = await async_get_integration(hass, DOMAIN)
_LOGGER.info(
STARTUP_MESSAGE.format(
title=NAME,
integration_version=integration.version,
)
STARTUP_MESSAGE,
NAME,
integration.version,
)

hass.data.setdefault(DOMAIN, {})
Expand Down
2 changes: 1 addition & 1 deletion custom_components/frigate/camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,7 @@ async def async_camera_image(
return self._last_image

@property
def state(self) -> str:
def state(self) -> str: # pylint: disable=overridden-final-method
"""Return the camera state."""
if self._last_image is None:
return STATE_IDLE
Expand Down
2 changes: 1 addition & 1 deletion custom_components/frigate/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def _show_config_form(
self,
user_input: dict[str, Any] | None = None,
errors: dict[str, Any] | None = None,
) -> dict[str, Any]: # pylint: disable=unused-argument
) -> dict[str, Any]:
"""Show the configuration form."""
if user_input is None:
user_input = {}
Expand Down
4 changes: 2 additions & 2 deletions custom_components/frigate/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@

STARTUP_MESSAGE = """
-------------------------------------------------------------------
{title}
Integration Version: {integration_version}
%s
Integration Version: %s
This is a custom integration!
If you have any issues with this you need to open an issue here:
https://github.com/blakeblackshear/frigate-hass-integration/issues
Expand Down
8 changes: 5 additions & 3 deletions custom_components/frigate/diagnostics.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""Diagnostics support for Frigate."""

from typing import Any, Dict
from __future__ import annotations

from typing import Any

from homeassistant.components.diagnostics import async_redact_data
from homeassistant.config_entries import ConfigEntry
Expand All @@ -11,15 +13,15 @@
REDACT_CONFIG = {CONF_PASSWORD, CONF_PATH}


def get_redacted_data(data: Dict[str, Any]) -> Any:
def get_redacted_data(data: dict[str, Any]) -> Any:
"""Redact sensitive vales from data."""
return async_redact_data(data, REDACT_CONFIG)


async def async_get_config_entry_diagnostics(
hass: HomeAssistant,
entry: ConfigEntry,
) -> Dict[str, Any]:
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""

config = hass.data[DOMAIN][entry.entry_id][ATTR_CONFIG]
Expand Down
59 changes: 23 additions & 36 deletions custom_components/frigate/media_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,11 +131,11 @@ def get_integration_proxy_path(self, timezone: str) -> str:

@classmethod
def _add_frigate_instance_id_to_parts_if_absent(
self, parts: list[str], default_frigate_instance_id: str | None = None
cls, parts: list[str], default_frigate_instance_id: str | None = None
) -> list[str]:
"""Add a frigate instance id if it's not specified."""
if (
self._get_index(parts, 0) == self.get_identifier_type()
cls._get_index(parts, 0) == cls.get_identifier_type()
and default_frigate_instance_id is not None
):
parts.insert(0, default_frigate_instance_id)
Expand Down Expand Up @@ -168,32 +168,28 @@ def mime_type(self) -> str:
"""Get mime type for this frigate media type."""
if self == FrigateMediaType.CLIPS:
return "application/x-mpegURL"
else:
return "image/jpg"
return "image/jpg"

@property
def media_type(self) -> str:
"""Get media type for this frigate media type."""
if self == FrigateMediaType.CLIPS:
return str(MEDIA_TYPE_VIDEO)
else:
return str(MEDIA_TYPE_IMAGE)
return str(MEDIA_TYPE_IMAGE)

@property
def media_class(self) -> str:
"""Get media class for this frigate media type."""
if self == FrigateMediaType.CLIPS:
return str(MEDIA_CLASS_VIDEO)
else:
return str(MEDIA_CLASS_IMAGE)
return str(MEDIA_CLASS_IMAGE)

@property
def extension(self) -> str:
"""Get filename extension."""
if self == FrigateMediaType.CLIPS:
return "m3u8"
else:
return "jpg"
return "jpg"


@attr.s(frozen=True)
Expand Down Expand Up @@ -255,8 +251,7 @@ def get_integration_proxy_path(self, timezone: str) -> str:
"""Get the equivalent Frigate server path."""
if self.frigate_media_type == FrigateMediaType.CLIPS:
return f"vod/event/{self.id}/index.{self.frigate_media_type.extension}"
else:
return f"snapshot/{self.id}"
return f"snapshot/{self.id}"

@property
def mime_type(self) -> str:
Expand Down Expand Up @@ -375,15 +370,15 @@ def _validate_year_month_day(
try:
dt.datetime.strptime(data, "%Y-%m-%d")
except ValueError as exc:
raise ValueError("Invalid date in identifier: %s" % data) from exc
raise ValueError(f"Invalid date in identifier: {data}") from exc


def _validate_hour(
inst: RecordingIdentifier, attribute: attr.Attribute, value: int | None
) -> None:
"""Determine if a value is a valid hour."""
if value is not None and (int(value) < 0 or int(value) > 23):
raise ValueError("Invalid hour in identifier: %s" % value)
raise ValueError(f"Invalid hour in identifier: {value}")


@attr.s(frozen=True)
Expand Down Expand Up @@ -554,8 +549,8 @@ def _get_client(self, identifier: Identifier) -> FrigateApiClient:
return client

raise MediaSourceError(
"Could not find client for frigate instance id: %s"
% identifier.frigate_instance_id
"Could not find client for frigate instance "
f"id: {identifier.frigate_instance_id}"
)

def _get_default_frigate_instance_id(self) -> str | None:
Expand Down Expand Up @@ -584,7 +579,7 @@ async def async_resolve_media(self, item: MediaSourceItem) -> PlayMedia:
f"/api/frigate/{identifier.frigate_instance_id}/{server_path}",
identifier.mime_type,
)
raise Unresolvable("Unknown or disallowed identifier: %s" % item.identifier)
raise Unresolvable(f"Unknown or disallowed identifier: {item.identifier}")

async def async_browse_media(
self,
Expand Down Expand Up @@ -672,7 +667,7 @@ async def async_browse_media(
identifier.frigate_instance_id
):
raise MediaSourceError(
"Forbidden media source identifier: %s" % item.identifier
f"Forbidden media source identifier: {item.identifier}"
)

if isinstance(identifier, EventSearchIdentifier):
Expand Down Expand Up @@ -719,7 +714,7 @@ async def async_browse_media(
except FrigateApiClientError as exc:
raise MediaSourceError from exc

raise MediaSourceError("Invalid media source identifier: %s" % item.identifier)
raise MediaSourceError(f"Invalid media source identifier: {item.identifier}")

async def _get_event_summary_data(
self, identifier: EventSearchIdentifier
Expand Down Expand Up @@ -1229,19 +1224,13 @@ def _count_by(
) -> int:
"""Return count of events that match the identifier."""
return sum(
[
d["count"]
for d in summary_data.data
if (
(identifier.after is None or d["timestamp"] >= identifier.after)
and (
identifier.before is None or d["timestamp"] < identifier.before
)
and (identifier.camera is None or identifier.camera in d["camera"])
and (identifier.label is None or identifier.label in d["label"])
and (identifier.zone is None or identifier.zone in d["zones"])
)
]
d["count"]
for d in summary_data.data
if (identifier.after is None or d["timestamp"] >= identifier.after)
and (identifier.before is None or d["timestamp"] < identifier.before)
and (identifier.camera is None or identifier.camera in d["camera"])
and (identifier.label is None or identifier.label in d["label"])
and (identifier.zone is None or identifier.zone in d["zones"])
)

def _get_recording_base_media_source(
Expand Down Expand Up @@ -1298,8 +1287,7 @@ def _get_recording_days(
dt.datetime.strptime(day_item["day"], "%Y-%m-%d")
except ValueError as exc:
raise MediaSourceError(
"Media source is not valid for %s %s"
% (identifier, day_item["day"])
f"Media source is not valid for {identifier} {day_item['day']}"
) from exc

base.children.append(
Expand Down Expand Up @@ -1340,8 +1328,7 @@ def _get_recording_hours(
title = dt.datetime.strptime(hour_data["hour"], "%H").strftime("%H:00")
except ValueError as exc:
raise MediaSourceError(
"Media source is not valid for %s %s"
% (identifier, hour_data["hour"])
f"Media source is not valid for {identifier} {hour_data['hour']}"
) from exc

base.children.append(
Expand Down
2 changes: 1 addition & 1 deletion custom_components/frigate/update.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def installed_version(self) -> str | None:
if not version_hash:
return None

version = str(version_hash).split("-")[0]
version = str(version_hash).split("-", maxsplit=1)[0]

return version

Expand Down
7 changes: 3 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ ignore = [
jobs = 2
load-plugins = [
"pylint.extensions.typing",
"pylint_strict_informational",
"pylint_pytest",
]
persistent = false
Expand Down Expand Up @@ -104,9 +103,9 @@ expected-line-ending-format = "LF"

[tool.pylint.EXCEPTIONS]
overgeneral-exceptions = [
"BaseException",
"Exception",
"HomeAssistantError",
"builtins.BaseException",
"builtins.Exception",
"homeassistant.HomeAssistantError",
]

[tool.pylint.TYPING]
Expand Down
2 changes: 1 addition & 1 deletion requirements_dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ mypy==1.1.1
pre-commit
pytest
pytest-homeassistant-custom-component==0.12.49
pylint-pytest
pylint-pytest==1.1.3a0
pylint
pytest-aiohttp
pytest-asyncio
Expand Down

0 comments on commit 4ba816d

Please sign in to comment.