Debian Codegraph @

js/src/make-source-package.py

raw
1 #!/usr/bin/env -S python3 -B
2 # This Source Code Form is subject to the terms of the Mozilla Public
3 # License, v. 2.0. If a copy of the MPL was not distributed with this file,
4 # You can obtain one at http://mozilla.org/MPL/2.0/.
5
6 import argparse
7 import enum
8 import logging
9 import os
10 import shutil
11 import subprocess
12 import sys
13 from pathlib import Path
14
15 logging.basicConfig(format="%(levelname)s: %(message)s", level=logging.INFO)
16
17
18 def find_command(names):
19 """Search for command in `names`, and returns the first one that exists."""
20
21 for name in names:
22 path = shutil.which(name)
23 if path is not None:
24 return name
25
26 return None
27
28
29 def assert_command(env_var, name):
30 """Assert that the command is not empty
31 The command name comes from either environment variable or find_command.
32 """
33 if not name:
34 logging.error(f"{env_var} command not found")
35 sys.exit(1)
36
37
38 def parse_version(topsrc_dir):
39 """Parse milestone.txt and return the entire milestone and major version."""
40 milestone_file = topsrc_dir / "config" / "milestone.txt"
41 if not milestone_file.is_file():
42 return ("", "", "")
43
44 with milestone_file.open("r") as f:
45 for line in f:
46 line = line.strip()
47 if not line:
48 continue
49 if line.startswith("#"):
50 continue
51
52 v = line.split(".")
53 return tuple((v + ["", ""])[:3])
54
55 return ("", "", "")
56
57
58 tmp_dir = Path("/tmp")
59
60 tar = os.environ.get("TAR", find_command(["tar"]))
61 assert_command("TAR", tar)
62
63 rsync = os.environ.get("RSYNC", find_command(["rsync"]))
64 assert_command("RSYNC", rsync)
65
66 awk = os.environ.get("AWK", find_command(["awk"]))
67 assert_command("AWK", awk)
68
69 src_dir = Path(os.environ.get("SRC_DIR", Path(__file__).parent.absolute()))
70 mozjs_name = os.environ.get("MOZJS_NAME", "mozjs")
71 staging_dir = Path(os.environ.get("STAGING", tmp_dir / "mozjs-src-pkg"))
72 dist_dir = Path(os.environ.get("DIST", tmp_dir))
73 topsrc_dir = src_dir.parent.parent.absolute()
74
75 parsed_major_version, parsed_minor_version, parsed_patch_version = parse_version(
76 topsrc_dir
77 )
78
79 major_version = os.environ.get("MOZJS_MAJOR_VERSION", parsed_major_version)
80 minor_version = os.environ.get("MOZJS_MINOR_VERSION", parsed_minor_version)
81 patch_version = os.environ.get("MOZJS_PATCH_VERSION", parsed_patch_version)
82 alpha = os.environ.get("MOZJS_ALPHA", "")
83
84 version = "{}-{}.{}.{}".format(
85 mozjs_name, major_version, minor_version, patch_version or alpha or "0"
86 )
87 target_dir = staging_dir / version
88 package_name = f"{version}.tar.xz"
89 package_file = dist_dir / package_name
90 tar_opts = ["-Jcf"]
91
92 # Given there might be some external program that reads the following output,
93 # use raw `print`, instead of logging.
94 print("Environment:")
95 print(f" TAR = {tar}")
96 print(f" RSYNC = {rsync}")
97 print(f" AWK = {awk}")
98 print(f" STAGING = {staging_dir}")
99 print(f" DIST = {dist_dir}")
100 print(f" SRC_DIR = {src_dir}")
101 print(f" MOZJS_NAME = {mozjs_name}")
102 print(f" MOZJS_MAJOR_VERSION = {major_version}")
103 print(f" MOZJS_MINOR_VERSION = {minor_version}")
104 print(f" MOZJS_PATCH_VERSION = {patch_version}")
105 print(f" MOZJS_ALPHA = {alpha}")
106 print("")
107
108 rsync_filter_list = """
109 # Top-level config and build files
110
111 + /client.mk
112 + /configure.py
113 + /LICENSE
114 + /mach
115 + /Makefile.in
116 + /moz.build
117 + /moz.configure
118 + /test.mozbuild
119 + /.babel-eslint.rc.js
120 + /.eslintrc*.js
121 + /.flake8
122 + /.gitignore
123 + /.hgignore
124 + /.lldbinit
125 + /.prettierignore
126 + /.prettierrc
127 + /.ycm_extra_conf.py
128
129 # Additional libraries (optionally) used by SpiderMonkey
130
131 + /mfbt/**
132 + /nsprpub/**
133
134 + /intl/bidi/**
135
136 - /intl/icu/source/data
137 - /intl/icu/source/test
138 - /intl/icu/source/tools
139 + /intl/icu/**
140
141 + /intl/icu_capi/**
142 + /intl/icu_segmenter_data/**
143
144 - /intl/components/gtest
145 + /intl/components/**
146
147 + /memory/replace/dmd/dmd.py
148 + /memory/build/**
149 + /memory/moz.build
150 + /memory/mozalloc/**
151
152 + /modules/fdlibm/**
153 + /modules/zlib/**
154
155 + /mozglue/baseprofiler/**
156 + /mozglue/build/**
157 + /mozglue/interposers/**
158 + /mozglue/misc/**
159 + /mozglue/moz.build
160 + /mozglue/static/**
161
162 + /tools/rb/fix_stacks.py
163 + /tools/fuzzing/moz.build
164 + /tools/fuzzing/interface/**
165 + /tools/fuzzing/registry/**
166 + /tools/fuzzing/libfuzzer/**
167 + /tools/fuzzing/*.mozbuild
168
169 # Build system and dependencies
170
171 + /Cargo.lock
172 + /build/**
173 + /config/**
174 + /python/**
175
176 + /.cargo/config.toml.in
177
178 + /third_party/fmt/**
179 + /third_party/function2/**
180 - /third_party/python/gyp
181 + /third_party/python/**
182 + /third_party/rust/**
183 + /third_party/gemmology/**
184 + /third_party/xsimd/**
185 + /layout/tools/reftest/reftest/**
186
187 + /testing/*.py
188 + /testing/moz.build
189 + /testing/mozbase/**
190 + /testing/mozharness/**
191 + /testing/performance/**
192 + /testing/test/**
193 + /testing/web-platform/*.ini
194 + /testing/web-platform/*.py
195 + /testing/web-platform/meta/streams/**
196 + /testing/web-platform/mozilla/**
197 + /testing/web-platform/tests/resources/**
198 + /testing/web-platform/tests/streams/**
199 + /testing/web-platform/tests/tools/**
200
201 + /toolkit/crashreporter/tools/symbolstore.py
202 + /toolkit/mozapps/installer/package-name.mk
203
204 + /xpcom/geckoprocesstypes_generator/**
205
206 # List of prefs.
207 + /modules/libpref/init/StaticPrefList.yaml
208
209 # SpiderMonkey itself
210
211 + /js/src/**
212 + /js/app.mozbuild
213 + /js/*.configure
214 + /js/examples/**
215 + /js/public/**
216
217 + */
218 - /**
219 """
220
221 INSTALL_CONTENT = """\
222 Documentation for SpiderMonkey is available at:
223
224 https://spidermonkey.dev/
225
226 In particular, it points to build documentation at
227
228 https://firefox-source-docs.mozilla.org/js/build.html
229
230 Note that the libraries produced by the build system include symbols,
231 causing the binaries to be extremely large. It is highly suggested that `strip`
232 be run over the binaries before deploying them.
233
234 Building with default options may be performed as follows:
235
236 ./mach build
237
238 This will produce a debug build (much more suitable for developing against the
239 SpiderMonkey JSAPI). To produce an optimized build:
240
241 export MOZCONFIG=$(pwd)/mozconfig.opt
242 ./mach build
243
244 You may edit the mozconfig and mozconfig.opt files to configure your own build
245 appropriately.
246 """
247
248 MOZCONFIG_DEBUG_CONTENT = """\
249 # Much slower when running, but adds assertions that are much better for
250 # developing against the JSAPI.
251 ac_add_options --enable-debug
252
253 # Much faster when running, worse for debugging.
254 ac_add_options --enable-optimize
255
256 mk_add_options MOZ_OBJDIR=obj-debug
257 """
258
259 MOZCONFIG_OPT_CONTENT = """\
260 # Much faster when running, but very error-prone to develop against because
261 # this will skip all the assertions critical to using the JSAPI properly.
262 ac_add_options --disable-debug
263
264 # Much faster when running, worse for debugging.
265 ac_add_options --enable-optimize
266
267 mk_add_options MOZ_OBJDIR=obj-opt
268 """
269
270 README_CONTENT = f"""\
271 This directory contains SpiderMonkey {major_version}.
272
273 This release is based on a revision of Mozilla {major_version}:
274 https://hg.mozilla.org/releases/
275 The changes in the patches/ directory were applied.
276
277 See https://spidermonkey.dev/ for documentation, examples, and release notes.
278 """
279
280
281 def is_mozjs_cargo_member(line):
282 """Checks if the line in workspace.members is mozjs-related"""
283
284 return '"js/' in line
285
286
287 def is_mozjs_crates_io_local_patch(line):
288 """Checks if the line in patch.crates-io is mozjs-related"""
289
290 return any(
291 f'path = "{p}' in line for p in ("js", "build", "third_party/rust", "intl")
292 )
293
294
295 def clean():
296 """Remove temporary directory and package file."""
297 logging.info(f"Cleaning {package_file} and {target_dir} ...")
298 if package_file.exists():
299 package_file.unlink()
300 if target_dir.exists():
301 shutil.rmtree(str(target_dir))
302
303
304 def assert_clean():
305 """Assert that target directory does not contain generated files."""
306 makefile_file = target_dir / "js" / "src" / "Makefile"
307 if makefile_file.exists():
308 logging.error("found js/src/Makefile. Please clean before packaging.")
309 sys.exit(1)
310
311
312 def create_target_dir():
313 if target_dir.exists():
314 logging.warning(f"dist tree {target_dir} already exists!")
315 else:
316 target_dir.mkdir(parents=True)
317
318
319 def sync_files():
320 # Output of the command should directly go to stdout/stderr.
321 p = subprocess.Popen(
322 [
323 str(rsync),
324 "--delete-excluded",
325 "--prune-empty-dirs",
326 "--quiet",
327 "--recursive",
328 f"{topsrc_dir}/",
329 f"{target_dir}/",
330 "--filter=. -",
331 ],
332 stdin=subprocess.PIPE,
333 )
334
335 p.communicate(rsync_filter_list.encode())
336
337 if p.returncode != 0:
338 sys.exit(p.returncode)
339
340
341 def copy_cargo_toml():
342 cargo_toml_file = topsrc_dir / "Cargo.toml"
343 target_cargo_toml_file = target_dir / "Cargo.toml"
344
345 with cargo_toml_file.open("r") as f:
346
347 class State(enum.Enum):
348 BEFORE_MEMBER = 1
349 INSIDE_MEMBER = 2
350 AFTER_MEMBER = 3
351 INSIDE_PATCH = 4
352 AFTER_PATCH = 5
353
354 content = ""
355 state = State.BEFORE_MEMBER
356 for line in f:
357 if state == State.BEFORE_MEMBER:
358 if line.strip() == "members = [":
359 state = State.INSIDE_MEMBER
360 elif state == State.INSIDE_MEMBER:
361 if line.strip() == "]":
362 state = State.AFTER_MEMBER
363 elif not is_mozjs_cargo_member(line):
364 continue
365 elif state == State.AFTER_MEMBER:
366 if line.strip() == "[patch.crates-io]":
367 state = State.INSIDE_PATCH
368 elif state == State.INSIDE_PATCH:
369 if line.startswith("["):
370 state = State.AFTER_PATCH
371 if "path = " in line:
372 if not is_mozjs_crates_io_local_patch(line):
373 continue
374
375 content += line
376
377 with target_cargo_toml_file.open("w") as f:
378 f.write(content)
379
380
381 def copy_file(filename, content):
382 """Copy an existing file from the staging area, or create a new file
383 with the given contents if it does not exist."""
384
385 staging_file = staging_dir / filename
386 target_file = target_dir / filename
387
388 if staging_file.exists():
389 shutil.copy2(str(staging_file), str(target_file))
390 else:
391 with target_file.open("w") as f:
392 f.write(content)
393
394
395 def copy_patches():
396 """Copy patches dir, if it exists."""
397
398 staging_patches_dir = staging_dir / "patches"
399 top_patches_dir = topsrc_dir / "patches"
400 target_patches_dir = target_dir / "patches"
401
402 if staging_patches_dir.is_dir():
403 shutil.copytree(str(staging_patches_dir), str(target_patches_dir))
404 elif top_patches_dir.is_dir():
405 shutil.copytree(str(top_patches_dir), str(target_patches_dir))
406
407
408 def remove_python_cache():
409 """Remove *.pyc and *.pyo files if any."""
410 for f in target_dir.glob("**/*.pyc"):
411 f.unlink()
412 for f in target_dir.glob("**/*.pyo"):
413 f.unlink()
414
415
416 def stage():
417 """Stage source tarball content."""
418 logging.info(f"Staging source tarball in {target_dir}...")
419
420 create_target_dir()
421 sync_files()
422 copy_cargo_toml()
423 copy_file("INSTALL", INSTALL_CONTENT)
424 copy_file("README", README_CONTENT)
425 copy_file("mozconfig", MOZCONFIG_DEBUG_CONTENT)
426 copy_file("mozconfig.opt", MOZCONFIG_OPT_CONTENT)
427 copy_patches()
428 remove_python_cache()
429
430
431 def create_tar():
432 """Roll the tarball."""
433
434 logging.info(f"Packaging source tarball at {package_file}...")
435
436 subprocess.run(
437 [str(tar)] + tar_opts + [str(package_file), "-C", str(staging_dir), version],
438 check=True,
439 )
440
441
442 def build():
443 assert_clean()
444 stage()
445 create_tar()
446
447
448 parser = argparse.ArgumentParser(description="Make SpiderMonkey source package")
449 subparsers = parser.add_subparsers(dest="COMMAND")
450 subparser_update = subparsers.add_parser("clean", help="")
451 subparser_update = subparsers.add_parser("build", help="")
452 args = parser.parse_args()
453
454 if args.COMMAND == "clean":
455 clean()
456 elif not args.COMMAND or args.COMMAND == "build":
457 build()