Skip to content

Commit

Permalink
github: CI: add ruff (#32)
Browse files Browse the repository at this point in the history
Signed-off-by: Álvaro Fernández Rojas <noltari@gmail.com>
  • Loading branch information
Noltari committed Jul 8, 2024
1 parent dfdbdee commit 6dbc8ed
Show file tree
Hide file tree
Showing 4 changed files with 95 additions and 22 deletions.
34 changes: 34 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: CI

on:
- push
- pull_request

env:
DEFAULT_PYTHON: "3.12"

jobs:
ruff:
name: Check ruff
runs-on: ubuntu-latest
steps:
- name: Check out code from GitHub
uses: actions/checkout@v4

- name: Set up Python ${{ env.DEFAULT_PYTHON }}
uses: actions/setup-python@v5
with:
python-version: ${{ env.DEFAULT_PYTHON }}

- name: Upgrade pip
run: |
python -m pip install --upgrade pip
pip --version
- name: Install ruff
run: |
pip install ruff
- name: Run ruff
run: |
ruff check homeconnect
44 changes: 27 additions & 17 deletions homeconnect/api.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import json
import logging
import os
import time
from threading import Thread
import time
from typing import Callable, Dict, Optional, Union

from oauthlib.oauth2 import TokenExpiredError
from requests import Response
from requests_oauthlib import OAuth2Session
from requests.exceptions import RetryError
from requests.adapters import HTTPAdapter, Retry
from requests.exceptions import RetryError
from requests_oauthlib import OAuth2Session

from .sseclient import SSEClient

Expand Down Expand Up @@ -138,8 +138,7 @@ def delete(self, endpoint):
return res

def get_appliances(self):
"""Return a list of `HomeConnectAppliance` instances for all
appliances."""
"""Return a list of `HomeConnectAppliance` instances for all appliances."""

appliances = {}

Expand Down Expand Up @@ -194,7 +193,8 @@ def handle_event(self, event, appliance):
"""Handle a new event.
Updates the status with the event data and executes any callback
function."""
function.
"""
event_data = json.loads(event.data)
items = event_data.get("items")
if items is not None:
Expand All @@ -218,8 +218,11 @@ def handle_event(self, event, appliance):

@staticmethod
def json2dict(lst):
"""Turn a list of dictionaries where one key is called 'key'
into a dictionary with the value of 'key' as key."""
"""Convert JSON to dictionary.
Turn a list of dictionaries where one key is called 'key'
into a dictionary with the value of 'key' as key.
"""
return {d.pop("key"): d for d in lst}


Expand All @@ -246,8 +249,7 @@ def token_dump(self, token):
json.dump(token, f)

def token_load(self):
"""Load the token from the cache if exists it and is not expired,
otherwise return None."""
"""Load the token from the cache if exists and not expired."""
if not os.path.exists(self.token_cache):
return None
with open(self.token_cache, "r") as f:
Expand All @@ -257,7 +259,10 @@ def token_load(self):
self._oauth = OAuth2Session(
client_id=self.client_id,
redirect_uri=self.redirect_uri,
auto_refresh_kwargs={"client_id": self.client_id, "client_secret": self.client_secret},
auto_refresh_kwargs={
"client_id": self.client_id,
"client_secret": self.client_secret,
},
token=token,
token_updater=self.token_updater,
)
Expand All @@ -269,8 +274,7 @@ def token_expired(self, token):
return token["expires_at"] - now < 60

def get_token(self, authorization_response):
"""Get the token given the redirect URL obtained from the
authorization."""
"""Get the token given the redirect URL obtained from the authorization."""
LOGGER.info("Fetching token ...")
token = self._oauth.fetch_token(
f"{self.host}{ENDPOINT_TOKEN}",
Expand Down Expand Up @@ -307,7 +311,10 @@ def __init__(
self.event_callback = None

def __repr__(self):
return "HomeConnectAppliance(hc, haId='{}', vib='{}', brand='{}', type='{}', name='{}', enumber='{}', connected={})".format(
return (
"HomeConnectAppliance(hc, haId='{}', vib='{}', brand='{}'"
", type='{}', name='{}', enumber='{}', connected={})"
).format(
self.haId,
self.vib,
self.brand,
Expand All @@ -318,16 +325,19 @@ def __repr__(self):
)

def listen_events(self, callback=None):
"""Register event callback method"""
"""Register event callback method."""
self.event_callback = callback

if not self.hc.listening_events:
self.hc.listen_events()

@staticmethod
def json2dict(lst):
"""Turn a list of dictionaries where one key is called 'key'
into a dictionary with the value of 'key' as key."""
"""Convert JSON to dictionary.
Turn a list of dictionaries where one key is called 'key'
into a dictionary with the value of 'key' as key.
"""
return {d.pop("key"): d for d in lst}

def get(self, endpoint):
Expand Down
12 changes: 7 additions & 5 deletions homeconnect/sseclient.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
"""Taken from https://github.com/btubbs/sseclient"""
"""Taken from https://github.com/btubbs/sseclient."""

import codecs
import logging
import re
import time
import warnings

import requests
from oauthlib.oauth2 import TokenExpiredError
import requests
from requests.exceptions import HTTPError

# Technically, we should support streams that mix line endings. This regex,
Expand Down Expand Up @@ -85,7 +85,8 @@ def __next__(self):
raise EOFError()
self.buf += decoder.decode(next_chunk)

# except (StopIteration, requests.RequestException, EOFError, http.client.IncompleteRead, ValueError) as e:
# except (StopIteration, requests.RequestException, EOFError,
# http.client.IncompleteRead, ValueError) as e:
except Exception as e:
LOGGER.warning("Exception while reading event: ", exc_info=True)
time.sleep(self.retry / 1000.0)
Expand Down Expand Up @@ -142,7 +143,8 @@ def dump(self):

@classmethod
def parse(cls, raw):
"""
"""Parse event message.
Given a possibly-multiline string representing an SSE message, parse it
and return a Event object.
"""
Expand All @@ -152,7 +154,7 @@ def parse(cls, raw):
if m is None:
# Malformed line. Discard but warn.
warnings.warn('Invalid SSE line: "%s"' % line, SyntaxWarning)
LOGGER.warn('Invalid SSE line: "%s"', line)
LOGGER.warning('Invalid SSE line: "%s"', line)
continue

name = m.group("name")
Expand Down
27 changes: 27 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
[tool.ruff.lint]
select = [
"D", # docstrings
"E", # pycodestyle
"G", # flake8-logging-format
"I", # isort
"W", # pycodestyle
]

ignore = [
"D100", # Missing docstring in public module
"D101", # Missing docstring in public class
"D102", # Missing docstring in public method
"D104", # Missing docstring in public package
"D105", # Missing docstring in magic method
"D107", # Missing docstring in `__init__`
"D202", # No blank lines allowed aftee function docstring
"D203", # 1 blank line required before class docstring
"D213", # Multi-line docstring summary should start at the second line
"D401", # First line should be in imperative mood
"E722", # Do not use bare `except`
]

[tool.ruff.lint.isort]
force-sort-within-sections = true
combine-as-imports = true
split-on-trailing-comma = false

0 comments on commit 6dbc8ed

Please sign in to comment.