Files
Jellyfin-Freebox/src/freebox_jellyfin/boxrules.py
T
stilobiqueandClaude Opus 5.5 1b2acae316
CI / Vérifications et paquet (push) Successful in 48s
CI / Release Gitea (push) Skipped
Add test suite (box rules, Python, QML against a fake Jellyfin server) and local preview jobs
- freebox-jellyfin test: box-only rules (ES5, QtQuick 2.5, qmldir, singletons),
  tooling unit tests, qmltestrunner on tests/qml against fake_server.py
- freebox-jellyfin fake-server and preview --fake-server
- package enforces the box rules; CI runs the tests
- JetBrains run configs: Local Preview, Local Preview (faux serveur), Tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:08:03 +01:00

155 lines
6.8 KiB
Python

"""Règles du Freebox Player que qmlscene (Qt 5.15) et qmllint ne signalent pas sur le PC.
- JavaScript ES5 seulement (Qt 5.5) : ni let/const, ni fonctions fléchées, ni gabarits `…`,
ni class, for…of ou opérateur « ... » ;
- QtQuick 2.5 au plus, pas de QtQuick.Controls, pas d'import "." ;
- chargement HTTP : chaque dossier importé a un qmldir qui liste tous ses types (et seulement
des fichiers existants), au plus un singleton par dossier, et aucun composant du dossier
d'un singleton ne l'utilise (« Cyclic dependency detected »).
Utilisé par `freebox-jellyfin test` et `freebox-jellyfin package`.
"""
import re
from pathlib import Path
ES5_RULES = [
(re.compile(r"\blet\s+[A-Za-z_$\[{]"), "« let » (ES6) : utiliser var"),
(re.compile(r"\bconst\s+[A-Za-z_$\[{]"), "« const » (ES6) : utiliser var"),
(re.compile(r"=>"), "fonction fléchée (ES6) : utiliser function"),
(re.compile(r"`"), "gabarit `…` (ES6) : concaténer des chaînes"),
(re.compile(r"\bclass\s+[A-Za-z_$]"), "class (ES6)"),
(re.compile(r"\bfor\s*\(\s*(?:var\s+)?[A-Za-z_$][\w$]*\s+of\b"), "for…of (ES6)"),
(re.compile(r"\.\.\.[A-Za-z_$\[{(]"), "opérateur « ... » (ES6)"),
]
QTQUICK_MAX = (2, 5)
IMPORT_RE = re.compile(r'^\s*import\s+(?:"([^"]+)"|([\w.]+)\s+(\d+)\.(\d+))', re.M)
def strip_code(text):
"""Remplace commentaires et contenu des chaînes par des espaces (lignes conservées).
Les littéraux d'expression régulière sont gardés tels quels : « // » n'y est pris pour un
commentaire que s'il n'est pas précédé d'une barre oblique inverse.
"""
out = []
i, n = 0, len(text)
while i < n:
c = text[i]
if c == "/" and i + 1 < n and text[i + 1] == "/" and (i == 0 or text[i - 1] != "\\"):
end = text.find("\n", i)
end = n if end < 0 else end
out.append(" " * (end - i))
i = end
elif c == "/" and i + 1 < n and text[i + 1] == "*":
end = text.find("*/", i + 2)
end = n if end < 0 else end + 2
out.append(re.sub(r"[^\n]", " ", text[i:end]))
i = end
elif c in "\"'":
j = i + 1
while j < n and text[j] != c and text[j] != "\n":
j += 2 if text[j] == "\\" else 1
out.append(c + " " * (min(j, n) - i - 1) + (c if j < n and text[j] == c else ""))
i = j + 1 if j < n and text[j] == c else j
else:
out.append(c)
i += 1
return "".join(out)
def check_es5(path, text):
problems = []
for number, line in enumerate(strip_code(text).splitlines(), 1):
for pattern, message in ES5_RULES:
if pattern.search(line):
problems.append("%s:%d: %s" % (path, number, message))
return problems
def check_imports(path, text):
problems = []
for match in IMPORT_RE.finditer(text): # une ligne commentée ne commence pas par « import »
line = text.count("\n", 0, match.start()) + 1
target, module = match.group(1), match.group(2)
if target is not None:
if target in (".", "./"):
problems.append("%s:%d: import \".\" interdit (cycle en chargement HTTP)" % (path, line))
continue
version = (int(match.group(3)), int(match.group(4)))
if module == "QtQuick" and version > QTQUICK_MAX:
problems.append("%s:%d: QtQuick %d.%d trop récent pour la box (2.5 au plus)"
% (path, line, version[0], version[1]))
if module.startswith("QtQuick.Controls"):
problems.append("%s:%d: QtQuick.Controls absent de la box" % (path, line))
return problems
def _qmldir_entries(qmldir):
"""[(type, singleton?, fichier)] d'un fichier qmldir."""
entries = []
for raw in qmldir.read_text(encoding="utf-8").splitlines():
parts = raw.split("#")[0].split()
if not parts or parts[0] in ("module", "plugin", "classname", "typeinfo", "depends", "designersupported"):
continue
singleton = parts[0] == "singleton"
if singleton:
parts = parts[1:]
if len(parts) >= 3:
entries.append((parts[0], singleton, parts[-1]))
return entries
def check_directories(app_dir):
"""Dossiers importés par chemin : qmldir complet, singletons sans cycle."""
app_dir = Path(app_dir)
problems = []
imported = set()
for qml in app_dir.rglob("*.qml"):
for match in IMPORT_RE.finditer(qml.read_text(encoding="utf-8")):
target = match.group(1)
if target and not target.endswith(".js") and target not in (".", "./"):
imported.add((qml.parent / target).resolve())
for folder in sorted(imported):
rel = folder.relative_to(app_dir.resolve()) if folder.is_relative_to(app_dir.resolve()) else folder
qmldir = folder / "qmldir"
if not qmldir.is_file():
problems.append("%s/: importé mais sans qmldir (« X is not a type » sur la box)" % rel)
continue
entries = _qmldir_entries(qmldir)
listed = {file for _, _, file in entries}
for name, _, file in entries:
if not (folder / file).is_file():
problems.append("%s/qmldir: %s → %s introuvable" % (rel, name, file))
for qml in sorted(folder.glob("*.qml")):
if qml.name[0].isupper() and qml.name not in listed:
problems.append("%s/qmldir: %s absent (« %s is not a type » sur la box)"
% (rel, qml.name, qml.stem))
singletons = [(name, file) for name, singleton, file in entries if singleton]
if len(singletons) > 1:
problems.append("%s/: plusieurs singletons (%s) : « Cyclic dependency detected » sur la box"
% (rel, ", ".join(n for n, _ in singletons)))
for name, file in singletons:
uses = re.compile(r"\b%s\." % re.escape(name))
for qml in sorted(folder.glob("*.qml")):
if qml.name != file and uses.search(strip_code(qml.read_text(encoding="utf-8"))):
problems.append("%s/%s: utilise le singleton %s de son propre dossier "
"(« Cyclic dependency detected » sur la box)" % (rel, qml.name, name))
return problems
def check_app(app_dir):
"""Toutes les règles sur le dossier de l'application ; renvoie la liste des problèmes."""
app_dir = Path(app_dir)
problems = []
for path in sorted(list(app_dir.rglob("*.qml")) + list(app_dir.rglob("*.js"))):
if any(part.startswith(".") for part in path.relative_to(app_dir).parts):
continue
rel = path.relative_to(app_dir)
text = path.read_text(encoding="utf-8")
problems += check_es5(rel, text)
if path.suffix == ".qml":
problems += check_imports(rel, text)
problems += check_directories(app_dir)
return problems