Make basic package
Publish package / publish (push) Successful in 13s

This commit is contained in:
stilobique committed 2026-10-30 18:25:58 +01:00
1 parent b81e86b640
commit b86ae38b03
8 files changed
+393 -2

No files matched your search

+19
View File
@@ -0,0 +1,19 @@
"""Discord build-status notifications for Gitea Actions CI."""
from .core import Attachment, Section, StepResult, build_payload, send
from .gitea_api import fetch_run_jobs
from .status import StepMapping, build_status, sections_from_status
__version__ = "0.1.0"
__all__ = [
"Attachment",
"Section",
"StepResult",
"build_payload",
"send",
"fetch_run_jobs",
"StepMapping",
"build_status",
"sections_from_status",
]
+110
View File
@@ -0,0 +1,110 @@
"""Discord embed layer for CI build/deploy notifications.
No CI-specific knowledge lives here: everything deals in StepResult/Section
objects and Discord's webhook payload shape.
"""
from dataclasses import dataclass, field
from typing import Optional
COLOR_SUCCESS = 0x2ECC71
COLOR_FAILURE = 0xE74C3C
@dataclass
class StepResult:
name: str
passed: Optional[bool]
log_url: Optional[str] = None
@property
def value(self) -> str:
if self.passed is None:
return "⏸️ pas encore exécuté"
if self.passed:
return "✅ passed"
if self.log_url:
return f"❌ failed — [voir les logs]({self.log_url})"
return "❌ failed"
@dataclass
class Section:
"""One Discord embed: a build/deploy report for one part of a pipeline."""
title: str
description: str
builds: list[StepResult] = field(default_factory=list)
deploys: list[StepResult] = field(default_factory=list)
url: Optional[str] = None
author: Optional[str] = "Gitea CI"
@property
def passed(self) -> bool:
return all(result.passed is not False for result in (*self.builds, *self.deploys))
def to_embed(self) -> dict:
fields = [
{"name": f"📦 {build.name}", "value": build.value}
for build in self.builds
] + [
{"name": f"🚀 {deploy.name}", "value": deploy.value}
for deploy in self.deploys
]
embed = {
"title": self.title,
"description": self.description,
"color": COLOR_SUCCESS if self.passed else COLOR_FAILURE,
"fields": fields,
}
if self.url:
embed["url"] = self.url
if self.author:
embed["author"] = {"name": self.author}
return embed
@dataclass
class Attachment:
"""A file attached to the Discord notification."""
filename: str
content: bytes
content_type: str = "application/octet-stream"
def build_payload(
sections: list[Section],
username: Optional[str] = None,
avatar_url: Optional[str] = None,
content: Optional[str] = None,
) -> dict:
payload = {"embeds": [section.to_embed() for section in sections]}
if username:
payload["username"] = username
if avatar_url:
payload["avatar_url"] = avatar_url
if content:
payload["content"] = content
return payload
def send(webhook_url: str, payload: dict, attachments: Optional[list[Attachment]] = None) -> None:
import requests
if not attachments:
response = requests.post(webhook_url, json=payload, timeout=10)
response.raise_for_status()
return
import json
files = {
f"files[{i}]": (a.filename, a.content, a.content_type)
for i, a in enumerate(attachments)
}
response = requests.post(
webhook_url,
data={"payload_json": json.dumps(payload)},
files=files,
timeout=10,
)
response.raise_for_status()
+17
View File
@@ -0,0 +1,17 @@
"""Thin, agnostic client for the Gitea Actions API.
Only reads what's needed to build a build/deploy status report: the jobs
and steps of a single workflow run.
"""
from typing import Any
def fetch_run_jobs(base_url: str, token: str, owner: str, repo: str, run_id) -> list[dict[str, Any]]:
"""Get a Gitea Action job state"""
import requests
url = f"{base_url}/api/v1/repos/{owner}/{repo}/actions/runs/{run_id}/jobs"
response = requests.get(url, headers={"Authorization": f"token {token}"}, timeout=10)
response.raise_for_status()
return response.json()["jobs"]
+111
View File
@@ -0,0 +1,111 @@
"""Turns raw Gitea Actions job/step results into a plain nested status dict,
and renders that dict into Discord-ready ``Section`` objects.
Nothing here knows about any specific project's artifact names (APK, AAB,
Play Store, ...) — the step-name mapping and display labels are supplied by
the caller (see Tamagosaure's ``notify.py`` for a concrete example).
Status dicts look like::
{
"android": [
{"builds": {"apk": True, "aab": False}},
{"deploy": {"itch": True, "play-store": None}},
],
}
``True``/``False`` mean the step ran and passed/failed; ``None`` means it
never ran during this workflow run (job skipped, step never reached, ...).
"""
from typing import Any, Optional
from .core import Section, StepResult
# step name -> (section key, "builds" | "deploy", item key).
# Keyed by step name rather than job name: several reusable workflows can
# define jobs with the same name (e.g. both the web and android pipelines
# have a job called "deploy-itch"), but their step names are always distinct.
StepMapping = dict[str, tuple[str, str, str]]
def _conclusion_to_bool(conclusion: str) -> Optional[bool]:
if conclusion == "success":
return True
if conclusion == "failure":
return False
return None
def build_status(jobs: list[dict[str, Any]], mapping: StepMapping) -> dict[str, list[dict]]:
status: dict[str, list[dict]] = {}
def bucket_for(section: str, bucket: str) -> dict:
entries = status.setdefault(section, [])
for entry in entries:
if bucket in entry:
return entry[bucket]
new_bucket: dict = {}
entries.append({bucket: new_bucket})
return new_bucket
# Seed every mapped key to "not run" first, so a step that never shows
# up in this run (skipped job, earlier failure, ...) still reports as
# pending instead of silently disappearing from the payload.
for _step_name, (section, bucket, key) in mapping.items():
bucket_for(section, bucket)[key] = None
steps_by_name = {
step["name"]: step.get("conclusion", "")
for job in jobs
for step in job.get("steps", [])
}
for step_name, (section, bucket, key) in mapping.items():
if step_name in steps_by_name:
bucket_for(section, bucket)[key] = _conclusion_to_bool(steps_by_name[step_name])
return status
def sections_from_status(
status: dict[str, list[dict]],
sections_config: dict[str, dict],
run_url: Optional[str] = None,
) -> list[Section]:
"""Build Discord ``Section`` objects from a status dict.
``sections_config`` maps a status key (e.g. "android") to display
config: ``title``, ``description``, ``builds_labels``, ``deploy_labels``,
``url_suffix`` and ``author``.
"""
sections = []
for key, config in sections_config.items():
entries = status.get(key, [])
builds_raw = next((entry["builds"] for entry in entries if "builds" in entry), {})
deploy_raw = next((entry["deploy"] for entry in entries if "deploy" in entry), {})
build_labels = config.get("builds_labels", {})
deploy_labels = config.get("deploy_labels", {})
url = run_url
if run_url and config.get("url_suffix"):
url = f"{run_url}{config['url_suffix']}"
sections.append(
Section(
title=config["title"],
description=config.get("description", ""),
builds=[
StepResult(name=build_labels.get(name, name), passed=passed, log_url=run_url)
for name, passed in builds_raw.items()
],
deploys=[
StepResult(name=deploy_labels.get(name, name), passed=passed, log_url=run_url)
for name, passed in deploy_raw.items()
],
url=url,
author=config.get("author", "Gitea CI"),
)
)
return sections