|
| 1 | +""" |
| 2 | +Logic to build installers using Briefcase. |
| 3 | +""" |
| 4 | + |
| 5 | +import logging |
| 6 | +import re |
| 7 | +import shutil |
| 8 | +import sysconfig |
| 9 | +import tempfile |
| 10 | +from pathlib import Path |
| 11 | +from subprocess import run |
| 12 | + |
| 13 | +import tomli_w |
| 14 | + |
| 15 | +from . import preconda |
| 16 | +from .utils import DEFAULT_REVERSE_DOMAIN_ID, copy_conda_exe, filename_dist |
| 17 | + |
| 18 | +BRIEFCASE_DIR = Path(__file__).parent / "briefcase" |
| 19 | +EXTERNAL_PACKAGE_PATH = "external" |
| 20 | + |
| 21 | +# Default to a low version, so that if a valid version is provided in the future, it'll |
| 22 | +# be treated as an upgrade. |
| 23 | +DEFAULT_VERSION = "0.0.1" |
| 24 | + |
| 25 | +logger = logging.getLogger(__name__) |
| 26 | + |
| 27 | + |
| 28 | +def get_name_version(info): |
| 29 | + if not (name := info.get("name")): |
| 30 | + raise ValueError("Name is empty") |
| 31 | + if not (version := info.get("version")): |
| 32 | + raise ValueError("Version is empty") |
| 33 | + |
| 34 | + # Briefcase requires version numbers to be in the canonical Python format, and some |
| 35 | + # installer types use the version to distinguish between upgrades, downgrades and |
| 36 | + # reinstalls. So try to produce a consistent ordering by extracting the last valid |
| 37 | + # version from the Constructor version string. |
| 38 | + # |
| 39 | + # Hyphens aren't allowed in this format, but for compatibility with Miniconda's |
| 40 | + # version format, we treat them as dots. |
| 41 | + matches = list( |
| 42 | + re.finditer( |
| 43 | + r"(\d+!)?\d+(\.\d+)*((a|b|rc)\d+)?(\.post\d+)?(\.dev\d+)?", |
| 44 | + version.lower().replace("-", "."), |
| 45 | + ) |
| 46 | + ) |
| 47 | + if not matches: |
| 48 | + logger.warning( |
| 49 | + f"Version {version!r} contains no valid version numbers; " |
| 50 | + f"defaulting to {DEFAULT_VERSION}" |
| 51 | + ) |
| 52 | + return f"{name} {version}", DEFAULT_VERSION |
| 53 | + |
| 54 | + match = matches[-1] |
| 55 | + version = match.group() |
| 56 | + |
| 57 | + # Treat anything else in the version string as part of the name. |
| 58 | + start, end = match.span() |
| 59 | + strip_chars = " .-_" |
| 60 | + before = info["version"][:start].strip(strip_chars) |
| 61 | + after = info["version"][end:].strip(strip_chars) |
| 62 | + name = " ".join(s for s in [name, before, after] if s) |
| 63 | + |
| 64 | + return name, version |
| 65 | + |
| 66 | + |
| 67 | +# Takes an arbitrary string with at least one alphanumeric character, and makes it into |
| 68 | +# a valid Python package name. |
| 69 | +def make_app_name(name, source): |
| 70 | + app_name = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-") |
| 71 | + if not app_name: |
| 72 | + raise ValueError(f"{source} contains no alphanumeric characters") |
| 73 | + return app_name |
| 74 | + |
| 75 | + |
| 76 | +# Some installer types use the reverse domain ID to detect when the product is already |
| 77 | +# installed, so it should be both unique between different products, and stable between |
| 78 | +# different versions of a product. |
| 79 | +def get_bundle_app_name(info, name): |
| 80 | + # If reverse_domain_identifier is provided, use it as-is, |
| 81 | + if (rdi := info.get("reverse_domain_identifier")) is not None: |
| 82 | + if "." not in rdi: |
| 83 | + raise ValueError(f"reverse_domain_identifier {rdi!r} contains no dots") |
| 84 | + bundle, app_name = rdi.rsplit(".", 1) |
| 85 | + |
| 86 | + # Ensure that the last component is a valid Python package name, as Briefcase |
| 87 | + # requires. |
| 88 | + if not re.fullmatch( |
| 89 | + r"[A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9]", app_name, flags=re.IGNORECASE |
| 90 | + ): |
| 91 | + app_name = make_app_name( |
| 92 | + app_name, f"Last component of reverse_domain_identifier {rdi!r}" |
| 93 | + ) |
| 94 | + |
| 95 | + # If reverse_domain_identifier isn't provided, generate it from the name. |
| 96 | + else: |
| 97 | + bundle = DEFAULT_REVERSE_DOMAIN_ID |
| 98 | + app_name = make_app_name(name, f"Name {name!r}") |
| 99 | + |
| 100 | + return bundle, app_name |
| 101 | + |
| 102 | + |
| 103 | +# Create a Briefcase configuration file. Using a full TOML writer rather than a Jinja |
| 104 | +# template allows us to avoid escaping strings everywhere. |
| 105 | +def write_pyproject_toml(tmp_dir, info): |
| 106 | + name, version = get_name_version(info) |
| 107 | + bundle, app_name = get_bundle_app_name(info, name) |
| 108 | + |
| 109 | + config = { |
| 110 | + "project_name": name, |
| 111 | + "bundle": bundle, |
| 112 | + "version": version, |
| 113 | + "license": ({"file": info["license_file"]} if "license_file" in info else {"text": ""}), |
| 114 | + "app": { |
| 115 | + app_name: { |
| 116 | + "formal_name": f"{info['name']} {info['version']}", |
| 117 | + "description": "", # Required, but not used in the installer. |
| 118 | + "external_package_path": EXTERNAL_PACKAGE_PATH, |
| 119 | + "use_full_install_path": False, |
| 120 | + "install_launcher": False, |
| 121 | + "post_install_script": str(BRIEFCASE_DIR / "run_installation.bat"), |
| 122 | + } |
| 123 | + }, |
| 124 | + } |
| 125 | + |
| 126 | + if "company" in info: |
| 127 | + config["author"] = info["company"] |
| 128 | + |
| 129 | + (tmp_dir / "pyproject.toml").write_text(tomli_w.dumps({"tool": {"briefcase": config}})) |
| 130 | + |
| 131 | + |
| 132 | +def create(info, verbose=False): |
| 133 | + tmp_dir = Path(tempfile.mkdtemp()) |
| 134 | + write_pyproject_toml(tmp_dir, info) |
| 135 | + |
| 136 | + external_dir = tmp_dir / EXTERNAL_PACKAGE_PATH |
| 137 | + external_dir.mkdir() |
| 138 | + preconda.write_files(info, external_dir) |
| 139 | + preconda.copy_extra_files(info.get("extra_files", []), external_dir) |
| 140 | + |
| 141 | + download_dir = Path(info["_download_dir"]) |
| 142 | + pkgs_dir = external_dir / "pkgs" |
| 143 | + for dist in info["_dists"]: |
| 144 | + shutil.copy(download_dir / filename_dist(dist), pkgs_dir) |
| 145 | + |
| 146 | + copy_conda_exe(external_dir, "_conda.exe", info["_conda_exe"]) |
| 147 | + |
| 148 | + briefcase = Path(sysconfig.get_path("scripts")) / "briefcase.exe" |
| 149 | + if not briefcase.exists(): |
| 150 | + raise FileNotFoundError( |
| 151 | + f"Dependency 'briefcase' does not seem to be installed.\nTried: {briefcase}" |
| 152 | + ) |
| 153 | + |
| 154 | + logger.info("Building installer") |
| 155 | + run( |
| 156 | + [briefcase, "package"] + (["-v"] if verbose else []), |
| 157 | + cwd=tmp_dir, |
| 158 | + check=True, |
| 159 | + ) |
| 160 | + |
| 161 | + dist_dir = tmp_dir / "dist" |
| 162 | + msi_paths = list(dist_dir.glob("*.msi")) |
| 163 | + if len(msi_paths) != 1: |
| 164 | + raise RuntimeError(f"Found {len(msi_paths)} MSI files in {dist_dir}") |
| 165 | + |
| 166 | + outpath = Path(info["_outpath"]) |
| 167 | + outpath.unlink(missing_ok=True) |
| 168 | + shutil.move(msi_paths[0], outpath) |
| 169 | + |
| 170 | + if not info.get("_debug"): |
| 171 | + shutil.rmtree(tmp_dir) |
0 commit comments