111 lines
3.0 KiB
Python
111 lines
3.0 KiB
Python
"""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()
|