Debian Codegraph @

rust/hgcli/pyoxidizer.bzl

raw
1 # The following variables can be passed in as parameters:
2 #
3 # VERSION
4 # Version string of program being produced.
5 #
6 # MSI_NAME
7 # Root name of MSI installer.
8 #
9 # EXTRA_MSI_FEATURES
10 # ; delimited string of extra features to advertise in the built MSA.
11 #
12 # SIGNING_PFX_PATH
13 # Path to code signing certificate to use.
14 #
15 # SIGNING_PFX_PASSWORD
16 # Password to code signing PFX file defined by SIGNING_PFX_PATH.
17 #
18 # SIGNING_SUBJECT_NAME
19 # String fragment in code signing certificate subject name used to find
20 # code signing certificate in Windows certificate store.
21 #
22 # TIME_STAMP_SERVER_URL
23 # URL of time-stamp token authority (RFC 3161) servers to stamp code signatures.
24
25 ROOT = CWD + "/../.."
26
27 VERSION = VARS.get("VERSION", "0.0")
28 MSI_NAME = VARS.get("MSI_NAME", "mercurial")
29 EXTRA_MSI_FEATURES = VARS.get("EXTRA_MSI_FEATURES")
30 SIGNING_PFX_PATH = VARS.get("SIGNING_PFX_PATH")
31 SIGNING_PFX_PASSWORD = VARS.get("SIGNING_PFX_PASSWORD", "")
32 SIGNING_SUBJECT_NAME = VARS.get("SIGNING_SUBJECT_NAME")
33 TIME_STAMP_SERVER_URL = VARS.get("TIME_STAMP_SERVER_URL", "http://timestamp.digicert.com")
34
35 IS_WINDOWS = "windows" in BUILD_TARGET_TRIPLE
36 IS_MACOS = "apple" in BUILD_TARGET_TRIPLE
37
38 # Use in-memory resources for all resources. If false, most of the Python
39 # stdlib will be in memory, but other things such as Mercurial itself will not
40 # be. See the comment in resource_callback, below.
41 USE_IN_MEMORY_RESOURCES = not IS_WINDOWS
42
43 # Code to run in Python interpreter.
44 RUN_CODE = """
45 import os
46 import sys
47 extra_path = os.environ.get('PYTHONPATH')
48 if extra_path is not None:
49 # extensions and hooks expect a working python environment
50 # We do not prepend the values because the Mercurial library wants to be in
51 # the front of the sys.path to avoid picking up other installations.
52 sys.path.extend(extra_path.split(os.pathsep))
53 # Add user site to sys.path to load extensions without the full path
54 if os.name == 'nt':
55 vi = sys.version_info
56 appdata = os.environ.get('APPDATA')
57 if appdata:
58 sys.path.append(
59 os.path.join(
60 appdata,
61 'Python',
62 'Python%d%d' % (vi[0], vi[1]),
63 'site-packages',
64 )
65 )
66 elif sys.platform == "darwin":
67 vi = sys.version_info
68
69 def joinuser(*args):
70 return os.path.expanduser(os.path.join(*args))
71
72 # Note: site.py uses `sys._framework` instead of hardcoding "Python" as the
73 # 3rd arg, but that is set to an empty string in an oxidized binary. It
74 # has a fallback to ~/.local when `sys._framework` isn't set, but we want
75 # to match what the system python uses, so it sees pip installed stuff.
76 usersite = joinuser("~", "Library", "Python",
77 "%d.%d" % vi[:2], "lib/python/site-packages")
78
79 sys.path.append(usersite)
80 import hgdemandimport;
81 hgdemandimport.enable();
82 from mercurial import dispatch;
83 dispatch.run();
84 """
85
86 set_build_path(ROOT + "/build/pyoxidizer")
87
88 def make_distribution():
89 return default_python_distribution(python_version = "3.9")
90
91 def resource_callback(policy, resource):
92 if USE_IN_MEMORY_RESOURCES:
93 resource.add_location = "in-memory"
94 return
95
96 # We use a custom resource routing policy to influence where things are loaded
97 # from.
98 #
99 # For Python modules and resources, we load from memory if they are in
100 # the standard library and from the filesystem if not. This is because
101 # parts of Mercurial and some 3rd party packages aren't yet compatible
102 # with memory loading.
103 #
104 # For Python extension modules, we load from the filesystem because
105 # this yields greatest compatibility.
106 if type(resource) in ("PythonModuleSource", "PythonPackageResource", "PythonPackageDistributionResource"):
107 if resource.is_stdlib:
108 resource.add_location = "in-memory"
109 else:
110 resource.add_location = "filesystem-relative:lib"
111
112 elif type(resource) == "PythonExtensionModule":
113 resource.add_location = "filesystem-relative:lib"
114
115 def make_exe(dist):
116 """Builds a Rust-wrapped Mercurial binary."""
117 packaging_policy = dist.make_python_packaging_policy()
118
119 # Extension may depend on any Python functionality. Include all
120 # extensions.
121 packaging_policy.extension_module_filter = "all"
122 packaging_policy.resources_location = "in-memory"
123 if not USE_IN_MEMORY_RESOURCES:
124 packaging_policy.resources_location_fallback = "filesystem-relative:lib"
125 packaging_policy.register_resource_callback(resource_callback)
126
127 config = dist.make_python_interpreter_config()
128 config.allocator_backend = "default"
129 config.run_command = RUN_CODE
130
131 # We want to let the user load extensions from the file system
132 config.filesystem_importer = True
133
134 # We need this to make resourceutil happy, since it looks for sys.frozen.
135 config.sys_frozen = True
136 config.legacy_windows_stdio = True
137
138 exe = dist.to_python_executable(
139 name = "hg",
140 packaging_policy = packaging_policy,
141 config = config,
142 )
143
144 # Add Mercurial to resources.
145 exe.add_python_resources(exe.pip_install(["--verbose", ROOT]))
146
147 # On Windows, we install extra packages for convenience.
148 if IS_WINDOWS:
149 exe.add_python_resources(
150 exe.pip_install(["-r", ROOT + "/contrib/packaging/requirements-windows-py3.txt"]),
151 )
152 if IS_MACOS:
153 exe.add_python_resources(
154 exe.pip_install(["-r", ROOT + "/contrib/packaging/requirements-macos.txt"]),
155 )
156 extra_packages = VARS.get("extra_py_packages", "")
157 if extra_packages:
158 for extra in extra_packages.split(","):
159 extra_src, pkgs = extra.split("=")
160 pkgs = pkgs.split(":")
161 exe.add_python_resources(exe.read_package_root(extra_src, pkgs))
162
163 return exe
164
165 def make_manifest(dist, exe):
166 m = FileManifest()
167 m.add_python_resource(".", exe)
168
169 return m
170
171
172 # This adjusts the InstallManifest produced from exe generation to provide
173 # additional files found in a Windows install layout.
174 def make_windows_install_layout(manifest):
175 # Copy various files to new install locations. This can go away once
176 # we're using the importlib resource reader.
177 RECURSIVE_COPIES = {
178 "lib/mercurial/locale/": "locale/",
179 "lib/mercurial/templates/": "templates/",
180 }
181 for (search, replace) in RECURSIVE_COPIES.items():
182 for path in manifest.paths():
183 if path.startswith(search):
184 new_path = path.replace(search, replace)
185 print("copy %s to %s" % (path, new_path))
186 file = manifest.get_file(path)
187 manifest.add_file(file, path = new_path)
188
189 # Similar to above, but with filename pattern matching.
190 # lib/mercurial/helptext/**/*.txt -> helptext/
191 # lib/mercurial/defaultrc/*.rc -> defaultrc/
192 for path in manifest.paths():
193 if path.startswith("lib/mercurial/helptext/") and path.endswith(".txt"):
194 new_path = path[len("lib/mercurial/"):]
195 elif path.startswith("lib/mercurial/defaultrc/") and path.endswith(".rc"):
196 new_path = path[len("lib/mercurial/"):]
197 else:
198 continue
199
200 print("copying %s to %s" % (path, new_path))
201 manifest.add_file(manifest.get_file(path), path = new_path)
202
203 extra_install_files = VARS.get("extra_install_files", "")
204 if extra_install_files:
205 for extra in extra_install_files.split(","):
206 print("adding extra files from %s" % extra)
207 # TODO: I expected a ** glob to work, but it didn't.
208 #
209 # TODO: I know this has forward-slash paths. As far as I can tell,
210 # backslashes don't ever match glob() expansions in
211 # tugger-starlark, even on Windows.
212 manifest.add_manifest(glob(include=[extra + "/*/*"], strip_prefix=extra+"/"))
213
214 # We also install a handful of additional files.
215 EXTRA_CONTRIB_FILES = [
216 "bash_completion",
217 "hgweb.fcgi",
218 "hgweb.wsgi",
219 "logo-droplets.svg",
220 "mercurial.el",
221 "mq.el",
222 "tcsh_completion",
223 "tcsh_completion_build.sh",
224 "xml.rnc",
225 "zsh_completion",
226 ]
227
228 for f in EXTRA_CONTRIB_FILES:
229 manifest.add_file(FileContent(path = ROOT + "/contrib/" + f), directory = "contrib")
230
231 # Individual files with full source to destination path mapping.
232 EXTRA_FILES = {
233 "contrib/hgk": "contrib/hgk.tcl",
234 "contrib/win32/postinstall.txt": "ReleaseNotes.txt",
235 "contrib/win32/ReadMe.html": "ReadMe.html",
236 "doc/style.css": "doc/style.css",
237 "COPYING": "Copying.txt",
238 }
239
240 for source, dest in EXTRA_FILES.items():
241 print("adding extra file %s" % dest)
242 manifest.add_file(FileContent(path = ROOT + "/" + source), path = dest)
243
244 # And finally some wildcard matches.
245 manifest.add_manifest(glob(
246 include = [ROOT + "/contrib/vim/*"],
247 strip_prefix = ROOT + "/"
248 ))
249 manifest.add_manifest(glob(
250 include = [ROOT + "/doc/*.html"],
251 strip_prefix = ROOT + "/"
252 ))
253
254 # But we don't ship hg-ssh on Windows, so exclude its documentation.
255 manifest.remove("doc/hg-ssh.8.html")
256
257 return manifest
258
259
260 def make_msi(manifest):
261 manifest = make_windows_install_layout(manifest)
262
263 if "x86_64" in BUILD_TARGET_TRIPLE:
264 platform = "x64"
265 else:
266 platform = "x86"
267
268 manifest.add_file(
269 FileContent(path = ROOT + "/contrib/packaging/wix/COPYING.rtf"),
270 path = "COPYING.rtf",
271 )
272 manifest.remove("Copying.txt")
273 manifest.add_file(
274 FileContent(path = ROOT + "/contrib/win32/mercurial.ini"),
275 path = "defaultrc/mercurial.rc",
276 )
277 manifest.add_file(
278 FileContent(filename = "editor.rc", content = "[ui]\neditor = notepad\n"),
279 path = "defaultrc/editor.rc",
280 )
281
282 wix = WiXInstaller(
283 "hg",
284 "%s-%s-%s.msi" % (MSI_NAME, VERSION, platform),
285 arch = platform,
286 )
287
288 # Materialize files in the manifest to the install layout.
289 wix.add_install_files(manifest)
290
291 # From mercurial.wxs.
292 wix.install_files_root_directory_id = "INSTALLDIR"
293
294 # Pull in our custom .wxs files.
295 defines = {
296 "PyOxidizer": "1",
297 "Platform": platform,
298 "Version": VERSION,
299 "Comments": "Installs Mercurial version %s" % VERSION,
300 "MercurialHasLib": "1",
301 }
302
303 if EXTRA_MSI_FEATURES:
304 defines["MercurialExtraFeatures"] = EXTRA_MSI_FEATURES
305
306 wix.add_wxs_file(
307 ROOT + "/contrib/packaging/wix/mercurial.wxs",
308 preprocessor_parameters=defines,
309 )
310
311 # Our .wxs references to other files. Pull those into the build environment.
312 for f in ("defines.wxi", "guids.wxi", "COPYING.rtf"):
313 wix.add_build_file(f, ROOT + "/contrib/packaging/wix/" + f)
314
315 wix.add_build_file("mercurial.ico", ROOT + "/contrib/win32/mercurial.ico")
316
317 return wix
318
319
320 def register_code_signers():
321 if not IS_WINDOWS:
322 return
323
324 if SIGNING_PFX_PATH:
325 signer = code_signer_from_pfx_file(SIGNING_PFX_PATH, SIGNING_PFX_PASSWORD)
326 elif SIGNING_SUBJECT_NAME:
327 signer = code_signer_from_windows_store_subject(SIGNING_SUBJECT_NAME)
328 else:
329 signer = None
330
331 if signer:
332 signer.set_time_stamp_server(TIME_STAMP_SERVER_URL)
333 signer.activate()
334
335
336 register_code_signers()
337
338 register_target("distribution", make_distribution)
339 register_target("exe", make_exe, depends = ["distribution"])
340 register_target("app", make_manifest, depends = ["distribution", "exe"], default = True)
341 register_target("msi", make_msi, depends = ["app"])
342
343 resolve_targets()