From f90a21e4e6b23d99ad6e03af78f7e1b2b833363d Mon Sep 17 00:00:00 2001 From: Guilhem Saurel Date: Thu, 9 Mar 2023 00:07:23 +0100 Subject: [PATCH] =?UTF-8?q?flake8,=20pydocstyle,=20pyupgrade=20=E2=86=92?= =?UTF-8?q?=20ruff?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .pre-commit-config.yaml | 19 +++++-------------- CHANGELOG.md | 2 ++ matrix_webhook/app.py | 3 +-- matrix_webhook/conf.py | 8 ++++++-- matrix_webhook/handler.py | 15 +++++++++------ matrix_webhook/utils.py | 4 +++- pyproject.toml | 5 +++++ setup.cfg | 2 -- tests/start.py | 11 ++++++++--- tests/test_github.py | 15 ++++++++------- tests/test_gitlab_gchat.py | 8 +++----- tests/test_gitlab_teams.py | 8 +++----- tests/test_grafana.py | 6 +++--- tests/test_grafana_9x.py | 6 +++--- tests/test_grafana_forward.py | 6 +++--- tests/tests.py | 10 +++++++--- 16 files changed, 69 insertions(+), 59 deletions(-) delete mode 100644 setup.cfg diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index ea79f1e..5bb6d9c 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -21,26 +21,17 @@ repos: rev: 5.12.0 hooks: - id: isort -- repo: https://github.com/PyCQA/pydocstyle - rev: 6.3.0 - hooks: - - id: pydocstyle -- repo: https://github.com/PyCQA/flake8 - rev: 6.0.0 - hooks: - - id: flake8 - repo: https://github.com/psf/black rev: 23.1.0 hooks: - id: black -- repo: https://github.com/asottile/pyupgrade - rev: v3.3.1 - hooks: - - id: pyupgrade - args: - - --py38-plus - repo: https://github.com/pappasam/toml-sort rev: v0.22.4 hooks: - id: toml-sort-fix exclude: 'poetry.lock' +- repo: https://github.com/charliermarsh/ruff-pre-commit + rev: v0.0.254 + hooks: + - id: ruff + args: [--fix, --exit-non-zero-on-fix] diff --git a/CHANGELOG.md b/CHANGELOG.md index daaa77d..9bcaa0e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- tools: flake8, pydocstyle, pyupgrade → ruff + ## [v3.7.0] - 2023-03-08 - Add support for using predefined access tokens diff --git a/matrix_webhook/app.py b/matrix_webhook/app.py index 2bc56bd..b56ad7d 100644 --- a/matrix_webhook/app.py +++ b/matrix_webhook/app.py @@ -12,8 +12,7 @@ LOGGER = logging.getLogger("matrix_webhook.app") async def main(event): - """ - Launch main coroutine. + """Launch main coroutine. matrix client login & start web server """ diff --git a/matrix_webhook/conf.py b/matrix_webhook/conf.py index 538ee18..d3a436c 100644 --- a/matrix_webhook/conf.py +++ b/matrix_webhook/conf.py @@ -34,7 +34,7 @@ parser.add_argument( ), ) auth = parser.add_mutually_exclusive_group( - required=all(v not in os.environ for v in ["MATRIX_PW", "MATRIX_TOKEN"]) + required=all(v not in os.environ for v in ["MATRIX_PW", "MATRIX_TOKEN"]), ) auth.add_argument( "-p", @@ -61,7 +61,11 @@ parser.add_argument( ), ) parser.add_argument( - "-v", "--verbose", action="count", default=0, help="increment verbosity level" + "-v", + "--verbose", + action="count", + default=0, + help="increment verbosity level", ) args = parser.parse_args() diff --git a/matrix_webhook/handler.py b/matrix_webhook/handler.py index 6ad4478..8d4156c 100644 --- a/matrix_webhook/handler.py +++ b/matrix_webhook/handler.py @@ -13,8 +13,7 @@ LOGGER = logging.getLogger("matrix_webhook.handler") async def matrix_webhook(request): - """ - Coroutine given to the server, st. it knows what to do with an HTTP request. + """Coroutine given to the server, st. it knows what to do with an HTTP request. This one handles a POST, checks its content, and forwards it to the matrix room. """ @@ -37,11 +36,13 @@ async def matrix_webhook(request): if "formatter" in request.rel_url.query: try: data = getattr(formatters, request.rel_url.query["formatter"])( - data, request.headers + data, + request.headers, ) except AttributeError: return utils.create_json_response( - HTTPStatus.BAD_REQUEST, "Unknown formatter" + HTTPStatus.BAD_REQUEST, + "Unknown formatter", ) if "room_id" in request.rel_url.query and "room_id" not in data: @@ -56,7 +57,8 @@ async def matrix_webhook(request): data["key"] = conf.API_KEY else: # but if there is a wrong digest, an informative error should be provided return utils.create_json_response( - HTTPStatus.UNAUTHORIZED, "Invalid SHA-256 HMAC digest" + HTTPStatus.UNAUTHORIZED, + "Invalid SHA-256 HMAC digest", ) missing = [] @@ -65,7 +67,8 @@ async def matrix_webhook(request): missing.append(key) if missing: return utils.create_json_response( - HTTPStatus.BAD_REQUEST, f"Missing {', '.join(missing)}" + HTTPStatus.BAD_REQUEST, + f"Missing {', '.join(missing)}", ) if data["key"] != conf.API_KEY: diff --git a/matrix_webhook/utils.py b/matrix_webhook/utils.py index b870819..bca936d 100644 --- a/matrix_webhook/utils.py +++ b/matrix_webhook/utils.py @@ -63,7 +63,9 @@ async def send_room_message(room_id, content): for _ in range(10): try: resp = await CLIENT.room_send( - room_id=room_id, message_type="m.room.message", content=content + room_id=room_id, + message_type="m.room.message", + content=content, ) if isinstance(resp, RoomSendError): if resp.status_code == "M_UNKNOWN_TOKEN": diff --git a/pyproject.toml b/pyproject.toml index 37379be..4012681 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,5 +38,10 @@ matrix-webhook = "matrix_webhook.__main__:main" [tool.poetry.urls] "changelog" = "https://github.com/nim65s/matrix-webhook/blob/master/CHANGELOG.md" +[tool.ruff] +extend-ignore = ["D203", "D213"] +extend-select = ["A", "B", "C", "COM", "D", "EM", "EXE", "G", "N", "PTH", "RET", "RUF", "UP", "W", "YTT"] +target-version = "py38" + [tool.tomlsort] all = true diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 2bcd70e..0000000 --- a/setup.cfg +++ /dev/null @@ -1,2 +0,0 @@ -[flake8] -max-line-length = 88 diff --git a/tests/start.py b/tests/start.py index 4697f73..ad40cb4 100755 --- a/tests/start.py +++ b/tests/start.py @@ -4,6 +4,7 @@ import argparse import logging from os import environ +from pathlib import Path from subprocess import Popen, run from time import time from unittest import main @@ -21,7 +22,11 @@ LOGGER = logging.getLogger("matrix-webhook.tests.start") parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( - "-v", "--verbose", action="count", default=0, help="increment verbosity level" + "-v", + "--verbose", + action="count", + default=0, + help="increment verbosity level", ) @@ -77,14 +82,14 @@ def run_and_test(): "synapse.app.homeserver", "--config-path", "/srv/homeserver.yaml", - ] + ], ) if not wait_available(f"{MATRIX_URL}/_matrix/client/r0/login", "flows"): return False # Register a user for the bot. LOGGER.info("Registering the bot") - with open("/srv/homeserver.yaml") as f: + with Path("/srv/homeserver.yaml").open() as f: secret = yaml.safe_load(f.read()).get("registration_shared_secret", None) request_registration(MATRIX_ID, MATRIX_PW, MATRIX_URL, secret, admin=True) diff --git a/tests/test_github.py b/tests/test_github.py index 9bf52f8..4008b56 100644 --- a/tests/test_github.py +++ b/tests/test_github.py @@ -1,6 +1,7 @@ """Test module for grafana formatter.""" import unittest +from pathlib import Path import httpx import nio @@ -39,7 +40,7 @@ class GithubFormatterTest(unittest.IsolatedAsyncioTestCase): await client.login(MATRIX_PW) room = await client.room_create() - with open("tests/example_github_push.json", "rb") as f: + with Path("tests/example_github_push.json", "rb").open() as f: example_github_push = f.read().strip() self.assertEqual( httpx.post( @@ -72,7 +73,7 @@ class GithubFormatterTest(unittest.IsolatedAsyncioTestCase): await client.login(MATRIX_PW) room = await client.room_create() - with open("tests/example_github_push.json", "rb") as f: + with Path("tests/example_github_push.json").open("rb") as f: example_github_push = f.read().strip() self.assertEqual( httpx.post( @@ -92,11 +93,11 @@ class GithubFormatterTest(unittest.IsolatedAsyncioTestCase): before = "ac7d1d9647008145e9d0cf65d24744d0db4862b8" after = "4bcdb25c809391baaabc264d9309059f9f48ead2" - GH = "https://github.com" - expected = f'

