#!/usr/bin/env python3 """Fabrique le paquet FreeStore (.tar.gz) à téléverser sur la console FreeFactory. Reproduit « Outils > Freebox SDK > Make FreeStore Package » du plugin QtCreator Freebox (github.com/fbx/freebox-qtcreator-plugin, src/freestorepackager.cc) : - fichiers inclus comme dans Jellyfin.fbxproject : QML, JS, images, polices, qmldir et manifest.json (tools/ est exclu : l'aperçu PC n'a rien à faire sur la box) ; - vérifications : manifest.json (identifiant, version identique à Session.clientVersion, points d'entrée existants), JSON valides, syntaxe QML/JS (qmllint, s'il est installé) ; - archive tar (format ustar, avec les entrées de dossiers) compressée en gzip. Usage : tools/package.py [--output dist/paquet.tar.gz] """ import argparse import io import json import os import re import shutil import subprocess import sys import tarfile import time PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Types de fichiers repris de Jellyfin.fbxproject (QmlFiles, JavaScriptFiles, ImageFiles, Files). EXTENSIONS = {".qml", ".js", ".png", ".jpg", ".jpeg", ".gif", ".svg", ".bmp", ".webp", ".ttf", ".otf", ".woff"} NAMES = {"qmldir", "manifest.json"} EXCLUDED_DIRS = {"tools", "dist"} def collect_files(): files = [] for root, dirs, names in os.walk(PROJECT_DIR): rel_root = os.path.relpath(root, PROJECT_DIR) # Dossiers cachés (.git, .idea…) et dossiers d'outillage exclus. dirs[:] = sorted(d for d in dirs if not d.startswith(".") and not (rel_root == "." and d in EXCLUDED_DIRS)) for name in sorted(names): if name in NAMES or os.path.splitext(name)[1].lower() in EXTENSIONS: files.append(os.path.normpath(os.path.join(rel_root, name))) return files def check_manifest(files): """Mêmes règles que fileformat/manifest.cc du plugin. Renvoie le manifest.""" path = os.path.join(PROJECT_DIR, "manifest.json") if not os.path.exists(path): raise ValueError("manifest.json manquant") manifest = json.load(open(path, encoding="utf-8")) identifier = manifest.get("identifier") if not isinstance(identifier, str) or not re.fullmatch(r"\w+(\.\w+)+", identifier): raise ValueError("manifest.json : « identifier » absent ou invalide (forme attendue : a.b.c)") entry_points = manifest.get("entryPoints") if not isinstance(entry_points, dict) or not entry_points: raise ValueError("manifest.json : « entryPoints » absent ou invalide") defaults = 0 for key, entry in entry_points.items(): if not isinstance(entry, dict) or not isinstance(entry.get("file"), str): raise ValueError("manifest.json : entryPoints.%s.file doit être un fichier" % key) if not re.fullmatch(r"[/\w.+~-]+", entry["file"]): raise ValueError("manifest.json : caractères invalides dans entryPoints.%s.file" % key) if entry["file"] not in files: raise ValueError("manifest.json : entryPoints.%s.file « %s » absent du paquet" % (key, entry["file"])) if "uiFlavor" in entry and entry["uiFlavor"] not in ("multi", "classic"): raise ValueError("manifest.json : entryPoints.%s.uiFlavor doit valoir multi ou classic" % key) if entry.get("default") is True: defaults += 1 if defaults > 1: raise ValueError("manifest.json : un seul point d'entrée peut avoir « default »: true") version = manifest.get("version") if not isinstance(version, str) or not re.fullmatch(r"\d+\.\d+\.\d+", version): raise ValueError("manifest.json : « version » absente ou invalide (forme attendue : 1.2.3)") # La version envoyée à Jellyfin (Session.clientVersion) doit rester la même. session = open(os.path.join(PROJECT_DIR, "Core", "Session.qml"), encoding="utf-8").read() client = re.search(r'clientVersion:\s*"([^"]*)"', session) if not client or client.group(1) != version: raise ValueError("version du manifest (%s) différente de Session.clientVersion (%s)" % (version, client.group(1) if client else "introuvable")) icon = manifest.get("icon") if icon and icon not in files: raise ValueError("manifest.json : icône « %s » absente du paquet" % icon) return manifest def check_sources(files): for name in files: if name.endswith(".json"): json.load(open(os.path.join(PROJECT_DIR, name), encoding="utf-8")) qmllint = shutil.which("qmllint") if not qmllint: print("Attention : qmllint introuvable, syntaxe QML/JS non vérifiée.") return sources = [os.path.join(PROJECT_DIR, f) for f in files if f.endswith((".qml", ".js"))] result = subprocess.run([qmllint] + sources, capture_output=True, text=True) if result.returncode != 0: raise ValueError("erreurs de syntaxe QML/JS :\n" + (result.stdout + result.stderr).strip()) def build_archive(files, output): def info(name, is_dir, size=0): entry = tarfile.TarInfo(name + ("/" if is_dir else "")) entry.type = tarfile.DIRTYPE if is_dir else tarfile.REGTYPE entry.mode = 0o755 if is_dir else 0o644 entry.size = size entry.mtime = int(time.time()) entry.uid = entry.gid = 0 entry.uname = entry.gname = "" return entry os.makedirs(os.path.dirname(os.path.abspath(output)), exist_ok=True) seen_dirs = set() with tarfile.open(output, "w:gz", format=tarfile.USTAR_FORMAT) as archive: for name in files: # Entrées de dossiers (comme le plugin), du parent vers l'enfant. parts = name.split(os.sep)[:-1] for depth in range(1, len(parts) + 1): directory = "/".join(parts[:depth]) if directory not in seen_dirs: seen_dirs.add(directory) archive.addfile(info(directory, True)) data = open(os.path.join(PROJECT_DIR, name), "rb").read() archive.addfile(info(name.replace(os.sep, "/"), False, len(data)), io.BytesIO(data)) def main(): parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--output", help="archive à créer (défaut : dist/-.tar.gz)") args = parser.parse_args() files = collect_files() try: manifest = check_manifest(files) check_sources(files) except (ValueError, json.JSONDecodeError) as error: sys.exit("Paquet non créé : %s" % error) output = args.output or os.path.join( PROJECT_DIR, "dist", "%s-%s.tar.gz" % (manifest["identifier"], manifest["version"])) build_archive(files, output) print("Paquet créé : %s — version %s (%d fichiers, %.1f Ko)" % ( os.path.relpath(output, os.getcwd()), manifest["version"], len(files), os.path.getsize(output) / 1024)) print("À téléverser sur la console FreeFactory (http://factory.free.fr).") if __name__ == "__main__": main()