Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

wire up ruff for formatting and linting #6

Merged
merged 10 commits into from
Feb 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions .github/workflows/check-format.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
name: "check with ruff"

on:
push:
branches: "**"
tags-ignore: ["**"]
pull_request:

permissions:
contents: "read"
checks: "write"
issues: "write"
pull-requests: "write"

jobs:
check:
runs-on: ubuntu-latest
steps:
- name: "setup"
uses: "KyoriPowered/.github/.github/actions/setup-python-env@trunk"
- name: "setup / install reviewdog"
uses: "reviewdog/action-setup@v1.3.0"
with:
reviewdog_version: "latest"
- name: "setup / install deps"
id: "install"
run: "poetry install"
- name: "run ruff / apply format"
env:
REVIEWDOG_GITHUB_API_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
run: |
if [ "$GITHUB_EVENT_NAME" = "pull_request" ]; then
REPORTER="github-pr-review"
else
REPORTER="github-check"
fi
poetry run ruff format --diff | reviewdog -reporter=$REPORTER -f=diff -f.diff.strip=0 -name=ruff-format -filter-mode=nofilter -fail-level=error
- name: "run ruff / check"
if: "${{ always() && steps.install.conclusion == 'success' }}"
run: "poetry run ruff check --output-format=github"
2 changes: 0 additions & 2 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,3 @@ jobs:
- name: "docker / push"
if: "${{ github.event_name == 'push' && steps.setup.outputs.publishing_branch != ''}}"
run: "docker push ghcr.io/kyoripowered/pydisgit"


