Skip to content

Commit

Permalink
use ruff in pre-commit for linting and formatting (#1314)
Browse files Browse the repository at this point in the history
* ruff fixes

* fix linting SIM105

* update ruff taget verdion to py312

* enable ruff in vs code

* remove black/flake/etc
  • Loading branch information
lbbrhzn authored Sep 8, 2024
1 parent 4b06be7 commit 5bd31f7
Show file tree
Hide file tree
Showing 20 changed files with 102 additions and 137 deletions.
5 changes: 0 additions & 5 deletions .github/workflows/constraints.txt
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
# home assistant
pip>=21.0,<24.3
pre-commit==3.8.0
bandit==1.7.9
black==24.8.0
flake8==7.1.1
isort==5.13.2
pre-comit-hooks==4.1.0
pyupgrade==3.17.0
reorder-python-imports==3.13.0
sqlalchemy>=1.4.23
43 changes: 6 additions & 37 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,44 +4,13 @@ repos:
hooks:
- id: pyupgrade
args: [--py37-plus]
- repo: https://github.com/psf/black
rev: 23.11.0
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.6.4
hooks:
- id: black
args:
- --safe
- --quiet
files: ^((custom_components|homeassistant|script|tests)/.+)?[^/]+\.py$
- repo: https://github.com/codespell-project/codespell
rev: v2.2.6
hooks:
- id: codespell
args:
- --ignore-words-list=hass,alot,datas,dof,dur,farenheit,hist,iff,ines,ist,lightsensor,mut,nd,pres,referer,ser,serie,te,technik,ue,uint,visability,wan,wanna,withing
- --skip="./.*,*.csv,*.json"
- --quiet-level=2
exclude_types: [csv, json]
- repo: https://github.com/PyCQA/flake8
rev: 6.1.0
hooks:
- id: flake8
additional_dependencies:
- flake8-docstrings==1.5.0
- pydocstyle==5.0.2
files: ^(custom_components|homeassistant|script|tests)/.+\.py$
- repo: https://github.com/PyCQA/bandit
rev: 1.7.5
hooks:
- id: bandit
args:
- --quiet
- --format=custom
- --configfile=bandit.yaml
files: ^(custom_components|homeassistant|script|tests|)/.+\.py$
- repo: https://github.com/PyCQA/isort
rev: 5.12.0
hooks:
- id: isort
# Run the linter.
- id: ruff
# Run the formatter.
- id: ruff-format
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
Expand Down
13 changes: 7 additions & 6 deletions .ruff.toml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# The contents of this file is based on https://github.com/home-assistant/core/blob/dev/pyproject.toml

target-version = "py310"
target-version = "py312"

select = [
lint.select = [
"B007", # Loop control variable {name} not used within loop body
"B014", # Exception handler with duplicate exception
"C", # complexity
Expand All @@ -26,7 +26,8 @@ select = [
"W", # pycodestyle
]

ignore = [
lint.ignore = [
"C901", # function too complex
"D202", # No blank lines allowed after function docstring
"D203", # 1 blank line required before class docstring
"D213", # Multi-line docstring summary should start at the second line
Expand All @@ -38,11 +39,11 @@ ignore = [
"E731", # do not assign a lambda expression, use a def
]

[flake8-pytest-style]
[lint.flake8-pytest-style]
fixture-parentheses = false

[pyupgrade]
[lint.pyupgrade]
keep-runtime-typing = true

[mccabe]
[lint.mccabe]
max-complexity = 25
5 changes: 4 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
{
"python.linting.pylintEnabled": true,
"python.linting.enabled": true,
"python.linting.enabledWithoutWorkspace": true,
"python.linting.lintOnSave": true,
"python.linting.pylintEnabled": true,
"python.linting.ruffEnabled": true,
"python.pythonPath": "/usr/local/bin/python",
"python.analysis.extraPaths": [
"/usr/local/lib/python3.9/site-packages"
Expand Down
48 changes: 22 additions & 26 deletions custom_components/ocpp/api.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
"""Representation of a OCCP Entities."""

from __future__ import annotations

import asyncio
from collections import defaultdict
from datetime import datetime, timedelta, timezone
from datetime import datetime, timedelta, UTC
import json
import logging
from math import sqrt
Expand Down Expand Up @@ -784,8 +785,7 @@ async def start_transaction(self):
return False

async def stop_transaction(self):
"""
Request remote stop of current transaction.
"""Request remote stop of current transaction.
Leaves charger in finishing state until unplugged.
Use reset() to make the charger available again for remote start
Expand Down Expand Up @@ -836,9 +836,9 @@ async def update_firmware(self, firmware_url: str, wait_time: int = 0):
url = schema(firmware_url)
except vol.MultipleInvalid as e:
_LOGGER.debug("Failed to parse url: %s", e)
update_time = (
datetime.now(tz=timezone.utc) + timedelta(hours=wait_time)
).strftime("%Y-%m-%dT%H:%M:%SZ")
update_time = (datetime.now(tz=UTC) + timedelta(hours=wait_time)).strftime(
"%Y-%m-%dT%H:%M:%SZ"
)
req = call.UpdateFirmware(location=url, retrieve_date=update_time)
resp = await self.call(req)
_LOGGER.info("Response: %s", resp)
Expand Down Expand Up @@ -875,9 +875,7 @@ async def data_transfer(self, vendor_id: str, message_id: str = "", data: str =
data,
resp.data,
)
self._metrics[cdet.data_response.value].value = datetime.now(
tz=timezone.utc
)
self._metrics[cdet.data_response.value].value = datetime.now(tz=UTC)
self._metrics[cdet.data_response.value].extra_attr = {message_id: resp.data}
return True
else:
Expand All @@ -897,9 +895,7 @@ async def get_configuration(self, key: str = ""):
if resp.configuration_key:
value = resp.configuration_key[0][om.value.value]
_LOGGER.debug("Get Configuration for %s: %s", key, value)
self._metrics[cdet.config_response.value].value = datetime.now(
tz=timezone.utc
)
self._metrics[cdet.config_response.value].value = datetime.now(tz=UTC)
self._metrics[cdet.config_response.value].extra_attr = {key: value}
return value
if resp.unknown_key:
Expand Down Expand Up @@ -994,7 +990,7 @@ async def monitor_connection(self):
self._metrics[cstat.latency_ping.value].value = latency_ping
self._metrics[cstat.latency_pong.value].value = latency_pong

except asyncio.TimeoutError as timeout_exception:
except TimeoutError as timeout_exception:
_LOGGER.debug(
f"Connection latency from '{self.central.csid}' to '{self.id}': ping={latency_ping} ms, pong={latency_pong} ms",
)
Expand Down Expand Up @@ -1027,7 +1023,7 @@ async def run(self, tasks):
self.tasks = [asyncio.ensure_future(task) for task in tasks]
try:
await asyncio.gather(*self.tasks)
except asyncio.TimeoutError:
except TimeoutError:
pass
except websockets.exceptions.WebSocketException as websocket_exception:
_LOGGER.debug(f"Connection closed to '{self.id}': {websocket_exception}")
Expand Down Expand Up @@ -1258,9 +1254,9 @@ def on_meter_values(self, connector_id: int, meter_value: dict, **kwargs):
self._metrics[measurand].value = float(value)
self._metrics[measurand].unit = unit
if location is not None:
self._metrics[measurand].extra_attr[
om.location.value
] = location
self._metrics[measurand].extra_attr[om.location.value] = (
location
)
if context is not None:
self._metrics[measurand].extra_attr[om.context.value] = context
processed_keys.append(idx)
Expand Down Expand Up @@ -1295,7 +1291,7 @@ def on_meter_values(self, connector_id: int, meter_value: dict, **kwargs):
def on_boot_notification(self, **kwargs):
"""Handle a boot notification."""
resp = call_result.BootNotification(
current_time=datetime.now(tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
current_time=datetime.now(tz=UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
interval=3600,
status=RegistrationStatus.accepted.value,
)
Expand Down Expand Up @@ -1333,12 +1329,12 @@ def on_status_notification(self, connector_id, error_code, status, **kwargs):
self._metrics[cstat.status_connector.value].value = status
self._metrics[cstat.error_code_connector.value].value = error_code
if connector_id >= 1:
self._metrics[cstat.status_connector.value].extra_attr[
connector_id
] = status
self._metrics[cstat.error_code_connector.value].extra_attr[
connector_id
] = error_code
self._metrics[cstat.status_connector.value].extra_attr[connector_id] = (
status
)
self._metrics[cstat.error_code_connector.value].extra_attr[connector_id] = (
error_code
)
if (
status == ChargePointStatus.suspended_ev.value
or status == ChargePointStatus.suspended_evse.value
Expand Down Expand Up @@ -1489,14 +1485,14 @@ def on_stop_transaction(self, meter_stop, timestamp, transaction_id, **kwargs):
def on_data_transfer(self, vendor_id, **kwargs):
"""Handle a Data transfer request."""
_LOGGER.debug("Data transfer received from %s: %s", self.id, kwargs)
self._metrics[cdet.data_transfer.value].value = datetime.now(tz=timezone.utc)
self._metrics[cdet.data_transfer.value].value = datetime.now(tz=UTC)
self._metrics[cdet.data_transfer.value].extra_attr = {vendor_id: kwargs}
return call_result.DataTransfer(status=DataTransferStatus.accepted.value)

@on(Action.heartbeat)
def on_heartbeat(self, **kwargs):
"""Handle a Heartbeat."""
now = datetime.now(tz=timezone.utc)
now = datetime.now(tz=UTC)
self._metrics[cstat.heartbeat.value].value = now
self.hass.async_create_task(self.central.update(self.central.cpid))
return call_result.Heartbeat(current_time=now.strftime("%Y-%m-%dT%H:%M:%SZ"))
Expand Down
1 change: 1 addition & 0 deletions custom_components/ocpp/button.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Button platform for ocpp."""

from __future__ import annotations

from dataclasses import dataclass
Expand Down
1 change: 1 addition & 0 deletions custom_components/ocpp/config_flow.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Adds config flow for ocpp."""

from homeassistant import config_entries
import voluptuous as vol

Expand Down
1 change: 1 addition & 0 deletions custom_components/ocpp/const.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Define constants for OCPP integration."""

import pathlib

import homeassistant.components.input_number as input_number
Expand Down
1 change: 1 addition & 0 deletions custom_components/ocpp/enums.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Additional enumerated values to use in home assistant."""

from enum import Enum, Flag, auto


Expand Down
2 changes: 1 addition & 1 deletion custom_components/ocpp/exception.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
""" This file is imported by home assistant, and can be used to define custom exceptions."""
"""This file is imported by home assistant, and can be used to define custom exceptions."""
1 change: 1 addition & 0 deletions custom_components/ocpp/number.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Number platform for ocpp."""

from __future__ import annotations

from dataclasses import dataclass
Expand Down
3 changes: 2 additions & 1 deletion custom_components/ocpp/sensor.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Sensor platform for ocpp."""

from __future__ import annotations

from dataclasses import dataclass
Expand Down Expand Up @@ -162,7 +163,7 @@ def device_class(self):
Measurand.rpm,
] or self.metric.lower().startswith("frequency"):
device_class = SensorDeviceClass.FREQUENCY
elif self.metric.lower().startswith(tuple(["power.a", "power.o", "power.r"])):
elif self.metric.lower().startswith(("power.a", "power.o", "power.r")):
device_class = SensorDeviceClass.POWER
elif self.metric.lower().startswith("temperature."):
device_class = SensorDeviceClass.TEMPERATURE
Expand Down
1 change: 1 addition & 0 deletions custom_components/ocpp/switch.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Switch platform for ocpp."""

from __future__ import annotations

from dataclasses import dataclass
Expand Down
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Configuration file for the Sphinx documentation builder.
"""Configuration file for the Sphinx documentation builder."""

# -- Project information

Expand Down
1 change: 1 addition & 0 deletions manage/update_manifest.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Update the manifest file."""

# https://github.com/hacs/integration/blob/main/manage/update_manifest.py
import json
import os
Expand Down
17 changes: 11 additions & 6 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Global fixtures for ocpp integration."""

import asyncio
from unittest.mock import patch

Expand All @@ -20,9 +21,11 @@ def auto_enable_custom_integrations(enable_custom_integrations):
@pytest.fixture(name="skip_notifications", autouse=True)
def skip_notifications_fixture():
"""Skip notification calls."""
with patch("homeassistant.components.persistent_notification.async_create"), patch(
"homeassistant.components.persistent_notification.async_dismiss"
), patch("custom_components.ocpp.api.ChargePoint.notify_ha"):
with (
patch("homeassistant.components.persistent_notification.async_create"),
patch("homeassistant.components.persistent_notification.async_dismiss"),
patch("custom_components.ocpp.api.ChargePoint.notify_ha"),
):
yield


Expand All @@ -33,9 +36,11 @@ def bypass_get_data_fixture():
"""Skip calls to get data from API."""
future = asyncio.Future()
future.set_result(websockets.WebSocketServer)
with patch("websockets.server.serve", return_value=future), patch(
"websockets.server.WebSocketServer.close"
), patch("websockets.server.WebSocketServer.wait_closed"):
with (
patch("websockets.server.serve", return_value=future),
patch("websockets.server.WebSocketServer.close"),
patch("websockets.server.WebSocketServer.wait_closed"),
):
yield


Expand Down
1 change: 1 addition & 0 deletions tests/const.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Constants for ocpp tests."""

from custom_components.ocpp.const import (
CONF_CPID,
CONF_CSID,
Expand Down
Loading

0 comments on commit 5bd31f7

Please sign in to comment.