#!/usr/bin/env python3 """Build a PacManager plugin package (.fwspacm) from a compiled plugin. A package is a ZIP archive holding a manifest (plugin.json) and the shared library itself. Dropping it anywhere on the application window installs it into the per-user plugin directory, with no catalogue and no network -- the file *is* the distribution format (see doc/plugins.md). Usage: ./make-plugin-package.py libmy-provider.so \\ --id myprov --name "My Provider" \\ --version 1.0.0 --author "Jane Doe" \\ --description "Handles my packages" \\ --kind provider -o my-provider.fwspacm Only the library is required: --id defaults to the library's base name (without the lib prefix and extension), and --name to the id. Everything else is what the application shows the user before the plugin is loaded. The checksum is not an option: it is computed here and written into the manifest, and PacManager refuses a package whose library does not match it. """ import argparse import hashlib import json import sys import zipfile from pathlib import Path MANIFEST_NAME = "plugin.json" PACKAGE_SUFFIX = ".fwspacm" # The manifest version the application accepts; bumped only if the layout of the # archive ever changes in a way an older build could misread. MANIFEST_FORMAT = 1 LIBRARY_SUFFIXES = (".so", ".dll", ".dylib") def default_id(library: Path) -> str: """Derive an id from the library name: libmy-provider.so -> my-provider. The 'lib' prefix and the platform suffix are what the build system adds, not what identifies the plugin, and the id has to be what the library itself declares in its C ABI: fws_plugin_id(). """ name = library.name for suffix in LIBRARY_SUFFIXES: if name.endswith(suffix): name = name[: -len(suffix)] break if name.startswith("lib"): name = name[3:] return name def require_id(value: str) -> str: """Refuse an id the manifest could not carry. The id becomes a settings key and is echoed in the interface, so the characters that would need quoting there (a slash among them) are refused rather than silently rewritten into something that would later mismatch. """ if not value or not value.strip(): raise ValueError("l'identifiant ne peut pas être vide") for forbidden in '/\\"': if forbidden in value: raise ValueError(f"identifiant refusé : {value!r}") return value.strip() def build_package(args: argparse.Namespace) -> Path: library = Path(args.library) if not library.is_file(): raise ValueError(f"bibliothèque introuvable : {library}") if not library.name.endswith(LIBRARY_SUFFIXES): raise ValueError( f"{library.name} n'est pas une bibliothèque partagée " f"({', '.join(LIBRARY_SUFFIXES)})" ) payload = library.read_bytes() if not payload: raise ValueError(f"la bibliothèque {library} est vide") plugin_id = require_id(args.id or default_id(library)) manifest = { "format": MANIFEST_FORMAT, "id": plugin_id, "name": args.name or plugin_id, "kind": args.kind, "version": args.version, "author": args.author, "description": args.description, # The entry name in the archive, which is also the name the library is # written under in the plugin directory. "library": library.name, "sha256": hashlib.sha256(payload).hexdigest(), } # Absent optional fields are left out rather than written as null, so the # manifest stays readable and the application sees an empty string. manifest = {key: value for key, value in manifest.items() if value != ""} output = Path(args.output) if args.output else Path(plugin_id + PACKAGE_SUFFIX) if output.suffix.lower() != PACKAGE_SUFFIX: output = output.with_name(output.name + PACKAGE_SUFFIX) output.parent.mkdir(parents=True, exist_ok=True) # Written through a temporary file so an interrupted packaging never leaves # a half-written .fwspacm that the application would try to install. temporary = output.with_name(output.name + ".tmp") try: with zipfile.ZipFile(temporary, "w", zipfile.ZIP_DEFLATED) as archive: archive.writestr(MANIFEST_NAME, json.dumps(manifest, indent=2, ensure_ascii=False) + "\n") # The library keeps its own name: the plugin directory is scanned for # shared libraries, and the manifest points at this exact entry. archive.write(library, arcname=library.name) temporary.replace(output) finally: if temporary.exists(): temporary.unlink() return output def main() -> int: parser = argparse.ArgumentParser( description="Empaqueter une bibliothèque de plugin en paquet .fwspacm.", ) parser.add_argument("library", help="la bibliothèque partagée à empaqueter") parser.add_argument("-o", "--output", help=f"fichier à écrire (défaut : {PACKAGE_SUFFIX})") parser.add_argument("--id", help="identifiant du plugin (défaut : déduit du nom de la bibliothèque)") parser.add_argument("--name", help="nom affiché dans l'interface") parser.add_argument("--kind", choices=("provider", "addon"), help="type de plugin (l'application peut aussi le lire dans la bibliothèque)") parser.add_argument("--version", help="version du plugin") parser.add_argument("--author", help="auteur ou organisation") parser.add_argument("--description", help="description affichée dans l'interface") args = parser.parse_args() try: output = build_package(args) except (ValueError, OSError) as error: print(f"erreur : {error}", file=sys.stderr) return 1 print(f"{output} ({output.stat().st_size} octets)") print(f"Déposez ce fichier sur la fenêtre de PacManager, ou utilisez " f"« Ouvrir un paquet... » dans la page Plugins.") return 0 if __name__ == "__main__": sys.exit(main())