20 changes: 20 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
- repo: "https://github.com/pre-commit/pre-commit-hooks"
rev: "v5.0.0"
hooks:
- id: "trailing-whitespace"
- id: "end-of-file-fixer"
- id: "check-case-conflict"
- id: "check-yaml"
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: "v0.9.4"
hooks:
- id: "ruff"
args: [ "--fix" ]
- id: "ruff-format"
- repo: "https://github.com/python-poetry/poetry"
rev: "2.0.1"
hooks:
- id: "poetry-check"
1 change: 0 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,3 @@ COPY --from=builder dist/ ./dist/
RUN pip install $(echo dist/*.whl)

ENTRYPOINT [ "hypercorn", "asgi:pydisgit:app", "-k", "uvloop" ]

4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ Some example unit files for deployment under Podman Quadlet with systemd socket

We recommend choosing a webhook secret to prevent unauthorized users from exhausting the host server's available ratelimit space.

## contributing

We welcome contributions! You'll need Python 3.12 or newer in your environment, and the [poetry](https://python-poetry.org) dependency manager installed. We also recommend installing and enabling [pre-commit](https://pre-commit.com/#install) to automatically resolve any formatting issues as you work on the project. We use the [ruff](https://docs.astral.sh/ruff) linter for code style, you may benefit from one of its editor plugins.

## licensing

pydisgit is released under the terms of the Apache Software License version 2.0. Thanks additionally go out to JRoy and all other contributors to upstream disgit for making it what it is today.
Expand Down
1 change: 0 additions & 1 deletion etc/deployment/etc-sysconfig-pydisgit
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,3 @@ PYDISGIT_IGNORED_PAYLOADS='ping'

# sekrit
# PYDISGIT_GITHUB_WEBHOOK_SECRET='changeme'

218 changes: 217 additions & 1 deletion poetry.lock

Large diffs are not rendered by default.

10 changes: 10 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,13 @@ pydisgit = 'pydisgit:run_dev'
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

[tool.poetry.group.dev.dependencies]
ruff = "^0.9.4"
pre-commit = "^4.1.0"

[tool.ruff]
indent-width = 2

[tool.ruff.lint]
extend-select= ["I"]
46 changes: 29 additions & 17 deletions src/pydisgit/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from httpx import AsyncClient
import pprint

from httpx import AsyncClient
from quart import Quart, Response, request
from werkzeug.exceptions import BadRequest

from .conf import Config, BoundEnv
from .conf import BoundEnv, Config
from .hmac import HmacVerifyMiddleware

Quart.__annotations__["http_client"] = AsyncClient
Expand All @@ -17,67 +18,78 @@
bound = BoundEnv(app.config, app.logger)
app.asgi_app = HmacVerifyMiddleware(app.asgi_app, bound.github_webhook_secret)

from .handlers import router as free_handler_router
from .handlers import router as free_handler_router # noqa: E402, I001

handler_router = free_handler_router.bind(bound, app.logger)

# http client


@app.before_serving
async def setup_httpclient():
app.http_client = AsyncClient(
headers={'User-Agent': 'pydisgit (kyori flavour)'}
)
app.http_client = AsyncClient(headers={"User-Agent": "pydisgit (kyori flavour)"})


@app.after_serving
async def teardown_httpclient():
await app.http_client.aclose()

@app.get('/')

@app.get("/")
async def hello() -> str:
"""
root handler
"""
return "begone foul beast", 400


@app.post('/<hook_id>/<token>')
@app.post("/<hook_id>/<token>")
async def gh_hook(hook_id: str, token: str) -> dict:
event = request.headers["X-GitHub-Event"]
if not event or not request.content_type:
raise BadRequest("No event or content type")

#if (!(await validateRequest(request, env.githubWebhookSecret))) {
# if (!(await validateRequest(request, env.githubWebhookSecret))) {
# return new Response('Invalid secret', { status: 403 });
#}
# }

if "application/json" in request.content_type:
json = await request.json
elif "application/x-www-form-urlencoded" in request.content_type:
json = json.loads((await request.form)['payload'])
json = json.loads((await request.form)["payload"])
else:
raise BadRequest(f"Unknown content type {request.content_type}")

embed = handler_router.process_request(event, json)
if not embed:
return 'Webhook NO-OP', 200
return "Webhook NO-OP", 200

if app.config['DEBUG']:
if app.config["DEBUG"]:
pprint.pprint(embed)
pass
# embed = await bound.buildDebugPaste(embed)

http: AsyncClient = app.http_client

result = await http.post(f"https://discord.com/api/webhooks/{hook_id}/{token}", json = embed)
result = await http.post(
f"https://discord.com/api/webhooks/{hook_id}/{token}", json=embed
)

if result.status_code in (200, 204):
result_text = "".join([await a async for a in result.aiter_text()])
return {"message": f"We won! Webhook {hook_id} executed with token {token} :3, response: {result_text}"}, 200
return {
"message": f"We won! Webhook {hook_id} executed with token {token} :3, response: {result_text}"
}, 200
else:
return Response(response = await result.aread(), status = result.status_code, content_type=result.headers['content-type'], headers=result.headers)
return Response(
response=await result.aread(),
status=result.status_code,
content_type=result.headers["content-type"],
headers=result.headers,
)


@app.get('/health')
@app.get("/health")
async def health_check() -> str:
"""
simple aliveness check
Expand Down
30 changes: 18 additions & 12 deletions src/pydisgit/conf.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
"""
Configuration for pydisgit
"""
from typing import Optional
import logging

import re
from typing import Optional


class Config:
"""
Raw environment from Workers
"""

IGNORED_BRANCH_REGEX: str = "^$"
IGNORED_BRANCHES: str = ""
IGNORED_USERS: str = ""
Expand All @@ -29,25 +31,27 @@ class BoundEnv:
__ignored_users: list[str]
__ignored_payloads: list[str]
__pastegg_api_key: str
__github_webhook_secret: str;
__github_webhook_secret: str

def __init__(self, env, logger):
self.__ignored_branch_pattern = re.compile(env['IGNORED_BRANCH_REGEX']) if 'IGNORED_BRANCH_REGEX' in env else None
self.__ignored_branches = env['IGNORED_BRANCHES'].split(",")
self.__ignored_users = env['IGNORED_USERS'].split(",")
self.__ignored_payloads = env['IGNORED_PAYLOADS'].split(",")
self.__pastegg_api_key = env['PASTE_GG_API_KEY']
self.__github_webhook_secret = env['GITHUB_WEBHOOK_SECRET']
self.__ignored_branch_pattern = (
re.compile(env["IGNORED_BRANCH_REGEX"]) if "IGNORED_BRANCH_REGEX" in env else None
)
self.__ignored_branches = env["IGNORED_BRANCHES"].split(",")
self.__ignored_users = env["IGNORED_USERS"].split(",")
self.__ignored_payloads = env["IGNORED_PAYLOADS"].split(",")
self.__pastegg_api_key = env["PASTE_GG_API_KEY"]
self.__github_webhook_secret = env["GITHUB_WEBHOOK_SECRET"]

logger.info("Ignored branch pattern: %s", self.__ignored_branch_pattern)
logger.info("Ignored branches: %s", self.__ignored_branches)
logger.info("Ignored users: %s", self.__ignored_users)
logger.info("Ignored payloads: %s", self.__ignored_payloads)

def ignored_branch(self, branch: str) -> bool:
return (self.__ignored_branch_pattern
and self.__ignored_branch_pattern.match(branch)) \
or branch in self.__ignored_branches
return (
self.__ignored_branch_pattern and self.__ignored_branch_pattern.match(branch)
) or branch in self.__ignored_branches

def ignored_user(self, user: str) -> bool:
return user in self.__ignored_users
Expand All @@ -61,6 +65,8 @@ def github_webhook_secret(self) -> str:

async def build_debug_paste(self, embed: any) -> str:
pass


# embed = JSON.stringify({
# "files": [
# {
Expand Down
Loading