Skip to content

Commit

Permalink
update to newest ruff, use ruff-format instead of black
Browse files Browse the repository at this point in the history
this is still wip
  • Loading branch information
rytilahti committed Mar 13, 2024
1 parent 6e6fb94 commit 75f659c
Show file tree
Hide file tree
Showing 78 changed files with 197 additions and 321 deletions.
24 changes: 5 additions & 19 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,12 @@ repos:
- id: debug-statements
- id: check-ast

- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: 'v0.0.235'
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: 'v0.3.2'
hooks:
- id: ruff
args: ["--fix"]


- repo: https://github.com/psf/black
rev: 24.2.0
hooks:
- id: black
language_version: python3
args: [--fix]
- id: ruff-format

#- repo: https://github.com/PyCQA/doc8
# rev: v1.1.1
Expand All @@ -36,16 +30,8 @@ repos:
# - id: docformatter
# args: [--in-place, --wrap-summaries, '88', --wrap-descriptions, '88', --black


- repo: https://github.com/PyCQA/bandit
rev: 1.7.7
hooks:
- id: bandit
args: [-x, 'tests', -x, '**/test_*.py']


- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.8.0
rev: v1.9.0
hooks:
- id: mypy
additional_dependencies: [types-attrs, types-PyYAML, types-requests, types-pytz, types-croniter, types-freezegun]
3 changes: 1 addition & 2 deletions devtools/miottemplate.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def list():
mapping = get_mapping()

for inst in mapping.instances:
click.echo(f"* {repr(inst)}")
click.echo(f"* {inst!r}")


@cli.command()
Expand All @@ -124,7 +124,6 @@ def list():
@click.pass_context
def download(ctx, urn, model):
"""Download description file for model."""

if urn is None:
if model is None:
click.echo("You need to specify either the model or --urn")
Expand Down
5 changes: 2 additions & 3 deletions miio/cloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def _login(self):
return

try:
from micloud import MiCloud # noqa: F811
from micloud import MiCloud
from micloud.micloudexception import MiCloudAccessDenied
except ImportError:
raise CloudException(
Expand Down Expand Up @@ -180,14 +180,13 @@ def cloud(ctx: click.Context, username, password):
@click.option("--raw", is_flag=True, default=False)
def cloud_list(ctx: click.Context, locale: Optional[str], raw: bool):
"""List devices connected to the cloud account."""

ci = ctx.obj

devices = ci.get_devices(locale=locale)

if raw:
jsonified = json.dumps([dev.raw_data for dev in devices.values()], indent=4)
print(jsonified) # noqa: T201
print(jsonified)
return

for dev in devices.values():
Expand Down
3 changes: 2 additions & 1 deletion miio/devicefactory.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ def register(cls, integration_cls: Type[Device]):
@classmethod
def supported_models(cls) -> Dict[str, Type[Device]]:
"""Return a dictionary of models and their corresponding implementation
classes."""
classes.
"""
return cls._supported_models

@classmethod
Expand Down
8 changes: 1 addition & 7 deletions miio/deviceinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,7 @@ def __init__(self, data):
self.data = data

def __repr__(self):
return "{} v{} ({}) @ {} - token: {}".format(
self.model,
self.firmware_version,
self.mac_address,
self.ip_address,
self.token,
)
return f"{self.model} v{self.firmware_version} ({self.mac_address}) @ {self.ip_address} - token: {self.token}"

@property
def network_interface(self) -> Dict:
Expand Down
2 changes: 1 addition & 1 deletion miio/devicestatus.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def __repr__(self):
s += f" {name}={prop_value}"

for name, embedded in self._embedded.items():
s += f" {name}={repr(embedded)}"
s += f" {name}={embedded!r}"

s += ">"
return s
Expand Down
2 changes: 1 addition & 1 deletion miio/devtools/pcapparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def read_payloads_from_file(file, tokens: List[str]):
try:
decrypted = Message.parse(data, token=bytes.fromhex(token))
break
except BaseException: # noqa: B036
except BaseException:
continue

if decrypted is None:
Expand Down
2 changes: 1 addition & 1 deletion miio/devtools/propertytester.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def fail(x):
fail("None")
else:
valid_properties[property] = value
ok(f"{repr(value)} {type(value)}")
ok(f"{value!r} {type(value)}")
except Exception as ex:
_LOGGER.warning("Unable to request %s: %s", property, ex)

Expand Down
4 changes: 3 additions & 1 deletion miio/extract_tokens.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,9 @@ def decrypt_ztoken(ztoken):
keystring = "00000000000000000000000000000000"
key = bytes.fromhex(keystring)
cipher = Cipher(
algorithms.AES(key), modes.ECB(), backend=default_backend() # nosec
algorithms.AES(key),
modes.ECB(),
backend=default_backend(), # nosec
)
decryptor = cipher.decryptor()
token = decryptor.update(bytes.fromhex(ztoken[:64])) + decryptor.finalize()
Expand Down
2 changes: 0 additions & 2 deletions miio/integrations/airdog/airpurifier/airpurifier_airdog.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ def __init__(self, data: Dict[str, Any]) -> None:
{'power: 'on', 'mode': 'sleep', 'speed': 1, 'lock': 'unlock',
'clean': 'n', 'pm': 11, 'hcho': 0}
"""

self.data = data

@property
Expand Down Expand Up @@ -113,7 +112,6 @@ class AirDogX3(Device):
)
def status(self) -> AirDogStatus:
"""Retrieve properties."""