@nim65s pushed on refs/heads/devel: ' - expected += f'@nim65s pushed on refs/heads/devel: ' + expected += f'{before} → {after}:

\n" message = messages.chunk[0] @@ -113,7 +114,7 @@ class GithubFormatterTest(unittest.IsolatedAsyncioTestCase): await client.login(MATRIX_PW) room = await client.room_create() - with open("tests/example_github_push.json", "rb") as f: + with Path("tests/example_github_push.json").open("rb") as f: example_github_push = f.read().strip() self.assertEqual( diff --git a/tests/test_gitlab_gchat.py b/tests/test_gitlab_gchat.py index 2328789..f3ecb0b 100644 --- a/tests/test_gitlab_gchat.py +++ b/tests/test_gitlab_gchat.py @@ -1,9 +1,7 @@ -""" -Test module for gitlab "google chat" formatter. - -""" +"""Test module for gitlab "google chat" formatter.""" import unittest +from pathlib import Path import httpx import nio @@ -22,7 +20,7 @@ class GitlabGchatFormatterTest(unittest.IsolatedAsyncioTestCase): await client.login(MATRIX_PW) room = await client.room_create() - with open("tests/example_gitlab_gchat.json") as f: + with Path("tests/example_gitlab_gchat.json").open() as f: example_gitlab_gchat_request = f.read() self.assertEqual( httpx.post( diff --git a/tests/test_gitlab_teams.py b/tests/test_gitlab_teams.py index eee89e5..5b7b4d2 100644 --- a/tests/test_gitlab_teams.py +++ b/tests/test_gitlab_teams.py @@ -1,9 +1,7 @@ -""" -Test module for gitlab "teams" formatter. - -""" +"""Test module for gitlab "teams" formatter.""" import unittest +from pathlib import Path import httpx import nio @@ -22,7 +20,7 @@ class GitlabTeamsFormatterTest(unittest.IsolatedAsyncioTestCase): await client.login(MATRIX_PW) room = await client.room_create() - with open("tests/example_gitlab_teams.json") as f: + with Path("tests/example_gitlab_teams.json").open() as f: example_gitlab_teams_request = f.read() self.assertEqual( httpx.post( diff --git a/tests/test_grafana.py b/tests/test_grafana.py index 5c7cbd5..5e526f8 100644 --- a/tests/test_grafana.py +++ b/tests/test_grafana.py @@ -1,10 +1,10 @@ -""" -Test module for grafana formatter. +"""Test module for grafana formatter. ref https://grafana.com/docs/grafana/latest/alerting/old-alerting/notifications/#webhook """ import unittest +from pathlib import Path import httpx import nio @@ -23,7 +23,7 @@ class GrafanaFormatterTest(unittest.IsolatedAsyncioTestCase): await client.login(MATRIX_PW) room = await client.room_create() - with open("tests/example_grafana.json") as f: + with Path("tests/example_grafana.json").open() as f: example_grafana_request = f.read() self.assertEqual( httpx.post( diff --git a/tests/test_grafana_9x.py b/tests/test_grafana_9x.py index 1411daa..8c42506 100644 --- a/tests/test_grafana_9x.py +++ b/tests/test_grafana_9x.py @@ -1,10 +1,10 @@ -""" -Test module for grafana v9 formatter. +"""Test module for grafana v9 formatter. ref https://grafana.com/docs/grafana/latest/alerting/old-alerting/notifications/#webhook """ import unittest +from pathlib import Path import httpx import nio @@ -23,7 +23,7 @@ class Grafana9xFormatterTest(unittest.IsolatedAsyncioTestCase): await client.login(MATRIX_PW) room = await client.room_create() - with open("tests/example_grafana_9x.json") as f: + with Path("tests/example_grafana_9x.json").open() as f: example_grafana_request = f.read() self.assertEqual( httpx.post( diff --git a/tests/test_grafana_forward.py b/tests/test_grafana_forward.py index c7e10c0..d1643a8 100644 --- a/tests/test_grafana_forward.py +++ b/tests/test_grafana_forward.py @@ -1,10 +1,10 @@ -""" -Test version 9 compatibility of grafana formatter. +"""Test version 9 compatibility of grafana formatter. ref https://grafana.com/docs/grafana/latest/alerting/old-alerting/notifications/#webhook """ import unittest +from pathlib import Path import httpx import nio @@ -23,7 +23,7 @@ class GrafanaForwardFormatterTest(unittest.IsolatedAsyncioTestCase): await client.login(MATRIX_PW) room = await client.room_create() - with open("tests/example_grafana_9x.json") as f: + with Path("tests/example_grafana_9x.json").open() as f: example_grafana_request = f.read() self.assertEqual( httpx.post( diff --git a/tests/tests.py b/tests/tests.py index 7d44d7e..809a5b6 100644 --- a/tests/tests.py +++ b/tests/tests.py @@ -50,7 +50,8 @@ class BotTest(unittest.IsolatedAsyncioTestCase): room = await client.room_create() self.assertEqual( - bot_req({"text": text}, KEY, room.room_id), {"status": 200, "ret": "OK"} + bot_req({"text": text}, KEY, room.room_id), + {"status": 200, "ret": "OK"}, ) sync = await client.sync() @@ -118,7 +119,8 @@ class BotTest(unittest.IsolatedAsyncioTestCase): room = await client.room_create() self.assertEqual( - bot_req({"body": body}, KEY, room.room_id), {"status": 200, "ret": "OK"} + bot_req({"body": body}, KEY, room.room_id), + {"status": 200, "ret": "OK"}, ) sync = await client.sync() @@ -142,7 +144,9 @@ class BotTest(unittest.IsolatedAsyncioTestCase): self.assertEqual( bot_req( - {"body": body, "formatted_body": formatted_body}, KEY, room.room_id + {"body": body, "formatted_body": formatted_body}, + KEY, + room.room_id, ), {"status": 200, "ret": "OK"}, )