| 1 |
"""Generate executable scripts, on various platforms.""" |
| 2 |
|
| 3 |
import io |
| 4 |
import os |
| 5 |
import shlex |
| 6 |
import zipfile |
| 7 |
from collections.abc import Mapping |
| 8 |
from dataclasses import dataclass, field |
| 9 |
from importlib.resources import files |
| 10 |
from typing import TYPE_CHECKING |
| 11 |
|
| 12 |
from installer import _scripts |
| 13 |
|
| 14 |
if TYPE_CHECKING: |
| 15 |
from typing import Literal |
| 16 |
|
| 17 |
LauncherKind = Literal["posix", "win-ia32", "win-amd64", "win-arm", "win-arm64"] |
| 18 |
ScriptSection = Literal["console", "gui"] |
| 19 |
|
| 20 |
|
| 21 |
__all__ = ["InvalidScript", "Script"] |
| 22 |
|
| 23 |
|
| 24 |
_ALLOWED_LAUNCHERS: Mapping[tuple["ScriptSection", "LauncherKind"], str] = { |
| 25 |
("console", "win-ia32"): "t32.exe", |
| 26 |
("console", "win-amd64"): "t64.exe", |
| 27 |
("console", "win-arm"): "t_arm.exe", |
| 28 |
("console", "win-arm64"): "t64-arm.exe", |
| 29 |
("gui", "win-ia32"): "w32.exe", |
| 30 |
("gui", "win-amd64"): "w64.exe", |
| 31 |
("gui", "win-arm"): "w_arm.exe", |
| 32 |
("gui", "win-arm64"): "w64-arm.exe", |
| 33 |
} |
| 34 |
|
| 35 |
_SCRIPT_TEMPLATE = """\ |
| 36 |
# -*- coding: utf-8 -*- |
| 37 |
import re |
| 38 |
import sys |
| 39 |
from {module} import {import_name} |
| 40 |
if __name__ == "__main__": |
| 41 |
sys.argv[0] = re.sub(r"(-script\\.pyw|\\.exe)?$", "", sys.argv[0]) |
| 42 |
sys.exit({func_path}()) |
| 43 |
""" |
| 44 |
|
| 45 |
|
| 46 |
class InvalidScript(ValueError): |
| 47 |
"""Raised if the user provides incorrect script section or kind.""" |
| 48 |
|
| 49 |
|
| 50 |
@dataclass |
| 51 |
class Script: |
| 52 |
"""Describes a script based on an entry point declaration.""" |
| 53 |
|
| 54 |
name: str |
| 55 |
"""Name of the script.""" |
| 56 |
|
| 57 |
module: str |
| 58 |
"""Module path, to load the entry point from.""" |
| 59 |
|
| 60 |
attr: str |
| 61 |
"""Final attribute access, for the entry point.""" |
| 62 |
|
| 63 |
section: "ScriptSection" = field(repr=False) |
| 64 |
""" |
| 65 |
Denotes the "entry point section" where this was specified. Valid values |
| 66 |
are ``"gui"`` and ``"console"``. |
| 67 |
""" |
| 68 |
|
| 69 |
def _get_launcher_data(self, kind: "LauncherKind") -> bytes | None: |
| 70 |
if kind == "posix": |
| 71 |
return None |
| 72 |
key = (self.section, kind) |
| 73 |
try: |
| 74 |
name = _ALLOWED_LAUNCHERS[key] |
| 75 |
except KeyError: |
| 76 |
error = f"{key!r} not in {sorted(_ALLOWED_LAUNCHERS)!r}" |
| 77 |
raise InvalidScript(error) from None |
| 78 |
return (files(_scripts) / name).read_bytes() |
| 79 |
|
| 80 |
def _get_alternate_executable(self, executable: str, kind: "LauncherKind") -> str: |
| 81 |
"""Get an alternate executable for the launcher. |
| 82 |
|
| 83 |
On Windows, when the script section is gui-script, pythonw.exe should be used. |
| 84 |
""" |
| 85 |
if self.section == "gui" and kind != "posix": |
| 86 |
dn, fn = os.path.split(executable) |
| 87 |
fn = fn.replace("python", "pythonw") |
| 88 |
executable = os.path.join(dn, fn) |
| 89 |
return executable |
| 90 |
|
| 91 |
def generate(self, executable: str, kind: "LauncherKind") -> tuple[str, bytes]: |
| 92 |
"""Generate a launcher for this script. |
| 93 |
|
| 94 |
:param executable: Path to the executable to invoke. |
| 95 |
:param kind: Which launcher template should be used. |
| 96 |
Valid values are ``"posix"``, ``"win-ia32"``, ``"win-amd64"`` and |
| 97 |
``"win-arm"``. |
| 98 |
:type kind: str |
| 99 |
|
| 100 |
:raises InvalidScript: if no appropriate template is available. |
| 101 |
:return: The name and contents of the launcher file. |
| 102 |
""" |
| 103 |
launcher = self._get_launcher_data(kind) |
| 104 |
executable = self._get_alternate_executable(executable, kind) |
| 105 |
shebang = self._build_shebang(executable, forlauncher=bool(launcher)) |
| 106 |
code = _SCRIPT_TEMPLATE.format( |
| 107 |
module=self.module, |
| 108 |
import_name=self.attr.split(".")[0], |
| 109 |
func_path=self.attr, |
| 110 |
).encode("utf-8") |
| 111 |
|
| 112 |
if launcher is None: |
| 113 |
return self.name, shebang + b"\n" + code |
| 114 |
|
| 115 |
stream = io.BytesIO() |
| 116 |
with zipfile.ZipFile(stream, "w") as zf: |
| 117 |
zf.writestr("__main__.py", code) |
| 118 |
name = f"{self.name}.exe" |
| 119 |
data = launcher + shebang + b"\n" + stream.getvalue() |
| 120 |
return name, data |
| 121 |
|
| 122 |
@staticmethod |
| 123 |
def _is_executable_simple(executable: bytes) -> bool: |
| 124 |
if b" " in executable: |
| 125 |
return False |
| 126 |
shebang_length = len(executable) + 3 |
| 127 |
|
| 128 |
|
| 129 |
|
| 130 |
return shebang_length <= 127 |
| 131 |
|
| 132 |
def _build_shebang(self, executable: str, forlauncher: bool) -> bytes: |
| 133 |
"""Build a shebang line. |
| 134 |
|
| 135 |
The non-launcher cases are taken directly from distlib's implementation, |
| 136 |
which tries its best to account for command length, spaces in path, etc. |
| 137 |
|
| 138 |
https://bitbucket.org/pypa/distlib/src/58cd5c6/distlib/scripts.py#lines-124 |
| 139 |
""" |
| 140 |
executable_bytes = executable.encode("utf-8") |
| 141 |
if forlauncher: |
| 142 |
return b"#!" + executable_bytes |
| 143 |
if self._is_executable_simple(executable_bytes): |
| 144 |
return b"#!" + executable_bytes |
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
|
| 149 |
|
| 150 |
|
| 151 |
|
| 152 |
quoted = shlex.quote(executable).encode("utf-8") |
| 153 |
|
| 154 |
return b"#!/bin/sh\n'''exec' " + quoted + b' "$0" "$@"\n' + b"' '''" |