Merge branch 'feat/bugreport' into fix/installer-wizard

Conflict resolution, file by file:

- interactive-defaults.ks: their %pre partitioning wins. It targets the largest
  NON-REMOVABLE disk instead of "clearpart --all" (which wiped every disk,
  including the user's Windows) and picks the disk label from the firmware
  (UEFI -> gpt, BIOS -> msdos) instead of forcing MBR everywhere. That
  supersedes my "let blivet decide" change. My GRUB fixes merged cleanly on top
  and are still needed: their branch still carried the broken ESP detection
  (awk on PARTTYPENAME, where "EFI System" contains a space and never matches),
  in the kickstart and twice in fws-grub-finalize, which they do not touch.

- build.sh: theirs for the rsync:// mirrorlist purge, the fws-bugreport syntax
  check and the systemd-networkd masking (networkd and NetworkManager were
  fighting over the same interfaces on the live). Their systemd-only symlink
  repair loop is dropped as redundant: the general restoration also covers
  /etc/resolv.conf and the gpt-auto-generator mask, which their loop missed.

- fws-bugreport replaces my fws-report-bug, which is deleted: theirs is the
  fuller tool (GTK form with a console fallback, exact JSON payload shown
  before sending, journal filtering, .desktop launcher). .xinitrc keeps my
  in-window buttons -- "Envoyer le rapport" and "Redémarrer" on the log window
  itself, retryable without losing the report -- but they now call
  fws-bugreport.

- profiledef.sh: their permission entry, mine removed with the tool.

- CHANGELOG.rst: both sets of entries. Two of mine were rewritten because the
  merge made them false (my reporting tool no longer exists, and my partition
  table change is superseded).

Untouched by their branch, so kept as is: the step-by-step wizard, the
next/back navigation and its transitions, the default desktop.

Signed-off-by: nocode <suzuku295@gmail.com>
This commit is contained in:
nocode committed 2026-09-09 11:40:03 +02:00
commit 0cf865a927
14 files changed
+1026 -319

No files matched your search

@@ -0,0 +1,699 @@
#!/usr/bin/env python3
# FWS — « Signaler un problème » : envoi OPTIONNEL et validé par l'utilisateur
# de logs aux développeurs. Rien n'est collecté ni envoyé sans action
# explicite : l'utilisateur remplit le formulaire, voit le payload JSON EXACT
# qui partira (infos système + extrait du journal inclus si la case est
# cochée), puis confirme l'envoi. Aucun daemon, aucune collecte en
# arrière-plan, aucun envoi automatique.
#
# L'envoi passe par curl vers l'API bugs du projet — tout part par CE curl,
# rien d'autre ne quitte la machine :
# curl -X POST https://fws.laxacube.ch/api/bugs.php
# -H "Content-Type: application/json"
# -d '{"app":"FWS","version":"0.7.0","type":"bug","title":"…","description":"…"}'
#
# Usages :
# fws-bugreport → fenêtre GTK (menu « Signaler un problème »)
# fws-bugreport --file <chemin> → pré-remplit la description avec un fichier
# de logs existant (écran de debug du live)
# fws-bugreport --tui → assistant console (repli sans X / SSH)
#
# Vérifier qu'un envoi est bien parti : la réponse du serveur (code HTTP +
# message, ex. « HTTP 201 — Signalement enregistré. Merci ! (id 13) ») est
# affichée et tracée dans /tmp/fws-bugreport.log.
#
# GTK3 : présent sur tous les bureaux FWS et sur le live (via Anaconda) ;
# sans GTK joignable, l'assistant console prend le relais automatiquement.
import json
import os
import re
import subprocess
import sys
import time
import traceback
# Trace locale de chaque tentative d'envoi (date, code HTTP, réponse du
# serveur) — la façon de vérifier qu'un rapport est bien parti :
# cat /tmp/fws-bugreport.log
_LOG_PATH = "/tmp/fws-bugreport.log"
_URL = "https://fws.laxacube.ch/api/bugs.php"
_APP = "FWS"
# (valeur envoyée au serveur, libellé affiché)
_TYPES = [
("bug", "Bug / panne"),
("question", "Question"),
("suggestion", "Suggestion"),
("other", "Autre"),
]
try:
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0") # sinon gi charge Gdk 4.0 (conflit Gtk3)
from gi.repository import Gdk, GLib, Gtk # noqa: E402
_HAS_GTK = True
except Exception: # noqa: BLE001 — pas de GTK (système CLI, live minimal…)
_HAS_GTK = False
# ── Informations système (mêmes sources que fws-about) ───────────────────────
def _osrelease():
data = {}
for path in ("/etc/os-release", "/usr/lib/os-release",
"/usr/local/share/fws/os-release"):
try:
with open(path) as fh:
for line in fh:
m = re.match(r'^([A-Z_]+)=(.*)$', line.strip())
if m:
data[m.group(1)] = m.group(2).strip('"')
if data:
break
except OSError:
continue
return data
def _cmd(*argv):
try:
return subprocess.check_output(
argv, text=True, errors="replace",
stderr=subprocess.DEVNULL, timeout=10).strip()
except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired):
return ""
def _cpu():
try:
with open("/proc/cpuinfo") as fh:
for line in fh:
if line.startswith("model name"):
return line.split(":", 1)[1].strip()
except OSError:
pass
return "inconnu"
def _mem():
try:
with open("/proc/meminfo") as fh:
for line in fh:
if line.startswith("MemTotal"):
return f"{int(line.split()[1]) / 1048576:.1f} Gio"
except OSError:
pass
return "inconnue"
def _gpus():
out = []
for line in _cmd("lspci").splitlines():
low = line.lower()
if "vga" in low or "3d" in low or "display" in low:
out.append(line.split(":", 2)[-1].strip())
return out or ["inconnu"]
def _disks():
out = []
for line in _cmd("lsblk", "-dno", "NAME,SIZE,MODEL,TYPE").splitlines():
f = line.split()
if f and f[-1] == "disk":
out.append(" ".join(f[:-1]))
return out or ["inconnu"]
def _desktop():
if os.environ.get("HYPRLAND_INSTANCE_SIGNATURE"):
return "Hyprland"
return (os.environ.get("XDG_CURRENT_DESKTOP")
or os.environ.get("DESKTOP_SESSION") or "inconnu")
def _session_type():
t = os.environ.get("XDG_SESSION_TYPE", "")
return {"wayland": "Wayland", "x11": "X11"}.get(t, t or "inconnu")
def _tail(path, max_lines):
try:
with open(path, errors="replace") as fh:
lines = fh.readlines()
if len(lines) > max_lines:
lines = lines[-max_lines:]
return "".join(lines).rstrip()
except OSError:
return ""
def _system_summary(osr):
rows = [
("Système", osr.get("PRETTY_NAME") or "FWS Linux"),
("Version", osr.get("VERSION_ID") or "inconnue"),
("Build", osr.get("BUILD_ID", "rolling")),
("Noyau", _cmd("uname", "-r") or "inconnu"),
("Bureau", _desktop()),
("Affichage", _session_type()),
("Processeur", _cpu()),
("Mémoire", _mem()),
("Carte(s) graphique(s)", " ; ".join(_gpus())),
("Disque(s)", " ; ".join(_disks())),
]
return "\n".join(f"{k}: {v}" for k, v in rows)
def _journal_excerpt(max_lines=200):
"""Extrait du journal (avertissements/erreurs) du dernier démarrage.
Retourne (accessible, texte) : accessible=False si le journal n'a pas pu
être lu ; sinon le texte filtré, éventuellement vide si le démarrage ne
contenait aucun warning/erreur utile.
"""
try:
out = subprocess.check_output(
["journalctl", "-b", "-p", "warning", "--no-pager"],
text=True, errors="replace",
stderr=subprocess.DEVNULL, timeout=20).strip()
except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired):
return False, ""
lines = out.splitlines()
# BRUIT DE L'INSTALLATEUR (vu en réel sur bare metal, 2 ISO successives) :
# les modules D-Bus d'Anaconda journalisent leur debug SANS marqueur de
# priorité exploitable — dumps parted (PedPartition 0x…), rapports JSON LVM,
# listing des 42 tâches, sortie mkfs (« Superblock backups stored on… ») —
# en INFO/DEBUG journald, donc journalctl -p warning les renvoie quand même,
# et un filtre à marqueur INFO:/DEBUG: les laisse passer. Un filtre général
# risquerait d'écraser de VRAIS problèmes d'autres services → on cible :
# pour les unités org.fedoraproject.Anaconda.* on garde UNIQUEMENT les
# messages marqués ERROR:/WARNING: — plus les lignes non marquées d'un
# traceback Python toujours signifiantes (« Traceback (most recent call
# last): », cadres « File "…", line … » et exception finale, ex.
# « FileNotFoundError: [Errno 2] … ») — tout le reste du journal passe
# sans toucher.
def _jbody(line):
m = re.search(r"\[\d+\]: ", line)
return line[m.end():] if m else line
kept = []
for ln in lines:
if "org.fedoraproject.Anaconda." not in ln:
kept.append(ln)
continue
body = _jbody(ln).lstrip()
if (re.search(r"\b(?:ERROR|WARNING):", ln)
or body.startswith("Traceback (most recent call last):")
or body.startswith('File "')
or re.match(r"^\w[\w.]*(?:Error|Exception)\b", body)):
kept.append(ln)
lines = kept
# « WARNING:py.warnings:… DeprecationWarning: … » : bruit de développement
# de l'installateur (la même ligne est répétée par chacun des ~12 modules
# D-Bus d'Anaconda), pas un problème machine — retiré, sauf côté noyau où
# un warning resterait significatif.
lines = [ln for ln in lines
if "DeprecationWarning:" not in ln or re.search(r" kernel: ", ln)]
# « kernel: ntfs3… » : flot massif émis par le pilote ntfs3 quand
# l'installateur SONDE la partition Windows (« Correct links count -> N »
# pour des centaines d'inodes, « N callbacks suppressed »). C'est la
# correction de liens du système de fichiers Windows pendant la détection
# des disques — pas un problème FWS, inexploitable dans un rapport (vu en
# réel sur bare metal : des dizaines de lignes). Retiré ; un vrai problème
# de disque reste signalé ailleurs (kernel: ata/ahci/nvme…).
lines = [ln for ln in lines if " kernel: ntfs3" not in ln]
# Reliques du build (checkout Windows → fichiers PLATS à la place des
# symlinks systemd, corrigées à la source dans build.sh mais présentes
# dans les anciennes ISO) : « Failed to preset all unit … already
# exists » et « … is not a symlink, ignoring » — bruit sans valeur de
# diagnostic.
lines = [ln for ln in lines
if ("Failed to preset all unit" not in ln
and "is not a symlink, ignoring" not in ln
and "Wants dependency dropin" not in ln)]
# « anaconda: kickstart: Command X will be parsed in DBus module. » :
# trace de debug du parseur de kickstart, sans information.
lines = [ln for ln in lines
if "will be parsed in DBus module" not in ln]
# 1) DÉDUPLICATION GLOBALE (vu en réel sur bare metal) : un service en
# échec boucle (xdg-desktop-portal-gtk sans session graphique) et les
# modules D-Bus répètent les mêmes warnings — le rapport se noie sous les
# doublons. Clé = ligne sans horodatage NI chiffres (« 125 »/« 11 » et
# [pids] s'effacent) : les répétitions à variable numérique près se
# fusionnent (ex. « fan_curve… (0x110024/25/32) failed » → 1 ligne [×3]),
# la 1re occurrence garde sa place, marquée « [×N] » — rien n'est perdu,
# le compte reste lisible.
_stamp_re = re.compile(r"^[A-Z][a-z]{2} +\d+ +\d\d:\d\d:\d\d +")
seen = {}
order = []
out = []
for ln in lines:
m = _stamp_re.match(ln)
key = re.sub(r"\d+", "#", (ln[m.end():] if m else ln).strip())
if key in seen:
seen[key] += 1
continue
seen[key] = 1
order.append(key)
out.append(ln)
lines = [ln + (f" [×{seen[k]}]" if seen[k] > 1 else "")
for ln, k in zip(out, order)]
# 2) PLAFOND PAR SOURCE : même uniques, les lignes d'une source en tempête
# restent des dizaines (xdg-desktop-portal essaie chaque interface du
# portail l'une après l'autre) — au-delà de 8 lignes de la même source, la
# suite est omise avec une note explicite. Le noyau n'est pas concerné
# (pas de [pid] journald dans ses lignes). L'identifiant journald peut
# être un chemin (« /usr/lib/xdg-desktop-portal[856] ») → l'hostname et
# l'ident sont séparés par une espace, d'où « \S+ +(.+?)\[pid\] ».
def _src(line):
m = re.match(r"^[A-Z][a-z]{2} +\d+ +\d\d:\d\d:\d\d +\S+ +(.+?)\[\d+\]: ", line)
return m.group(1) if m else None
capped, counts, omitted = [], {}, {}
def _note(src, n):
return (f" (… +{n} autres lignes de « {src} » omises — "
"spam répétitif ; journal complet : journalctl -b -p warning)")
for ln in lines:
src = _src(ln)
if src is not None and counts.get(src, 0) >= 8:
omitted[src] = omitted.get(src, 0) + 1
continue
if src is not None:
counts[src] = counts.get(src, 0) + 1
if omitted.get(src):
capped.append(_note(src, omitted[src]))
omitted[src] = 0
capped.append(ln)
for src, n in omitted.items():
if n:
capped.append(_note(src, n))
lines = capped
if len(lines) > max_lines:
lines = lines[-max_lines:]
return True, "\n".join(lines)
def _collect_diagnostics(osr):
parts = ["===== Informations système =====", _system_summary(osr)]
post_log = "/var/log/fws-post.log"
if os.path.isfile(post_log):
tail = _tail(post_log, 100)
if tail:
parts += ["", "===== Log d'installation FWS (fin) =====", tail]
journal_ok, journal = _journal_excerpt()
if journal:
parts += ["", "===== Journal du dernier démarrage "
"(avertissements / erreurs) =====", journal]
elif journal_ok:
# Journal lisible mais rien d'utile après filtrage du bruit : mieux
# vaut le dire que d'insinuer que le journal était inaccessible.
parts += ["", "===== Journal du dernier démarrage "
"(avertissements / erreurs) =====",
"(aucune entrée warning/erreur utile dans le journal)"]
else:
parts += ["", "(journal du dernier démarrage inaccessible — "
"lance fws-bugreport depuis un terminal avec sudo "
"pour l'inclure)"]
return "\n".join(parts)
def _build_payload(osr, typ, title, description, include_diag):
description = description.strip()
if include_diag:
diag = _collect_diagnostics(osr)
description = f"{description}\n\n{diag}" if description else diag
return {
"app": _APP,
"version": osr.get("VERSION_ID") or "unknown",
"type": typ,
"title": title,
"description": description,
}
# ── Envoi (un seul curl, comme spécifié) ─────────────────────────────────────
def _trace(lines):
try:
with open(_LOG_PATH, "a",
encoding="utf-8", errors="replace") as fh:
fh.write("\n".join(lines) + "\n")
except OSError:
pass
def _send(payload):
data = json.dumps(payload, ensure_ascii=False).encode("utf-8", "replace")
# Le corps passe par stdin (--data-binary @-) : pas de limite de taille
# d'argument (le journal peut faire des centaines de Ko) et aucun souci
# de quoting. -w ajoute le code HTTP en dernière ligne de stdout.
try:
proc = subprocess.run(
["curl", "-sS", "--max-time", "30", "-X", "POST", _URL,
"-H", "Content-Type: application/json",
"--data-binary", "@-",
"-w", "\n%{http_code}"],
input=data, capture_output=True, timeout=45)
except OSError as exc:
_trace([f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] ÉCHEC — "
f"curl introuvable : {exc}"])
return False, f"curl introuvable : {exc}"
except subprocess.TimeoutExpired:
_trace([f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] ÉCHEC — délai "
"dépassé (30 s)"])
return False, "Délai dépassé (30 s) — vérifie ta connexion réseau."
out = proc.stdout.decode("utf-8", "replace")
err = proc.stderr.decode("utf-8", "replace")
parts = out.rsplit("\n", 1)
body = parts[0] if len(parts) == 2 else out
code = parts[-1].strip()
if proc.returncode != 0:
detail = err.strip() or body.strip()
_trace([f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] ÉCHEC curl "
f"(code {proc.returncode}) : {detail[:300]}"])
return False, detail or f"curl a échoué (code {proc.returncode})."
# Le serveur répond en JSON : {"ok":true,"id":…,"message":…}. Un code
# HTTP ≥ 400 ne fait PAS échouer curl — on le détecte ici, sinon l'utilisateur
# verrait « envoyé ✔ » alors que rien n'a été enregistré.
ok = code.startswith("2")
msg = body.strip()
rid = ""
try:
j = json.loads(body)
if isinstance(j, dict):
ok = bool(j.get("ok")) and code.startswith("2")
if j.get("message"):
msg = str(j["message"])
if j.get("id"):
rid = f" (id {j['id']})"
except ValueError:
pass
_trace([f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {_URL} "
f"app={payload.get('app')} type={payload.get('type')} "
f"titre={payload.get('title')!r} payload={len(data)} o "
f"→ HTTP {code or '?'} ok={ok} {msg[:200]}{rid}"])
if ok:
return True, f"HTTP {code or '?'} — {msg}{rid}"
return False, (f"HTTP {code or '?'} — {msg or 'réponse vide'}. "
"Le serveur a refusé le rapport.")
# ── Assistant console (repli sans X) ─────────────────────────────────────────
def _tui(preload_path):
# Robustesse locale : l'assistant console peut tourner dans une console
# non-UTF-8 (Windows…). On force UTF-8 avec remplacement plutôt que de
# crasher sur les caractères accentués/boîtes.
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
sys.stdin.reconfigure(encoding="utf-8", errors="replace")
except (AttributeError, ValueError, OSError):
pass
def ask(prompt, default=""):
try:
return input(prompt).strip() or default
except EOFError:
return default
print("FWS — « Signaler un problème » (envoi optionnel de logs)")
print("Rien ne sera envoyé sans ta confirmation.\n")
if preload_path:
try:
with open(preload_path, errors="replace") as fh:
description = fh.read().strip()
print(f"Logs chargés depuis {preload_path} "
f"({len(description)} caractères).")
except OSError as exc:
print(f" ⚠ Impossible de lire {preload_path} : {exc}")
description = ""
else:
description = ""
valid_types = [v for v, _l in _TYPES]
if not description:
print("Type (défaut : bug) : " + ", ".join(valid_types))
typ = ask("> ", "bug")
if typ not in valid_types:
typ = "bug"
title = ask("Titre : ")
print("Description (ligne vide pour terminer) :")
lines = []
while True:
line = ask("> ")
if not line:
break
lines.append(line)
description = "\n".join(lines)
else:
typ = ask("Type (défaut : bug) : ", "bug")
if typ not in valid_types:
typ = "bug"
title = ask("Titre : ")
if not title:
print(" ⚠ Titre obligatoire — envoi annulé.")
return 1
osr = _osrelease()
payload = _build_payload(osr, typ, title, description, include_diag=True)
print("\n─── Aperçu de ce qui sera envoyé à", _URL, "───")
print(json.dumps(payload, ensure_ascii=False, indent=2))
if ask("\nEnvoyer ? [o/N] ", "n").lower() not in ("o", "oui", "y", "yes"):
print("Envoi annulé.")
return 0
ok, msg = _send(payload)
print(("✔ " if ok else "✖ ") + msg)
if not ok:
print(f"Détails : {_LOG_PATH}")
return 0 if ok else 1
# ── Fenêtre GTK (uniquement si GTK est disponible) ───────────────────────────
if _HAS_GTK:
def _preview_dialog(parent, payload):
dlg = Gtk.Dialog(title="Confirmer l'envoi", transient_for=parent,
modal=True, destroy_with_parent=True)
dlg.set_default_size(680, 520)
dlg.set_position(Gtk.WindowPosition.CENTER)
dlg.add_buttons("Annuler", Gtk.ResponseType.CANCEL,
"Confirmer l'envoi", Gtk.ResponseType.OK)
box = dlg.get_content_area()
box.set_spacing(10)
box.set_border_width(14)
note = Gtk.Label()
note.set_markup(
"<b>Voici EXACTEMENT ce qui sera envoyé</b> à "
"<span font_family='monospace'>https://fws.laxacube.ch/api/bugs.php</span> :")
note.set_line_wrap(True)
note.set_xalign(0)
box.pack_start(note, False, False, 0)
scroll = Gtk.ScrolledWindow()
scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
view = Gtk.TextView()
view.set_editable(False)
view.set_cursor_visible(False)
view.set_monospace(True)
view.get_buffer().set_text(
json.dumps(payload, ensure_ascii=False, indent=2))
scroll.add(view)
box.pack_start(scroll, True, True, 0)
dlg.show_all()
response = dlg.run()
dlg.destroy()
return response == Gtk.ResponseType.OK
def _message(parent, kind, title, text):
msg_type = (Gtk.MessageType.ERROR if kind == "error"
else Gtk.MessageType.INFO)
dlg = Gtk.MessageDialog(transient_for=parent, modal=True,
message_type=msg_type,
buttons=Gtk.ButtonsType.CLOSE,
text=title)
if text:
dlg.format_secondary_text(text)
dlg.run()
dlg.destroy()
class BugReportWindow(Gtk.Window):
def __init__(self, preload_path=None):
super().__init__(title="Signaler un problème — FWS")
self.set_icon_name("fws-bugreport")
self.set_default_size(580, -1)
self.set_position(Gtk.WindowPosition.CENTER)
self.set_border_width(18)
# DIALOGUE : les tuileurs (i3/Hyprland) gardent les dialogues en
# flottant → taille naturelle au lieu d'être étirée.
self.set_type_hint(Gdk.WindowTypeHint.DIALOG)
self.set_resizable(False)
self.connect("destroy", Gtk.main_quit)
self._osr = _osrelease()
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
self.add(box)
title = Gtk.Label()
title.set_markup(
"<span size='x-large' weight='bold'>Signaler un problème</span>")
box.pack_start(title, False, False, 0)
subtitle = Gtk.Label(
label="Un souci avec FWS ? Décris-le ci-dessous. Les informations "
"système et les logs de diagnostic peuvent être joints pour "
"aider les développeurs. Rien ne part sans ta confirmation.")
subtitle.set_line_wrap(True)
subtitle.set_xalign(0)
box.pack_start(subtitle, False, False, 0)
grid = Gtk.Grid(column_spacing=10, row_spacing=8)
grid.set_halign(Gtk.Align.FILL)
grid.attach(Gtk.Label(label="Type :", xalign=1), 0, 0, 1, 1)
self._type = Gtk.ComboBoxText()
for value, label in _TYPES:
self._type.append(value, label)
self._type.set_active(0)
grid.attach(self._type, 1, 0, 1, 1)
grid.attach(Gtk.Label(label="Titre :", xalign=1), 0, 1, 1, 1)
self._title = Gtk.Entry()
self._title.set_placeholder_text("Résumé court du problème")
grid.attach(self._title, 1, 1, 1, 1)
box.pack_start(grid, False, False, 0)
desc_label = Gtk.Label(label="Description :", xalign=0)
box.pack_start(desc_label, False, False, 0)
scroll = Gtk.ScrolledWindow()
scroll.set_min_content_height(130)
scroll.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
self._description = Gtk.TextView()
self._description.set_wrap_mode(Gtk.WrapMode.WORD)
self._description.set_placeholder_text(
"Ce qui s'est passé, ce que tu attendais, ce que tu as essayé…")
scroll.add(self._description)
box.pack_start(scroll, False, False, 0)
if preload_path:
try:
with open(preload_path, errors="replace") as fh:
content = fh.read()
self._description.get_buffer().set_text(content)
loaded = Gtk.Label()
loaded.set_markup(
f"<span size='small' foreground='#89b4fa'>Logs chargés "
f"depuis <span font_family='monospace'>{preload_path}"
f"</span> — tu peux les compléter ou les retirer.</span>")
loaded.set_line_wrap(True)
loaded.set_xalign(0)
box.pack_start(loaded, False, False, 0)
except OSError as exc:
_message(self, "error", "Fichier illisible",
f"{preload_path} : {exc}")
self._include = Gtk.CheckButton(
label="Joindre les informations système et les logs de diagnostic")
self._include.set_active(True)
self._include.set_tooltip_text(
"Version FWS, matériel détecté, extrait du journal du dernier "
"démarrage — à relire dans l'aperçu avant l'envoi")
box.pack_start(self._include, False, False, 4)
footer = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
cancel = Gtk.Button(label="Fermer")
cancel.connect("clicked", lambda _b: self.close())
send = Gtk.Button(label="Envoyer…")
send.get_style_context().add_class("suggested-action")
send.connect("clicked", self._on_send)
footer.pack_end(send, False, False, 0)
footer.pack_end(cancel, False, False, 0)
box.pack_start(footer, False, False, 6)
self._title.connect("activate", self._on_send)
def _on_send(self, _widget=None):
# Un crash ne doit JAMAIS mourir en silence (le lancement depuis
# l'écran de debug du live redirige stderr vers /dev/null) : on
# trace et on affiche.
try:
self._do_send()
except Exception as exc: # noqa: BLE001
_trace(["=== CRASH fws-bugreport ===",
traceback.format_exc()])
_message(self, "error", "Erreur inattendue",
f"{exc}\n\nDétails : {_LOG_PATH}")
def _do_send(self):
title = self._title.get_text().strip()
buf = self._description.get_buffer()
description = buf.get_text(buf.get_start_iter(),
buf.get_end_iter(), True).strip()
include = self._include.get_active()
if not title:
_message(self, "error", "Titre manquant",
"Indique un titre court pour le problème.")
return
if not description and not include:
_message(self, "error", "Rapport vide",
"Écris une description ou coche la jointure des "
"informations système et des logs.")
return
typ = self._type.get_active_id() or "bug"
payload = _build_payload(self._osr, typ, title, description, include)
if not _preview_dialog(self, payload):
return
ok, msg = _send(payload)
if ok:
_message(self, "info", "Rapport envoyé ✔",
f"{msg}\n\nMerci ! L'équipe FWS a reçu ton rapport.\n"
f"(trace : {_LOG_PATH})")
else:
_message(self, "error", "Envoi impossible",
f"{msg}\n\nTon rapport n'a pas été envoyé. Vérifie ta "
f"connexion et réessaie.\nDétails : {_LOG_PATH}")
def main():
args = sys.argv[1:]
preload = None
if "--file" in args:
i = args.index("--file")
if i + 1 < len(args):
preload = args[i + 1]
if _HAS_GTK and "--tui" not in args and Gtk.init_check()[0]:
GLib.set_prgname("fws-bugreport")
win = BugReportWindow(preload)
win.show_all()
Gtk.main()
return 0
return _tui(preload)
if __name__ == "__main__":
raise SystemExit(main())
@@ -1,225 +0,0 @@
#!/usr/bin/env python3
"""FWS — envoi d'un signalement à l'API de suivi de bugs.
POURQUOI EN PYTHON : le contenu envoyé est du JSON contenant des LOGS bruts
(guillemets, antislashs, accents, sauts de ligne). Le construire à la main en
shell casse à la première ligne de log contenant un guillemet ; json.dumps
échappe correctement. python3 est de toute façon garanti sur le live (Anaconda
en dépend) et sur le système installé (copie du live) — pas de dépendance en
plus, et urllib évite même d'avoir besoin de curl.
CONTRAT DE L'API (POST JSON sur $FWS_BUG_API) :
app, version, type, title, description, email, system_info, logs
« type » ∈ bug | crash | installation | suggestion | autre.
Réponse : 201 {"ok":true,"id":N,"message":…} ou {"ok":false,"error":…}.
Utilisation :
fws-report-bug --type installation --logs /tmp/fws-debug.txt \\
--title "Installation interrompue"
fws-report-bug --gui --logs /tmp/fws-debug.txt # demande la description
RIEN N'EST ENVOYÉ SANS ACTION EXPLICITE : ce script n'est jamais appelé
automatiquement, seulement derrière une confirmation de l'utilisateur (cf. le
harnais de diagnostic du .xinitrc) ou à la main. L'e-mail est facultatif et
n'est joint que s'il est passé en argument.
"""
import argparse
import json
import os
import platform
import shutil
import subprocess
import sys
import urllib.error
import urllib.request
API = os.environ.get("FWS_BUG_API", "https://fws.laxacube.ch/api/bugs.php")
TIMEOUT = 25
# Les logs d'installation peuvent peser plusieurs Mo (journal complet). On
# n'envoie que la FIN : c'est là que se trouve l'erreur, et ça garde la requête
# sous les limites d'upload d'un PHP par défaut.
MAX_LOG_CHARS = 200_000
def _run(cmd):
"""Sortie d'une commande, ou chaîne vide — un rapport ne doit jamais planter."""
try:
out = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
return (out.stdout or "").strip()
except Exception: # pylint: disable=broad-except
return ""
def _os_release():
data = {}
for path in ("/etc/os-release", "/usr/lib/os-release"):
try:
with open(path, encoding="utf-8") as fh:
for line in fh:
if "=" in line and not line.startswith("#"):
key, _, val = line.partition("=")
data[key.strip()] = val.strip().strip('"')
break
except OSError:
continue
return data
def collect_system_info():
"""Matériel et environnement — rien de nominatif (ni user, ni hostname)."""
osr = _os_release()
bits = [
f"{osr.get('NAME', 'FWS')} {osr.get('VERSION_ID', '?')}",
f"noyau {platform.release()}",
"UEFI" if os.path.isdir("/sys/firmware/efi") else "BIOS",
]
virt = _run(["systemd-detect-virt"])
bits.append(f"virtualisation {virt}" if virt and virt != "none" else "matériel réel")
cpu = ""
try:
with open("/proc/cpuinfo", encoding="utf-8") as fh:
for line in fh:
if line.startswith("model name"):
cpu = line.split(":", 1)[1].strip()
break
except OSError:
pass
if cpu:
bits.append(f"CPU {cpu}")
try:
with open("/proc/meminfo", encoding="utf-8") as fh:
for line in fh:
if line.startswith("MemTotal:"):
bits.append(f"RAM {int(line.split()[1]) // 1024} Mio")
break
except OSError:
pass
if shutil.which("lspci"):
gpus = [ln.split(": ", 1)[-1] for ln in _run(["lspci"]).splitlines()
if "VGA compatible controller" in ln or "3D controller" in ln]
if gpus:
bits.append("GPU " + " | ".join(gpus))
disks = _run(["lsblk", "-dno", "NAME,SIZE,MODEL"])
if disks:
bits.append("disques " + " ; ".join(disks.split("\n")))
return "\n".join(bits)
def read_logs(paths):
"""Concatène les fichiers de log lisibles, en gardant la FIN de l'ensemble."""
chunks = []
for path in paths:
try:
with open(path, encoding="utf-8", errors="replace") as fh:
chunks.append(f"########## {path} ##########\n{fh.read()}")
except OSError as err:
chunks.append(f"########## {path} : illisible ({err}) ##########")
text = "\n".join(chunks)
if len(text) > MAX_LOG_CHARS:
text = ("[… début tronqué, seuls les derniers "
f"{MAX_LOG_CHARS} caractères sont envoyés …]\n"
+ text[-MAX_LOG_CHARS:])
return text
def send(payload):
"""POST du signalement. Renvoie (ok, message)."""
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
request = urllib.request.Request(
API, data=body, method="POST",
headers={"Content-Type": "application/json",
"User-Agent": "fws-report-bug/1.0"})
try:
with urllib.request.urlopen(request, timeout=TIMEOUT) as resp:
answer = json.loads(resp.read().decode("utf-8", "replace"))
except urllib.error.HTTPError as err:
detail = err.read().decode("utf-8", "replace")[:400]
return False, f"Le serveur a refusé le signalement (HTTP {err.code}) : {detail}"
except urllib.error.URLError as err:
return False, f"Serveur injoignable ({err.reason}). Vérifiez la connexion Internet."
except Exception as err: # pylint: disable=broad-except
return False, f"Envoi impossible : {err}"
if answer.get("ok"):
return True, f"Signalement envoyé ✔ (numéro {answer.get('id', '?')})"
return False, f"Refusé : {answer.get('error', 'raison inconnue')}"
def ask_description_gui():
"""Demande la description via zenity. None = l'utilisateur a annulé."""
if not shutil.which("zenity"):
return ""
try:
out = subprocess.run(
["zenity", "--entry", "--width=520", "--title=FWS — signaler un problème",
"--text=Décrivez en une phrase ce qui s'est passé "
"(les logs et le matériel sont joints automatiquement) :"],
capture_output=True, text=True, timeout=600)
except Exception: # pylint: disable=broad-except
return ""
if out.returncode != 0:
return None
return (out.stdout or "").strip()
def notify_gui(ok, message):
if not shutil.which("zenity"):
return
subprocess.run(["zenity", "--info" if ok else "--error",
"--width=460", "--title=FWS", f"--text={message}"],
capture_output=True, timeout=300, check=False)
def main():
parser = argparse.ArgumentParser(description="Envoie un signalement à l'équipe FWS.")
parser.add_argument("--type", default="bug",
choices=["bug", "crash", "installation", "suggestion", "autre"])
parser.add_argument("--app", default="FWS")
parser.add_argument("--title", default="")
parser.add_argument("--description", default="")
parser.add_argument("--email", default="", help="facultatif, pour être recontacté")
parser.add_argument("--logs", action="append", default=[],
metavar="FICHIER", help="peut être répété")
parser.add_argument("--gui", action="store_true",
help="demander la description et afficher le résultat via zenity")
args = parser.parse_args()
description = args.description
if args.gui and not description:
description = ask_description_gui()
if description is None:
print("Envoi annulé.")
return 1
title = args.title or (description.splitlines()[0][:120] if description
else f"Signalement {args.type} sans titre")
payload = {
"app": args.app,
"version": _os_release().get("VERSION_ID", ""),
"type": args.type,
"title": title,
"description": description,
"system_info": collect_system_info(),
"logs": read_logs(args.logs) if args.logs else "",
}
if args.email:
payload["email"] = args.email
ok, message = send(payload)
print(message, file=sys.stdout if ok else sys.stderr)
if args.gui:
notify_gui(ok, message)
return 0 if ok else 1
if __name__ == "__main__":
sys.exit(main())
@@ -177,4 +177,5 @@ windowrule = float on, match:class ^([Pp]avucontrol|org.pulseaudio.pavucontrol)$
windowrule = float on, match:class ^(.?[Bb]lueman-manager.*)$
windowrule = float on, match:class ^([Ff]ws-hello)$
windowrule = float on, match:class ^([Ff]ws-about)$
windowrule = float on, match:class ^([Ff]ws-bugreport)$
windowrule = float on, match:title ^(Picture-in-Picture)$
@@ -132,6 +132,7 @@ bindsym XF86MonBrightnessDown exec --no-startup-id brightnessctl set 5%-
for_window [class="floating-term"] floating enable, resize set 900 550
for_window [class="(?i)fws-hello"] floating enable
for_window [class="(?i)fws-about"] floating enable
for_window [class="(?i)fws-bugreport"] floating enable
for_window [class="(?i)pavucontrol"] floating enable, resize set 700 500
for_window [class="(?i)blueman-manager"] floating enable
for_window [title="Picture-in-Picture"] floating enable