Mise à jour: migration de gitlab --> Forgejo

This commit is contained in:
Mathis 2026-07-11 21:42:45 +02:00
parent 0e6a14dd10
commit d8ef20ba8c
5 changed files with 61 additions and 18 deletions

View file

@ -8,15 +8,31 @@ from typing import Optional, List
forgejo_internal_logger = logging.getLogger("ForgejoClient")
forgejo_internal_logger.setLevel(logging.INFO)
# Alias de compatibilité pour les anciens imports du bot
gitlab_internal_logger = forgejo_internal_logger
class ForgejoClient:
# MAP REEL DES LABELS (Pêchés directement depuis API Forgejo)
LABEL_MAPPING = {
"bug": 10,
"suggestion": 11, # Redirige "suggestion" vers "enhancement"
"enhancement": 11, # ID de ton étiquette bleue
"manual-report": 15,
"manual-suggestion": 16
}
def __init__(self):
self.token = os.getenv("FORGEJO_TOKEN")
self.owner = os.getenv("FORGEJO_OWNER") # Exemple: "Gameur"
self.repo = os.getenv("FORGEJO_REPO") # Exemple: "kuby"
self.assignee = os.getenv("FORGEJO_ASSIGNEE") # Nom d'utilisateur (optionnel)
self.assignee = os.getenv("FORGEJO_ASSIGNEE") # Pseudo string (optionnel)
# URL de base automatique via ton Tailscale
self.base_url = os.getenv("FORGEJO_URL", "https://omegakubeserv.tail951d2f.ts.net").rstrip("/")
# URL de base automatique via ton Tailscale.
# FIX DE SECURITE : On force le protocole HTTP brut pour éviter l'erreur "ssl:default" sur le port 80
configured_url = os.getenv("FORGEJO_URL", "http://omegakubeserv.tail951d2f.ts.net").strip().rstrip("/")
if configured_url.startswith("https://"):
configured_url = configured_url.replace("https://", "http://", 1)
self.base_url = configured_url
# Construction de l'URL de l'API v1 standard de Forgejo/Gitea
if "api/v1" not in self.base_url:
@ -26,11 +42,11 @@ class ForgejoClient:
async def create_issue(self, title: str, description: str, labels: Optional[List[str]] = None) -> Optional[dict]:
"""
Crée un ticket sur Forgejo.
Crée un ticket sur Forgejo avec les bons IDs numériques de labels.
"""
if not self.token or not self.owner or not self.repo:
if not hasattr(self, '_config_warned'):
print("⚠️ L'intégration Forgejo n'est pas configurée.")
forgejo_internal_logger.warning("⚠️ L'intégration Forgejo n'est pas configurée (token/owner/repo manquants).")
self._config_warned = True
return None
@ -39,23 +55,30 @@ class ForgejoClient:
"Content-Type": "application/json"
}
# Payload au format Forgejo (JSON)
# CONVERSION DES LABELS : On transforme les chaînes ("bug") en entiers (10) attendus par l'API Go
forgejo_label_ids = []
if labels:
for label in labels:
label_id = self.LABEL_MAPPING.get(label.lower())
if label_id:
forgejo_label_ids.append(label_id)
# Payload au format Forgejo strict
payload = {
"title": title,
"body": description, # 'description' devient 'body'
"labels": labels if labels else [] # Devient une vraie liste []
"body": description,
"labels": forgejo_label_ids # Reçoit désormais un tableau d'int64 (ex: [10])
}
if self.assignee:
payload["assignees"] = [self.assignee] # Liste de pseudos strings
payload["assignees"] = [self.assignee]
async with aiohttp.ClientSession() as session:
timeout = aiohttp.ClientTimeout(total=15)
async with aiohttp.ClientSession(timeout=timeout) as session:
try:
# Forgejo attend du JSON strict (json=payload)
async with session.post(self.api_url, headers=headers, json=payload) as response:
if response.status == 201:
result = await response.json()
# Forgejo renvoie l'URL dans 'html_url' au lieu de 'web_url'
forgejo_internal_logger.info(f"✅ Forgejo issue créée : {result.get('html_url')}")
return result
else:
@ -74,7 +97,6 @@ class ForgejoClient:
return None
headers = {"Authorization": f"token {self.token}"}
# GitLab utilise 'opened', Forgejo utilise 'open'
forgejo_state = "open" if state == "opened" else state
params = {
@ -105,7 +127,6 @@ class ForgejoClient:
return []
headers = {"Authorization": f"token {self.token}"}
# Forgejo utilise 'since' au format ISO pour filtrer par date
yesterday = (datetime.now(timezone.utc) - timedelta(days=1)).isoformat()
params = {
@ -147,5 +168,6 @@ class ForgejoClient:
forgejo_internal_logger.error(f"❌ Erreur connexion API Forgejo : {e}")
return None
# Instance unique
gitlab_client = ForgejoClient() # Nom conservé pour éviter de réécrire les imports du bot
# --- SÉCURITÉ ET ALIAS DE COMPATIBILITÉ ---
GitLabClient = ForgejoClient
gitlab_client = ForgejoClient() # Singleton conservé sous l'ancien nom pour le reste du bot