properties = AVAILABLE_PROPERTIES.get(
self.model, AVAILABLE_PROPERTIES[MODEL_AIRDOG_X3]
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,6 @@ class AirQualityMonitorCGDN1(MiotDevice):
)
def status(self) -> AirQualityMonitorCGDN1Status:
"""Retrieve properties."""

return AirQualityMonitorCGDN1Status(
{
prop["did"]: prop["value"] if prop["code"] == 0 else None
Expand Down
4 changes: 1 addition & 3 deletions miio/integrations/chuangmi/camera/chuangmi_camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,7 @@ class CameraStatus(DeviceStatus):
"""Container for status reports from the Xiaomi Chuangmi Camera."""

def __init__(self, data: Dict[str, Any]) -> None:
"""
Request:
"""Request:
["power", "motion_record", "light", "full_color", "flip", "improve_program", "wdr",
"track", "sdcard_status", "watermark", "max_client", "night_mode", "mini_level"]
Expand Down Expand Up @@ -381,7 +380,6 @@ def set_nas_config(
video_retention_time: NASVideoRetentionTime = NASVideoRetentionTime.Week,
):
"""Set NAS configuration."""

params: Dict[str, Any] = {
"state": state,
"sync_interval": sync_interval,
Expand Down
2 changes: 0 additions & 2 deletions miio/integrations/chuangmi/remote/chuangmi_ir.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ def learn(self, key: int = 1):
:param int key: Storage slot, must be between 1 and 1000000
"""

if key < 1 or key > 1000000:
raise ValueError("Invalid storage slot.")
return self.send("miIO.ir_learn", {"key": str(key)})
Expand All @@ -67,7 +66,6 @@ def read(self, key: int = 1):
:param int key: Slot to read from
"""

if key < 1 or key > 1000000:
raise ValueError("Invalid storage slot.")
return self.send("miIO.ir_read", {"key": str(key)})
Expand Down
6 changes: 2 additions & 4 deletions miio/integrations/chunmi/cooker/cooker.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,9 +209,7 @@ def __init__(self, stage: str):

@property
def state(self) -> int:
"""
10: Cooking finished
"""10: Cooking finished
11: Cooking finished
12: Cooking finished
"""
Expand Down Expand Up @@ -617,7 +615,7 @@ def status(self) -> CookerStatus:
Some cookers doesn't support a list of properties here. Therefore "all" properties
are requested. If the property count or order changes the property list above must
be updated.
""" # noqa: B018
"""
values = self.send("get_prop", ["all"])

properties_count = len(properties)
Expand Down
2 changes: 0 additions & 2 deletions miio/integrations/deerma/humidifier/airhumidifier_jsqs.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,6 @@ def error(self) -> int:
@property
def mode(self) -> OperationMode:
"""Return current operation mode."""

try:
mode = OperationMode(self.data["mode"])
except ValueError as e:
Expand Down Expand Up @@ -166,7 +165,6 @@ class AirHumidifierJsqs(MiotDevice):
)
def status(self) -> AirHumidifierJsqsStatus:
"""Retrieve properties."""

return AirHumidifierJsqsStatus(
{
prop["did"]: prop["value"] if prop["code"] == 0 else None
Expand Down
2 changes: 0 additions & 2 deletions miio/integrations/deerma/humidifier/airhumidifier_mjjsq.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ def __init__(self, data: Dict[str, Any]) -> None:
'Led_State': 1, 'OnOff_State': 0, 'TemperatureValue': 21,
'TipSound_State': 1, 'waterstatus': 1, 'watertankstatus': 1}
"""

self.data = data

@property
Expand Down Expand Up @@ -146,7 +145,6 @@ class AirHumidifierMjjsq(Device):
)
def status(self) -> AirHumidifierStatus:
"""Retrieve properties."""

properties = AVAILABLE_PROPERTIES.get(
self.model, AVAILABLE_PROPERTIES[MODEL_HUMIDIFIER_MJJSQ]
)
Expand Down
5 changes: 1 addition & 4 deletions miio/integrations/dmaker/airfresh/airfresh_t2017.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,7 @@ class AirFreshStatus(DeviceStatus):
"""Container for status reports from the air fresh t2017."""

def __init__(self, data: Dict[str, Any]) -> None:
"""
Response of a Air Fresh A1 (dmaker.airfresh.a1):
"""Response of a Air Fresh A1 (dmaker.airfresh.a1):
{
'power': True,
'mode': 'auto',
Expand Down Expand Up @@ -111,7 +110,6 @@ def __init__(self, data: Dict[str, Any]) -> None:
'screen_direction': 'forward',
}
"""

self.data = data

@property
Expand Down Expand Up @@ -242,7 +240,6 @@ class AirFreshA1(Device):
)
def status(self) -> AirFreshStatus:
"""Retrieve properties."""

properties = AVAILABLE_PROPERTIES.get(
self.model, AVAILABLE_PROPERTIES[MODEL_AIRFRESH_A1]
)
Expand Down
1 change: 0 additions & 1 deletion miio/integrations/dmaker/fan/fan.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,6 @@ def set_child_lock(self, lock: bool):
)
def delay_off(self, minutes: int):
"""Set delay off minutes."""

if minutes < 0:
raise ValueError("Invalid value for a delayed turn off: %s" % minutes)

Expand Down
5 changes: 1 addition & 4 deletions miio/integrations/dmaker/fan/fan_miot.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,7 @@ class FanStatusMiot(DeviceStatus):
"""Container for status reports for Xiaomi Mi Smart Pedestal Fan DMaker P9/P10."""

def __init__(self, data: Dict[str, Any], model: str) -> None:
"""
Response of a FanMiot (dmaker.fan.p10):
"""Response of a FanMiot (dmaker.fan.p10):
{
'id': 1,
Expand Down Expand Up @@ -431,7 +430,6 @@ def set_child_lock(self, lock: bool):
)
def delay_off(self, minutes: int):
"""Set delay off minutes."""

if minutes < 0 or minutes > 480:
raise ValueError("Invalid value for a delayed turn off: %s" % minutes)

Expand Down Expand Up @@ -572,7 +570,6 @@ def set_child_lock(self, lock: bool):
)
def delay_off(self, minutes: int):
"""Set delay off minutes."""

if minutes < 0 or minutes > 480:
raise ValueError("Invalid value for a delayed turn off: %s" % minutes)

Expand Down
12 changes: 6 additions & 6 deletions miio/integrations/dreame/vacuum/dreamevacuum_miot.py
Original file line number Diff line number Diff line change
Expand Up @@ -459,7 +459,8 @@ def water_flow(self) -> Optional[WaterFlow]:
@property
def is_water_box_carriage_attached(self) -> Optional[bool]:
"""Return True if water box carriage (mop) is installed, None if sensor not
present."""
present.
"""
if "water_box_carriage_status" in self.data:
return self.data["water_box_carriage_status"] == 1
return None
Expand Down Expand Up @@ -505,7 +506,6 @@ class DreameVacuum(MiotDevice):
)
def status(self) -> DreameVacuumStatus:
"""State of the vacuum."""

return DreameVacuumStatus(
{
prop["did"]: prop.get("value") if prop.get("code") == 0 else None
Expand Down Expand Up @@ -567,7 +567,7 @@ def fan_speed(self):
fanspeed = dreame_vacuum_status.cleaning_mode
if not fanspeed or fanspeed.value == -1:
_LOGGER.warning("Unknown fanspeed value received")
return
return None
return {fanspeed.name: fanspeed.value}

@command(click.argument("speed", type=int))
Expand All @@ -579,7 +579,7 @@ def set_fan_speed(self, speed: int):
fanspeeds_enum = _get_cleaning_mode_enum_class(self.model)
fanspeed = None
if not fanspeeds_enum:
return
return None
try:
fanspeed = fanspeeds_enum(speed)
except ValueError:
Expand Down Expand Up @@ -612,7 +612,7 @@ def waterflow(self):
waterflow = dreame_vacuum_status.water_flow
if not waterflow or waterflow.value == -1:
_LOGGER.warning("Unknown waterflow value received")
return
return None
return {waterflow.name: waterflow.value}

@command(click.argument("value", type=int))
Expand Down Expand Up @@ -713,7 +713,7 @@ def set_voice(self, url: str, md5sum: str, size: int, voice_id: str):
click.echo(
"You need to pass md5 and file size when using URL for updating."
)
return
return None
local_url = url
else:
server = OneShotServer(file=url)
Expand Down
Loading

0 comments on commit 75f659c

Please sign in to comment.