Build and Release Barcode Reader Server (Multi-Platform) / build-linux (push) Failing after 39s
Build and Release Barcode Reader Server (Multi-Platform) / build-windows (push) Successful in 3m42s
Build and Release Barcode Reader Server (Multi-Platform) / build-macos (push) Successful in 1m5s
311 lines
9.6 KiB
Python
Executable File
311 lines
9.6 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""
|
|
Script multi-piattaforma per compilare Barcode Reader Server con PyInstaller (PySide6)
|
|
e preparare l'AppDir per AppImage su Linux o bundle .app su macOS.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import os
|
|
import platform
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
from version import APP_BINARY_NAME, APP_ID, APP_NAME
|
|
|
|
SERVER_DIR = Path(__file__).resolve().parent
|
|
VERSION_FILE = SERVER_DIR / "version.py"
|
|
|
|
HIDDEN_IMPORTS = [
|
|
"PySide6.QtCore",
|
|
"PySide6.QtGui",
|
|
"PySide6.QtWidgets",
|
|
"PIL",
|
|
"PIL.Image",
|
|
"qrcode",
|
|
"aiohttp",
|
|
"pynput",
|
|
"pyperclip",
|
|
]
|
|
|
|
EXCLUDED_MODULES = [
|
|
"tkinter",
|
|
"_tkinter",
|
|
"PyQt5",
|
|
"PyQt6",
|
|
"PySide6.QtQml",
|
|
"PySide6.QtQuick",
|
|
"PySide6.QtQuickWidgets",
|
|
"PySide6.QtWebEngineCore",
|
|
"PySide6.QtWebEngineWidgets",
|
|
"PySide6.Qt3DCore",
|
|
"PySide6.QtMultimedia",
|
|
]
|
|
|
|
|
|
def _configure_console_encoding() -> None:
|
|
"""Forza stdout/stderr in UTF-8 per evitare errori su console Windows cp1252."""
|
|
for stream in (sys.stdout, sys.stderr):
|
|
if stream is not None and hasattr(stream, "reconfigure"):
|
|
try:
|
|
stream.reconfigure(encoding="utf-8", errors="replace")
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _venv_python(venv_dir: Path) -> Path:
|
|
if platform.system() == "Windows":
|
|
return venv_dir / "Scripts" / "python.exe"
|
|
python_bin = venv_dir / "bin" / "python"
|
|
if python_bin.exists():
|
|
return python_bin
|
|
return venv_dir / "bin" / "python3"
|
|
|
|
|
|
def _resolve_venv_dir(base_dir: Path) -> Path:
|
|
default_venv = base_dir / "venv"
|
|
if platform.system() == "Windows":
|
|
if (default_venv / "bin").exists() and not (default_venv / "Scripts" / "python.exe").exists():
|
|
print('[!] Rilevato ambiente virtuale Unix in "venv". Uso "venv_win".')
|
|
return base_dir / "venv_win"
|
|
return default_venv
|
|
|
|
has_unix_python = (default_venv / "bin" / "python").exists() or (default_venv / "bin" / "python3").exists()
|
|
if (default_venv / "Scripts").exists() and not has_unix_python:
|
|
print('[!] Rilevato ambiente virtuale Windows in "venv". Uso "venv_unix".')
|
|
return base_dir / "venv_unix"
|
|
return default_venv
|
|
|
|
|
|
def _can_import(python_exe: Path, module_name: str) -> bool:
|
|
result = subprocess.run(
|
|
[str(python_exe), "-c", f"import {module_name}"],
|
|
stdout=subprocess.DEVNULL,
|
|
stderr=subprocess.DEVNULL,
|
|
)
|
|
return result.returncode == 0
|
|
|
|
|
|
def _ensure_venv_python(base_dir: Path) -> Path:
|
|
if sys.prefix != getattr(sys, "base_prefix", sys.prefix):
|
|
return Path(sys.executable)
|
|
|
|
venv_dir = _resolve_venv_dir(base_dir)
|
|
venv_python = _venv_python(venv_dir)
|
|
if not venv_python.exists():
|
|
print(f"[+] Creazione ambiente virtuale Python in {venv_dir.name}...")
|
|
subprocess.check_call([sys.executable, "-m", "venv", str(venv_dir)])
|
|
return venv_python
|
|
|
|
|
|
def _ensure_build_dependencies(venv_python: Path) -> None:
|
|
print("[+] Verifica/installazione dipendenze da requirements.txt...")
|
|
subprocess.check_call(
|
|
[str(venv_python), "-m", "pip", "install", "--disable-pip-version-check", "-q", "-r", "requirements.txt"]
|
|
)
|
|
|
|
if not _can_import(venv_python, "PyInstaller"):
|
|
print("[+] Installazione PyInstaller nel venv...")
|
|
subprocess.check_call(
|
|
[str(venv_python), "-m", "pip", "install", "--disable-pip-version-check", "-q", "pyinstaller"]
|
|
)
|
|
|
|
|
|
def _stamp_version(version_override: str | None) -> str | None:
|
|
"""Sostituisce temporaneamente APP_VERSION in version.py, restituendo il contenuto originale."""
|
|
if not version_override:
|
|
return None
|
|
cleaned = version_override.strip().lstrip("vV")
|
|
if not cleaned:
|
|
return None
|
|
|
|
original = VERSION_FILE.read_text(encoding="utf-8")
|
|
updated, count = re.subn(
|
|
r'^APP_VERSION\s*=\s*["\'][^"\']*["\']',
|
|
f'APP_VERSION = "{cleaned}"',
|
|
original,
|
|
count=1,
|
|
flags=re.MULTILINE,
|
|
)
|
|
if count != 1:
|
|
raise RuntimeError("Impossibile aggiornare APP_VERSION in version.py")
|
|
VERSION_FILE.write_text(updated, encoding="utf-8")
|
|
print(f"[+] Versione di build impostata a: {cleaned}")
|
|
return original
|
|
|
|
|
|
def _build_linux_appdir(dist_bundle_dir: Path, appdir_path: Path) -> None:
|
|
"""Impacchetta la cartella --onedir di PyInstaller in una AppDir valida per AppImage."""
|
|
if appdir_path.exists():
|
|
shutil.rmtree(appdir_path)
|
|
|
|
usr_bin = appdir_path / "usr" / "bin"
|
|
shutil.copytree(dist_bundle_dir, usr_bin, symlinks=True)
|
|
|
|
icon_src = SERVER_DIR / "assets" / "icon.png"
|
|
if icon_src.exists():
|
|
shutil.copy2(icon_src, appdir_path / f"{APP_BINARY_NAME}.png")
|
|
shutil.copy2(icon_src, appdir_path / ".DirIcon")
|
|
hicolor = appdir_path / "usr" / "share" / "icons" / "hicolor" / "512x512" / "apps"
|
|
hicolor.mkdir(parents=True, exist_ok=True)
|
|
shutil.copy2(icon_src, hicolor / f"{APP_BINARY_NAME}.png")
|
|
|
|
apprun = appdir_path / "AppRun"
|
|
apprun.write_text(
|
|
"#!/bin/sh\n"
|
|
'HERE="$(dirname "$(readlink -f "${0}")")"\n'
|
|
f'exec "${{HERE}}/usr/bin/{APP_BINARY_NAME}" "$@"\n',
|
|
encoding="utf-8",
|
|
)
|
|
apprun.chmod(0o755)
|
|
|
|
desktop_file = appdir_path / f"{APP_BINARY_NAME}.desktop"
|
|
desktop_file.write_text(
|
|
"[Desktop Entry]\n"
|
|
"Version=1.0\n"
|
|
"Type=Application\n"
|
|
f"Name={APP_NAME}\n"
|
|
f"Exec={APP_BINARY_NAME} %u\n"
|
|
f"Icon={APP_BINARY_NAME}\n"
|
|
"Terminal=false\n"
|
|
"Categories=Utility;\n"
|
|
f"StartupWMClass={APP_ID}\n",
|
|
encoding="utf-8",
|
|
)
|
|
print(f"[OK] AppDir pronta per AppImage: {appdir_path}")
|
|
|
|
|
|
def build(
|
|
onefile: bool = False,
|
|
windowed: bool = True,
|
|
create_appdir: bool = False,
|
|
version_override: str | None = None,
|
|
) -> None:
|
|
_configure_console_encoding()
|
|
os.chdir(SERVER_DIR)
|
|
|
|
if create_appdir and onefile:
|
|
print("[i] --appdir richiede --onedir: disabilito --onefile per creare l'AppDir.")
|
|
onefile = False
|
|
|
|
system = platform.system()
|
|
print(f"[+] Compilazione {APP_BINARY_NAME} per {system}...")
|
|
|
|
venv_python = _ensure_venv_python(SERVER_DIR)
|
|
_ensure_build_dependencies(venv_python)
|
|
|
|
original_version_text = _stamp_version(version_override)
|
|
try:
|
|
data_sep = ";" if system == "Windows" else ":"
|
|
cmd = [
|
|
str(venv_python),
|
|
"-m",
|
|
"PyInstaller",
|
|
f"--name={APP_BINARY_NAME}",
|
|
"--onefile" if onefile else "--onedir",
|
|
"--clean",
|
|
"--noconfirm",
|
|
"--collect-submodules=pynput",
|
|
]
|
|
|
|
if system == "Linux":
|
|
cmd.append("--collect-submodules=Xlib")
|
|
|
|
if windowed:
|
|
cmd.append("--windowed")
|
|
if system == "Darwin":
|
|
cmd.append(f"--osx-bundle-identifier={APP_ID}")
|
|
|
|
assets_dir = SERVER_DIR / "assets"
|
|
if assets_dir.exists():
|
|
cmd.append(f"--add-data={assets_dir}{data_sep}assets")
|
|
|
|
if system == "Windows" and (assets_dir / "icon.ico").exists():
|
|
cmd.append(f"--icon={assets_dir / 'icon.ico'}")
|
|
elif (assets_dir / "icon.png").exists():
|
|
cmd.append(f"--icon={assets_dir / 'icon.png'}")
|
|
|
|
for hidden_import in HIDDEN_IMPORTS:
|
|
cmd.append(f"--hidden-import={hidden_import}")
|
|
for excluded in EXCLUDED_MODULES:
|
|
cmd.append(f"--exclude-module={excluded}")
|
|
|
|
cmd.append("main.py")
|
|
|
|
print(f"[+] Comando: {' '.join(cmd)}")
|
|
subprocess.check_call(cmd)
|
|
finally:
|
|
if original_version_text is not None:
|
|
VERSION_FILE.write_text(original_version_text, encoding="utf-8")
|
|
|
|
dist_dir = SERVER_DIR / "dist"
|
|
if system == "Darwin" and windowed and not onefile:
|
|
output_path = dist_dir / f"{APP_BINARY_NAME}.app"
|
|
elif onefile:
|
|
ext = ".exe" if system == "Windows" else ""
|
|
output_path = dist_dir / f"{APP_BINARY_NAME}{ext}"
|
|
else:
|
|
output_path = dist_dir / APP_BINARY_NAME
|
|
|
|
print(f"\n[OK] Compilazione completata: {output_path}")
|
|
|
|
if create_appdir:
|
|
if system != "Linux":
|
|
print("[!] --appdir è supportato solo su Linux; passaggio saltato.")
|
|
else:
|
|
appdir_path = dist_dir / f"{APP_BINARY_NAME}.AppDir"
|
|
_build_linux_appdir(output_path, appdir_path)
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description="Compila Barcode Reader Server con PyInstaller")
|
|
parser.add_argument(
|
|
"--onefile",
|
|
action="store_true",
|
|
help="Genera un singolo eseguibile compresso invece della cartella --onedir",
|
|
)
|
|
parser.add_argument(
|
|
"--onedir",
|
|
action="store_true",
|
|
help="Genera la cartella standalone --onedir (default)",
|
|
)
|
|
parser.add_argument(
|
|
"--console",
|
|
action="store_true",
|
|
help="Mantieni la console di sistema aperta (disattiva --windowed)",
|
|
)
|
|
parser.add_argument(
|
|
"--windowed",
|
|
action="store_true",
|
|
help="Compila senza finestra terminale (default)",
|
|
)
|
|
parser.add_argument(
|
|
"--appdir",
|
|
action="store_true",
|
|
help="Crea dist/BarcodeServer.AppDir pronta per appimagetool su Linux",
|
|
)
|
|
parser.add_argument(
|
|
"--version",
|
|
type=str,
|
|
default=None,
|
|
help="Sovrascrive APP_VERSION durante il build (es. 1.0.1)",
|
|
)
|
|
|
|
args = parser.parse_args()
|
|
windowed = False if args.console else True
|
|
onefile = bool(args.onefile and not args.onedir)
|
|
build(
|
|
onefile=onefile,
|
|
windowed=windowed,
|
|
create_appdir=args.appdir,
|
|
version_override=args.version,
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|