219 lines
9.2 KiB
Python
219 lines
9.2 KiB
Python
"""Package a release binary built with the vendored-lua feature."""
|
|
|
|
import argparse
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import tarfile
|
|
import tempfile
|
|
import tomllib
|
|
import zipfile
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
PACKAGE = tomllib.loads((ROOT / "Cargo.toml").read_text(encoding="utf-8"))["package"]
|
|
NAME = PACKAGE["name"]
|
|
VERSION = PACKAGE["version"]
|
|
NOTICES = {
|
|
"LICENSE.txt": ROOT / "LICENSE",
|
|
"LiberationSans.txt": ROOT / "assets/fonts/LiberationSans License.txt",
|
|
"VeraMono.txt": ROOT / "assets/fonts/VeraMono License.txt",
|
|
}
|
|
|
|
|
|
def check_binary(binary, platform):
|
|
with binary.open("rb") as stream:
|
|
header = stream.read(64)
|
|
if platform == "linux":
|
|
# ELF64, little endian, EM_X86_64.
|
|
if header[:6] == b"\x7fELF\x02\x01" and header[18:20] == b"\x3e\x00":
|
|
return
|
|
elif len(header) == 64 and header[:2] == b"MZ":
|
|
stream.seek(struct.unpack_from("<I", header, 60)[0])
|
|
if stream.read(6) == b"PE\x00\x00\x64\x86":
|
|
return
|
|
raise ValueError(f"{binary} is not an x86_64 {platform} executable")
|
|
|
|
|
|
def windows_inventory(payload, include):
|
|
from windows_deps import safe_basename
|
|
|
|
paths = sorted(payload.rglob("*"), key=lambda p: p.relative_to(payload).as_posix().lower())
|
|
files, directories, seen = [], [], set()
|
|
for path in paths:
|
|
relative = path.relative_to(payload)
|
|
for part in relative.parts:
|
|
safe_basename(part)
|
|
key = relative.as_posix().lower()
|
|
if key in seen or key == "uninstall.exe":
|
|
raise ValueError(f"Conflicting Windows payload filename: {relative}")
|
|
seen.add(key)
|
|
if path.is_symlink():
|
|
raise ValueError(f"Symlink in Windows payload: {relative}")
|
|
if path.is_dir():
|
|
directories.append(relative)
|
|
elif path.is_file():
|
|
files.append(relative)
|
|
else:
|
|
raise ValueError(f"Not a regular payload file: {relative}")
|
|
install = ["!macro InstallPayload"]
|
|
previous = None
|
|
for path in files:
|
|
parent = "\\".join(path.parts[:-1])
|
|
destination = "$INSTDIR" + ("\\" + parent if parent else "")
|
|
if destination != previous:
|
|
install.append(f' SetOutPath "{destination}"')
|
|
previous = destination
|
|
source = "\\".join(path.parts)
|
|
install.append(f' File "payload\\{source}"')
|
|
install.extend([' SetOutPath "$INSTDIR"', "!macroend", "", "!macro UninstallPayload"])
|
|
for path in files:
|
|
name = "\\".join(path.parts)
|
|
install.append(f' Delete "$INSTDIR\\{name}"')
|
|
for path in sorted(directories, key=lambda p: (-len(p.parts), p.as_posix().lower())):
|
|
name = "\\".join(path.parts)
|
|
install.append(f' RMDir "$INSTDIR\\{name}"')
|
|
install.append("!macroend")
|
|
include.write_text("\n".join(install) + "\n", encoding="utf-8")
|
|
return files
|
|
|
|
|
|
def package_windows(binary, work, dll_dirs=(), require_static_crt=False):
|
|
from windows_deps import resolve_dependencies, safe_basename
|
|
|
|
safe_basename(NAME)
|
|
safe_basename(VERSION)
|
|
dependencies = resolve_dependencies(binary, dll_dirs, require_static_crt)
|
|
stem = f"{NAME}-{VERSION}-windows-x86_64"
|
|
payload = work / "payload"
|
|
(payload / "licenses").mkdir(parents=True)
|
|
shutil.copyfile(binary, payload / f"{NAME}.exe")
|
|
for name, source in dependencies.items():
|
|
shutil.copyfile(source, payload / name)
|
|
for name, source in NOTICES.items():
|
|
shutil.copyfile(source, payload / "licenses" / name)
|
|
|
|
# Freeze one validated inventory for the archive and both NSIS macros.
|
|
inventory = windows_inventory(payload, work / "payload-files.nsh")
|
|
archive = work / f"{stem}.zip"
|
|
with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as bundle:
|
|
for relative in inventory:
|
|
bundle.write(payload / relative, relative.as_posix())
|
|
|
|
makensis = shutil.which("makensis")
|
|
if not makensis and os.name == "nt":
|
|
for key in ("ProgramFiles(x86)", "ProgramFiles"):
|
|
if key in os.environ:
|
|
candidate = Path(os.environ[key]) / "NSIS" / "makensis.exe"
|
|
if candidate.is_file():
|
|
makensis = str(candidate)
|
|
break
|
|
if not makensis:
|
|
raise ValueError("Install NSIS 3 and make makensis available")
|
|
shutil.copyfile(ROOT / "packaging/windows/installer.nsi", work / "installer.nsi")
|
|
shutil.copyfile(ROOT / "assets/icon.ico", work / "app.ico")
|
|
define = "/D" if os.name == "nt" else "-D"
|
|
installer = work / f"{stem}-setup.exe"
|
|
subprocess.run(
|
|
[makensis, f"{define}VERSION={VERSION}", f"{define}OUTPUT={installer.name}", "installer.nsi"],
|
|
cwd=work, check=True,
|
|
)
|
|
return archive, installer
|
|
|
|
|
|
def package_linux(binary, work):
|
|
stem = f"{NAME}-{VERSION}-linux-x86_64"
|
|
package = work / "debian" / NAME
|
|
executable = package / "usr/bin" / NAME
|
|
executable.parent.mkdir(parents=True)
|
|
shutil.copyfile(binary, executable)
|
|
executable.chmod(0o755)
|
|
|
|
docs = package / "usr/share/doc" / NAME
|
|
docs.mkdir(parents=True)
|
|
for name, source in NOTICES.items():
|
|
shutil.copyfile(source, docs / ("copyright" if name == "LICENSE.txt" else name))
|
|
desktop = package / "usr/share/applications" / f"{NAME}.desktop"
|
|
desktop.parent.mkdir(parents=True)
|
|
shutil.copyfile(ROOT / "packaging/linux" / desktop.name, desktop)
|
|
icon = package / "usr/share/icons/hicolor/256x256/apps" / f"{NAME}.png"
|
|
icon.parent.mkdir(parents=True)
|
|
shutil.copyfile(ROOT / "assets/icon.png", icon)
|
|
|
|
# dpkg-shlibdeps reads the build system's package database and requires a source stanza.
|
|
(work / "debian/control").write_text(f"Source: {NAME}\n", encoding="utf-8")
|
|
control = package / "DEBIAN/control"
|
|
control.parent.mkdir()
|
|
linked = subprocess.check_output(
|
|
["dpkg-shlibdeps", "-O", executable.relative_to(work)], cwd=work, text=True
|
|
).strip().removeprefix("shlibs:Depends=")
|
|
# winit and wgpu load the window-system and Vulkan libraries at runtime.
|
|
extra = ("ca-certificates", "libvulkan1", "libx11-6", "libx11-xcb1", "libxcursor1",
|
|
"libxi6", "libxkbcommon0", "libxkbcommon-x11-0", "libwayland-client0",
|
|
"libwayland-cursor0")
|
|
control.write_text(
|
|
f"Package: {NAME}\nVersion: {VERSION}\nArchitecture: amd64\n"
|
|
"Section: games\nPriority: optional\n"
|
|
"Maintainer: Rusty Path of Building contributors <noreply@git.faumaray.com>\n"
|
|
f"Homepage: {PACKAGE['repository']}\n"
|
|
f"Depends: {', '.join((linked, *extra))}\n"
|
|
"Recommends: mesa-vulkan-drivers | vulkan-icd\n"
|
|
f"Description: {PACKAGE['description']}\n"
|
|
" Plan characters for Path of Exile 1 and 2.\n",
|
|
encoding="utf-8",
|
|
)
|
|
# The runner's umask must not give package files writable system permissions.
|
|
for path in [package, *package.rglob("*")]:
|
|
path.chmod(0o755 if path.is_dir() or path == executable else 0o644)
|
|
installer = work / f"{NAME}_{VERSION}_amd64.deb"
|
|
subprocess.run(["dpkg-deb", "--root-owner-group", "--build", package, installer], check=True)
|
|
|
|
archive = work / f"{stem}.tar.gz"
|
|
with tarfile.open(archive, "w:gz") as bundle:
|
|
members = {NAME: executable, **{f"licenses/{key}": value for key, value in NOTICES.items()}}
|
|
for name, source in members.items():
|
|
entry = bundle.gettarinfo(str(source), arcname=f"{stem}/{name}")
|
|
entry.uid = entry.gid = 0
|
|
entry.uname = entry.gname = "root"
|
|
entry.mode = 0o755 if name == NAME else 0o644
|
|
with source.open("rb") as stream:
|
|
bundle.addfile(entry, stream)
|
|
return archive, installer
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("platform", choices=("windows", "linux"))
|
|
parser.add_argument("binary", type=Path)
|
|
parser.add_argument("--output", type=Path, default=ROOT / "target/dist")
|
|
parser.add_argument("--dll-dir", type=Path, action="append", default=[], metavar="DIR",
|
|
help="Windows DLL source directory (repeatable; no PATH search)")
|
|
parser.add_argument("--require-static-crt", action="store_true",
|
|
help="Reject direct/delay CRT imports in the Windows executable")
|
|
args = parser.parse_args()
|
|
if args.platform != "windows" and (args.dll_dir or args.require_static_crt):
|
|
parser.error("--dll-dir and --require-static-crt apply only to Windows")
|
|
binary = args.binary.resolve()
|
|
output = args.output.resolve()
|
|
check_binary(binary, args.platform)
|
|
output.mkdir(parents=True, exist_ok=True)
|
|
with tempfile.TemporaryDirectory(dir=output) as temp:
|
|
if args.platform == "windows":
|
|
artifacts = package_windows(binary, Path(temp), args.dll_dir, args.require_static_crt)
|
|
else:
|
|
artifacts = package_linux(binary, Path(temp))
|
|
for artifact in artifacts:
|
|
destination = output / artifact.name
|
|
artifact.replace(destination)
|
|
print(destination)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except (OSError, ValueError, subprocess.CalledProcessError) as error:
|
|
sys.exit(str(error))
|