Debian Codegraph @

js/src/tests/test262-update.py

raw
1 #!/usr/bin/env python
2 #
3 # This Source Code Form is subject to the terms of the Mozilla Public
4 # License, v. 2.0. If a copy of the MPL was not distributed with this
5 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7 import contextlib
8 import os
9 import shutil
10 import sys
11 import tempfile
12 from functools import partial
13 from itertools import chain
14 from operator import itemgetter
15
16 # Skip all tests which use features not supported in SpiderMonkey.
17 UNSUPPORTED_FEATURES = set(
18 [
19 "tail-call-optimization",
20 "Intl.Locale-info", # Bug 1693576
21 "legacy-regexp", # Bug 1306461
22 "source-phase-imports",
23 "source-phase-imports-module-source",
24 "import-defer",
25 ]
26 )
27 FEATURE_CHECK_NEEDED = {
28 "Atomics": "!this.hasOwnProperty('Atomics')",
29 "FinalizationRegistry": "!this.hasOwnProperty('FinalizationRegistry')",
30 "SharedArrayBuffer": "!this.hasOwnProperty('SharedArrayBuffer')",
31 "Temporal": "!this.hasOwnProperty('Temporal')",
32 "WeakRef": "!this.hasOwnProperty('WeakRef')",
33 "decorators": "!(this.hasOwnProperty('getBuildConfiguration')&&getBuildConfiguration('decorators'))", # Bug 1435869
34 "iterator-helpers": "!this.hasOwnProperty('Iterator')", # Bug 1568906
35 "Intl.Segmenter": "!Intl.Segmenter", # Bug 1423593
36 "Intl.DurationFormat": "!Intl.hasOwnProperty('DurationFormat')", # Bug 1648139
37 "uint8array-base64": "!Uint8Array.fromBase64", # Bug 1862220
38 "json-parse-with-source": "!JSON.hasOwnProperty('isRawJSON')", # Bug 1658310
39 "RegExp.escape": "!RegExp.escape",
40 "promise-try": "!Promise.try",
41 "explicit-resource-management": "!(this.hasOwnProperty('getBuildConfiguration')&&getBuildConfiguration('explicit-resource-management'))", # Bug 1569081
42 "Atomics.pause": "!this.hasOwnProperty('Atomics')||!Atomics.pause",
43 "Error.isError": "!Error.isError",
44 "iterator-sequencing": "!Iterator.concat",
45 "Math.sumPrecise": "!Math.sumPrecise", # Bug 1918708
46 "upsert": "!Map.prototype.getOrInsertComputed",
47 }
48 RELEASE_OR_BETA = set(
49 [
50 "regexp-modifiers",
51 "symbols-as-weakmap-keys",
52 ]
53 )
54 SHELL_OPTIONS = {
55 "import-attributes": "--enable-import-attributes",
56 "ShadowRealm": "--enable-shadow-realms",
57 "iterator-helpers": "--enable-iterator-helpers",
58 "symbols-as-weakmap-keys": "--enable-symbols-as-weakmap-keys",
59 "uint8array-base64": "--enable-uint8array-base64",
60 "json-parse-with-source": "--enable-json-parse-with-source",
61 "regexp-duplicate-named-groups": "--enable-regexp-duplicate-named-groups",
62 "RegExp.escape": "--enable-regexp-escape",
63 "regexp-modifiers": "--enable-regexp-modifiers",
64 "promise-try": "--enable-promise-try",
65 "explicit-resource-management": "--enable-explicit-resource-management",
66 "Atomics.pause": "--enable-atomics-pause",
67 "Temporal": "--enable-temporal",
68 "Error.isError": "--enable-error-iserror",
69 "iterator-sequencing": "--enable-iterator-sequencing",
70 "Math.sumPrecise": "--enable-math-sumprecise",
71 "Atomics.waitAsync": "--setpref=atomics_wait_async",
72 "upsert": "--enable-upsert",
73 }
74
75 INCLUDE_FEATURE_DETECTED_OPTIONAL_SHELL_OPTIONS = {}
76
77
78 @contextlib.contextmanager
79 def TemporaryDirectory():
80 tmpDir = tempfile.mkdtemp()
81 try:
82 yield tmpDir
83 finally:
84 shutil.rmtree(tmpDir)
85
86
87 def loadTest262Parser(test262Dir):
88 """
89 Loads the test262 test record parser.
90 """
91 import importlib.machinery
92 import importlib.util
93
94 packagingDir = os.path.join(test262Dir, "tools", "packaging")
95 moduleName = "parseTestRecord"
96
97 # Create a FileFinder to load Python source files.
98 loader_details = (
99 importlib.machinery.SourceFileLoader,
100 importlib.machinery.SOURCE_SUFFIXES,
101 )
102 finder = importlib.machinery.FileFinder(packagingDir, loader_details)
103
104 # Find the module spec.
105 spec = finder.find_spec(moduleName)
106 if spec is None:
107 raise RuntimeError("Can't find parseTestRecord module")
108
109 # Create and execute the module.
110 module = importlib.util.module_from_spec(spec)
111 spec.loader.exec_module(module)
112
113 # Return the executed module
114 return module
115
116
117 def tryParseTestFile(test262parser, source, testName):
118 """
119 Returns the result of test262parser.parseTestRecord() or None if a parser
120 error occured.
121
122 See <https://github.com/tc39/test262/blob/main/INTERPRETING.md> for an
123 overview of the returned test attributes.
124 """
125 try:
126 return test262parser.parseTestRecord(source, testName)
127 except Exception as err:
128 print("Error '%s' in file: %s" % (err, testName), file=sys.stderr)
129 print("Please report this error to the test262 GitHub repository!")
130 return None
131
132
133 def createRefTestEntry(options, skip, skipIf, error, isModule, isAsync):
134 """
135 Returns the |reftest| tuple (terms, comments) from the input arguments. Or a
136 tuple of empty strings if no reftest entry is required.
137 """
138
139 terms = []
140 comments = []
141
142 if options:
143 terms.extend(options)
144
145 if skip:
146 terms.append("skip")
147 comments.extend(skip)
148
149 if skipIf:
150 terms.append("skip-if(" + "||".join([cond for (cond, _) in skipIf]) + ")")
151 comments.extend([comment for (_, comment) in skipIf])
152
153 if error:
154 terms.append("error:" + error)
155
156 if isModule:
157 terms.append("module")
158
159 if isAsync:
160 terms.append("async")
161
162 return (" ".join(terms), ", ".join(comments))
163
164
165 def createRefTestLine(terms, comments):
166 """
167 Creates the |reftest| line using the given terms and comments.
168 """
169
170 refTest = terms
171 if comments:
172 refTest += " -- " + comments
173 return refTest
174
175
176 def createSource(testSource, refTest, prologue, epilogue):
177 """
178 Returns the post-processed source for |testSource|.
179 """
180
181 source = []
182
183 # Add the |reftest| line.
184 if refTest:
185 source.append(b"// |reftest| " + refTest.encode("utf-8"))
186
187 # Prepend any directives if present.
188 if prologue:
189 source.append(prologue.encode("utf-8"))
190
191 source.append(testSource)
192
193 # Append the test epilogue, i.e. the call to "reportCompare".
194 # TODO: Does this conflict with raw tests?
195 if epilogue:
196 source.append(epilogue.encode("utf-8"))
197 source.append(b"")
198
199 return b"\n".join(source)
200
201
202 def writeTestFile(test262OutDir, testFileName, source):
203 """
204 Writes the test source to |test262OutDir|.
205 """
206
207 with open(os.path.join(test262OutDir, testFileName), "wb") as output:
208 output.write(source)
209
210
211 def addSuffixToFileName(fileName, suffix):
212 (filePath, ext) = os.path.splitext(fileName)
213 return filePath + suffix + ext
214
215
216 def writeShellAndBrowserFiles(
217 test262OutDir, harnessDir, includesMap, localIncludesMap, relPath
218 ):
219 """
220 Generate the shell.js and browser.js files for the test harness.
221 """
222
223 # Find all includes from parent directories.
224 def findParentIncludes():
225 parentIncludes = set()
226 current = relPath
227 while current:
228 (parent, child) = os.path.split(current)
229 if parent in includesMap:
230 parentIncludes.update(includesMap[parent])
231 current = parent
232 return parentIncludes
233
234 # Find all includes, skipping includes already present in parent directories.
235 def findIncludes():
236 parentIncludes = findParentIncludes()
237 for include in includesMap[relPath]:
238 if include not in parentIncludes:
239 yield include
240
241 def readIncludeFile(filePath):
242 with open(filePath, "rb") as includeFile:
243 return b"// file: %s\n%s" % (
244 os.path.basename(filePath).encode("utf-8"),
245 includeFile.read(),
246 )
247
248 localIncludes = localIncludesMap[relPath] if relPath in localIncludesMap else []
249
250 # Concatenate all includes files.
251 includeSource = b"\n".join(
252 map(
253 readIncludeFile,
254 chain(
255 # The requested include files.
256 map(partial(os.path.join, harnessDir), sorted(findIncludes())),
257 # And additional local include files.
258 map(partial(os.path.join, os.getcwd()), sorted(localIncludes)),
259 ),
260 )
261 )
262
263 # Write the concatenated include sources to shell.js.
264 with open(os.path.join(test262OutDir, relPath, "shell.js"), "wb") as shellFile:
265 if includeSource:
266 shellFile.write(b"// GENERATED, DO NOT EDIT\n")
267 shellFile.write(includeSource)
268
269 # The browser.js file is always empty for test262 tests.
270 with open(os.path.join(test262OutDir, relPath, "browser.js"), "wb") as browserFile:
271 browserFile.write(b"")
272
273
274 def pathStartsWith(path, *args):
275 prefix = os.path.join(*args)
276 return os.path.commonprefix([path, prefix]) == prefix
277
278
279 def convertTestFile(test262parser, testSource, testName, includeSet, strictTests):
280 """
281 Convert a test262 test to a compatible jstests test file.
282 """
283
284 # The test record dictionary, its contents are explained in depth at
285 # <https://github.com/tc39/test262/blob/main/INTERPRETING.md>.
286 testRec = tryParseTestFile(test262parser, testSource.decode("utf-8"), testName)
287
288 # jsreftest meta data
289 refTestOptions = []
290 refTestSkip = []
291 refTestSkipIf = []
292
293 # Skip all files which contain YAML errors.
294 if testRec is None:
295 refTestSkip.append("has YAML errors")
296 testRec = dict()
297
298 # onlyStrict is set when the test must only be run in strict mode.
299 onlyStrict = "onlyStrict" in testRec
300
301 # noStrict is set when the test must not be run in strict mode.
302 noStrict = "noStrict" in testRec
303
304 # The "raw" attribute is used in the default test262 runner to prevent
305 # prepending additional content (use-strict directive, harness files)
306 # before the actual test source code.
307 raw = "raw" in testRec
308
309 # Negative tests have additional meta-data to specify the error type and
310 # when the error is issued (runtime error or early parse error). We're
311 # currently ignoring the error phase attribute.
312 # testRec["negative"] == {type=<error name>, phase=parse|resolution|runtime}
313 isNegative = "negative" in testRec
314 assert not isNegative or type(testRec["negative"]) is dict
315 errorType = testRec["negative"]["type"] if isNegative else None
316
317 # Async tests are marked with the "async" attribute.
318 isAsync = "async" in testRec
319
320 # Test262 tests cannot be both "negative" and "async". (In principle a
321 # negative async test is permitted when the error phase is not "parse" or
322 # the error type is not SyntaxError, but no such tests exist now.)
323 assert not (isNegative and isAsync), (
324 "Can't have both async and negative attributes: %s" % testName
325 )
326
327 # Only async tests may use the $DONE or asyncTest function. However,
328 # negative parse tests may "use" the $DONE (or asyncTest) function (of
329 # course they don't actually use it!) without specifying the "async"
330 # attribute. Otherwise, neither $DONE nor asyncTest must appear in the test.
331 #
332 # Some "harness" tests redefine $DONE, so skip this check when the test file
333 # is in the "harness" directory.
334 assert (
335 (b"$DONE" not in testSource and b"asyncTest" not in testSource)
336 or isAsync
337 or isNegative
338 or testName.split(os.path.sep)[0] == "harness"
339 ), ("Missing async attribute in: %s" % testName)
340
341 # When the "module" attribute is set, the source code is module code.
342 isModule = "module" in testRec
343
344 # CanBlockIsFalse is set when the test expects that the implementation
345 # cannot block on the main thread.
346 if "CanBlockIsFalse" in testRec:
347 refTestSkipIf.append(("xulRuntime.shell", "shell can block main thread"))
348
349 # CanBlockIsTrue is set when the test expects that the implementation
350 # can block on the main thread.
351 if "CanBlockIsTrue" in testRec:
352 refTestSkipIf.append(("!xulRuntime.shell", "browser cannot block main thread"))
353
354 # Skip tests with unsupported features.
355 if "features" in testRec:
356 unsupported = [f for f in testRec["features"] if f in UNSUPPORTED_FEATURES]
357 if unsupported:
358 refTestSkip.append("%s is not supported" % ",".join(unsupported))
359 else:
360 releaseOrBeta = [f for f in testRec["features"] if f in RELEASE_OR_BETA]
361 if releaseOrBeta:
362 refTestSkipIf.append(
363 (
364 "release_or_beta",
365 "%s is not released yet" % ",".join(releaseOrBeta),
366 )
367 )
368
369 featureCheckNeeded = [
370 f for f in testRec["features"] if f in FEATURE_CHECK_NEEDED
371 ]
372 if featureCheckNeeded:
373 refTestSkipIf.append(
374 (
375 "||".join(
376 [FEATURE_CHECK_NEEDED[f] for f in featureCheckNeeded]
377 ),
378 "%s is not enabled unconditionally"
379 % ",".join(featureCheckNeeded),
380 )
381 )
382
383 if (
384 "Atomics" in testRec["features"]
385 and "SharedArrayBuffer" in testRec["features"]
386 ):
387 refTestSkipIf.append(
388 (
389 "(this.hasOwnProperty('getBuildConfiguration')"
390 "&&getBuildConfiguration('arm64-simulator'))",
391 "ARM64 Simulator cannot emulate atomics",
392 )
393 )
394
395 shellOptions = {
396 SHELL_OPTIONS[f] for f in testRec["features"] if f in SHELL_OPTIONS
397 }
398 if shellOptions:
399 refTestSkipIf.append(("!xulRuntime.shell", "requires shell-options"))
400 refTestOptions.extend(
401 f"shell-option({opt})" for opt in sorted(shellOptions)
402 )
403
404 # Optional shell options. Some tests use feature detection for additional
405 # test coverage. We want to get this extra coverage without having to skip
406 # these tests in browser builds.
407 if "includes" in testRec:
408 optionalShellOptions = (
409 SHELL_OPTIONS[INCLUDE_FEATURE_DETECTED_OPTIONAL_SHELL_OPTIONS[include]]
410 for include in testRec["includes"]
411 if include in INCLUDE_FEATURE_DETECTED_OPTIONAL_SHELL_OPTIONS
412 )
413 refTestOptions.extend(
414 f"shell-option({opt})" for opt in sorted(optionalShellOptions)
415 )
416
417 # Includes for every test file in a directory is collected in a single
418 # shell.js file per directory level. This is done to avoid adding all
419 # test harness files to the top level shell.js file.
420 if "includes" in testRec:
421 assert not raw, "Raw test with includes: %s" % testName
422 includeSet.update(testRec["includes"])
423
424 # Add reportCompare() after all positive, synchronous tests.
425 if not isNegative and not isAsync:
426 testEpilogue = "reportCompare(0, 0);"
427 else:
428 testEpilogue = ""
429
430 if raw:
431 refTestOptions.append("test262-raw")
432
433 (terms, comments) = createRefTestEntry(
434 refTestOptions, refTestSkip, refTestSkipIf, errorType, isModule, isAsync
435 )
436 if raw:
437 refTest = ""
438 externRefTest = (terms, comments)
439 else:
440 refTest = createRefTestLine(terms, comments)
441 externRefTest = None
442
443 # Don't write a strict-mode variant for raw or module files.
444 noStrictVariant = raw or isModule
445 assert not (noStrictVariant and (onlyStrict or noStrict)), (
446 "Unexpected onlyStrict or noStrict attribute: %s" % testName
447 )
448
449 # Write non-strict mode test.
450 if noStrictVariant or noStrict or not onlyStrict:
451 testPrologue = ""
452 nonStrictSource = createSource(testSource, refTest, testPrologue, testEpilogue)
453 testFileName = testName
454 yield (testFileName, nonStrictSource, externRefTest)
455
456 # Write strict mode test.
457 if not noStrictVariant and (onlyStrict or (not noStrict and strictTests)):
458 testPrologue = "'use strict';"
459 strictSource = createSource(testSource, refTest, testPrologue, testEpilogue)
460 testFileName = testName
461 if not noStrict:
462 testFileName = addSuffixToFileName(testFileName, "-strict")
463 yield (testFileName, strictSource, externRefTest)
464
465
466 def convertFixtureFile(fixtureSource, fixtureName):
467 """
468 Convert a test262 fixture file to a compatible jstests test file.
469 """
470
471 # jsreftest meta data
472 refTestOptions = []
473 refTestSkip = ["not a test file"]
474 refTestSkipIf = []
475 errorType = None
476 isModule = False
477 isAsync = False
478
479 (terms, comments) = createRefTestEntry(
480 refTestOptions, refTestSkip, refTestSkipIf, errorType, isModule, isAsync
481 )
482 refTest = createRefTestLine(terms, comments)
483
484 source = createSource(fixtureSource, refTest, "", "")
485 externRefTest = None
486 yield (fixtureName, source, externRefTest)
487
488
489 def process_test262(test262Dir, test262OutDir, strictTests, externManifests):
490 """
491 Process all test262 files and converts them into jstests compatible tests.
492 """
493
494 harnessDir = os.path.join(test262Dir, "harness")
495 testDir = os.path.join(test262Dir, "test")
496 test262parser = loadTest262Parser(test262Dir)
497
498 # Map of test262 subdirectories to the set of include files required for
499 # tests in that subdirectory. The includes for all tests in a subdirectory
500 # are merged into a single shell.js.
501 # map<dirname, set<includeFiles>>
502 includesMap = {}
503
504 # Additional local includes keyed by test262 directory names. The include
505 # files in this map must be located in the js/src/tests directory.
506 # map<dirname, list<includeFiles>>
507 localIncludesMap = {}
508
509 # The root directory contains required harness files and test262-host.js.
510 includesMap[""] = set(["sta.js", "assert.js"])
511 localIncludesMap[""] = ["test262-host.js"]
512
513 # Also add files known to be used by many tests to the root shell.js file.
514 includesMap[""].update(["propertyHelper.js", "compareArray.js"])
515
516 # Write the root shell.js file.
517 writeShellAndBrowserFiles(
518 test262OutDir, harnessDir, includesMap, localIncludesMap, ""
519 )
520
521 # Additional explicit includes inserted at well-chosen locations to reduce
522 # code duplication in shell.js files.
523 explicitIncludes = {}
524 explicitIncludes[os.path.join("built-ins", "Atomics")] = [
525 "testAtomics.js",
526 "testTypedArray.js",
527 ]
528 explicitIncludes[os.path.join("built-ins", "DataView")] = [
529 "byteConversionValues.js"
530 ]
531 explicitIncludes[os.path.join("built-ins", "Promise")] = ["promiseHelper.js"]
532 explicitIncludes[os.path.join("built-ins", "Temporal")] = ["temporalHelpers.js"]
533 explicitIncludes[os.path.join("built-ins", "TypedArray")] = [
534 "byteConversionValues.js",
535 "detachArrayBuffer.js",
536 "nans.js",
537 ]
538 explicitIncludes[os.path.join("built-ins", "TypedArrays")] = [
539 "detachArrayBuffer.js"
540 ]
541
542 # We can't include "sm/non262.js", because it conflicts with our test harness,
543 # but some definitions from "sm/non262.js" are still needed.
544 localIncludesMap[os.path.join("staging", "sm")] = ["test262-non262.js"]
545
546 # Process all test directories recursively.
547 for dirPath, dirNames, fileNames in os.walk(testDir):
548 relPath = os.path.relpath(dirPath, testDir)
549 if relPath == ".":
550 continue
551
552 # Skip creating a "prs" directory if it already exists
553 if relPath not in ("prs", "local") and not os.path.exists(
554 os.path.join(test262OutDir, relPath)
555 ):
556 os.makedirs(os.path.join(test262OutDir, relPath))
557
558 includeSet = set()
559 includesMap[relPath] = includeSet
560
561 if relPath in explicitIncludes:
562 includeSet.update(explicitIncludes[relPath])
563
564 # Convert each test file.
565 for fileName in fileNames:
566 filePath = os.path.join(dirPath, fileName)
567 testName = os.path.relpath(filePath, testDir)
568
569 # Copy non-test files as is.
570 (_, fileExt) = os.path.splitext(fileName)
571 if fileExt != ".js":
572 shutil.copyfile(filePath, os.path.join(test262OutDir, testName))
573 continue
574
575 # Files ending with "_FIXTURE.js" are fixture files:
576 # https://github.com/tc39/test262/blob/main/INTERPRETING.md#modules
577 isFixtureFile = fileName.endswith("_FIXTURE.js")
578
579 # Read the original test source and preprocess it for the jstests harness.
580 with open(filePath, "rb") as testFile:
581 testSource = testFile.read()
582
583 if isFixtureFile:
584 convert = convertFixtureFile(testSource, testName)
585 else:
586 convert = convertTestFile(
587 test262parser,
588 testSource,
589 testName,
590 includeSet,
591 strictTests,
592 )
593
594 for newFileName, newSource, externRefTest in convert:
595 writeTestFile(test262OutDir, newFileName, newSource)
596
597 if externRefTest is not None:
598 externManifests.append(
599 {
600 "name": newFileName,
601 "reftest": externRefTest,
602 }
603 )
604
605 # Remove "sm/non262.js" because it overwrites our test harness with stub
606 # functions.
607 includeSet.discard("sm/non262.js")
608
609 # Add shell.js and browers.js files for the current directory.
610 writeShellAndBrowserFiles(
611 test262OutDir, harnessDir, includesMap, localIncludesMap, relPath
612 )
613
614
615 def fetch_local_changes(inDir, outDir, srcDir, strictTests):
616 """
617 Fetch the changes from a local clone of Test262.
618
619 1. Get the list of file changes made by the current branch used on Test262 (srcDir).
620 2. Copy only the (A)dded, (C)opied, (M)odified, and (R)enamed files to inDir.
621 3. inDir is treated like a Test262 checkout, where files will be converted.
622 4. Fetches the current branch name to set the outDir.
623 5. Processed files will be added to `<outDir>/local/<branchName>`.
624 """
625 import subprocess
626
627 # TODO: fail if it's in the default branch? or require a branch name?
628 # Checks for unstaged or non committed files. A clean branch provides a clean status.
629 status = subprocess.check_output(
630 ("git -C %s status --porcelain" % srcDir).split(" "), encoding="utf-8"
631 )
632
633 if status.strip():
634 raise RuntimeError(
635 "Please commit files and cleanup the local test262 folder before importing files.\n"
636 "Current status: \n%s" % status
637 )
638
639 # Captures the branch name to be used on the output
640 branchName = subprocess.check_output(
641 ("git -C %s rev-parse --abbrev-ref HEAD" % srcDir).split(" "), encoding="utf-8"
642 ).split("\n")[0]
643
644 # Fetches the file names to import
645 files = subprocess.check_output(
646 ("git -C %s diff main --diff-filter=ACMR --name-only" % srcDir).split(" "),
647 encoding="utf-8",
648 )
649
650 # Fetches the deleted files to print an output log. This can be used to
651 # set up the skip list, if necessary.
652 deletedFiles = subprocess.check_output(
653 ("git -C %s diff main --diff-filter=D --name-only" % srcDir).split(" "),
654 encoding="utf-8",
655 )
656
657 # Fetches the modified files as well for logging to support maintenance
658 # in the skip list.
659 modifiedFiles = subprocess.check_output(
660 ("git -C %s diff main --diff-filter=M --name-only" % srcDir).split(" "),
661 encoding="utf-8",
662 )
663
664 # Fetches the renamed files for the same reason, this avoids duplicate
665 # tests if running the new local folder and the general imported Test262
666 # files.
667 renamedFiles = subprocess.check_output(
668 ("git -C %s diff main --diff-filter=R --summary" % srcDir).split(" "),
669 encoding="utf-8",
670 )
671
672 # Print some friendly output
673 print("From the branch %s in %s \n" % (branchName, srcDir))
674 print("Files being copied to the local folder: \n%s" % files)
675 if deletedFiles:
676 print(
677 "Deleted files (use this list to update the skip list): \n%s" % deletedFiles
678 )
679 if modifiedFiles:
680 print(
681 "Modified files (use this list to update the skip list): \n%s"
682 % modifiedFiles
683 )
684 if renamedFiles:
685 print("Renamed files (already added with the new names): \n%s" % renamedFiles)
686
687 for f in files.splitlines():
688 # Capture the subdirectories names to recreate the file tree
689 # TODO: join the file tree with -- instead of multiple subfolders?
690 fileTree = os.path.join(inDir, os.path.dirname(f))
691 if not os.path.exists(fileTree):
692 os.makedirs(fileTree)
693
694 shutil.copyfile(
695 os.path.join(srcDir, f), os.path.join(fileTree, os.path.basename(f))
696 )
697
698 # Extras from Test262. Copy the current support folders - including the
699 # harness - for a proper conversion process
700 shutil.copytree(os.path.join(srcDir, "tools"), os.path.join(inDir, "tools"))
701 shutil.copytree(os.path.join(srcDir, "harness"), os.path.join(inDir, "harness"))
702
703 # Reset any older directory in the output using the same branch name
704 outDir = os.path.join(outDir, "local", branchName)
705 if os.path.isdir(outDir):
706 shutil.rmtree(outDir)
707 os.makedirs(outDir)
708
709 process_test262(inDir, outDir, strictTests, [])
710
711
712 def fetch_pr_files(inDir, outDir, prNumber, strictTests):
713 import requests
714
715 prTestsOutDir = os.path.join(outDir, "prs", prNumber)
716 if os.path.isdir(prTestsOutDir):
717 print("Removing folder %s" % prTestsOutDir)
718 shutil.rmtree(prTestsOutDir)
719 os.makedirs(prTestsOutDir)
720
721 # Reuses current Test262 clone's harness and tools folders only, the clone's test/
722 # folder can be discarded from here
723 shutil.rmtree(os.path.join(inDir, "test"))
724
725 prRequest = requests.get(
726 "https://api.github.com/repos/tc39/test262/pulls/%s" % prNumber
727 )
728 prRequest.raise_for_status()
729
730 pr = prRequest.json()
731
732 if pr["state"] != "open":
733 # Closed PR, remove respective files from folder
734 return print("PR %s is closed" % prNumber)
735
736 url = "https://api.github.com/repos/tc39/test262/pulls/%s/files" % prNumber
737 hasNext = True
738
739 while hasNext:
740 files = requests.get(url)
741 files.raise_for_status()
742
743 for item in files.json():
744 if not item["filename"].startswith("test/"):
745 continue
746
747 filename = item["filename"]
748 fileStatus = item["status"]
749
750 print("%s %s" % (fileStatus, filename))
751
752 # Do not add deleted files
753 if fileStatus == "removed":
754 continue
755
756 contents = requests.get(item["raw_url"])
757 contents.raise_for_status()
758
759 fileText = contents.text
760
761 filePathDirs = os.path.join(inDir, *filename.split("/")[:-1])
762
763 if not os.path.isdir(filePathDirs):
764 os.makedirs(filePathDirs)
765
766 with open(os.path.join(inDir, *filename.split("/")), "wb") as output_file:
767 output_file.write(fileText.encode("utf8"))
768
769 hasNext = False
770
771 # Check if the pull request changes are split over multiple pages.
772 if "link" in files.headers:
773 link = files.headers["link"]
774
775 # The links are comma separated and the entries within a link are separated by a
776 # semicolon. For example the first two links entries for PR 3199:
777 #
778 # https://api.github.com/repos/tc39/test262/pulls/3199/files
779 # """
780 # <https://api.github.com/repositories/16147933/pulls/3199/files?page=2>; rel="next",
781 # <https://api.github.com/repositories/16147933/pulls/3199/files?page=14>; rel="last"
782 # """
783 #
784 # https://api.github.com/repositories/16147933/pulls/3199/files?page=2
785 # """
786 # <https://api.github.com/repositories/16147933/pulls/3199/files?page=1>; rel="prev",
787 # <https://api.github.com/repositories/16147933/pulls/3199/files?page=3>; rel="next",
788 # <https://api.github.com/repositories/16147933/pulls/3199/files?page=14>; rel="last",
789 # <https://api.github.com/repositories/16147933/pulls/3199/files?page=1>; rel="first"
790 # """
791
792 for pages in link.split(", "):
793 (pageUrl, rel) = pages.split("; ")
794
795 assert pageUrl[0] == "<"
796 assert pageUrl[-1] == ">"
797
798 # Remove the angle brackets around the URL.
799 pageUrl = pageUrl[1:-1]
800
801 # Make sure we only request data from github and not some other place.
802 assert pageUrl.startswith("https://api.github.com/")
803
804 # Ensure the relative URL marker has the expected format.
805 assert (
806 rel == 'rel="prev"'
807 or rel == 'rel="next"'
808 or rel == 'rel="first"'
809 or rel == 'rel="last"'
810 )
811
812 # We only need the URL for the next page.
813 if rel == 'rel="next"':
814 url = pageUrl
815 hasNext = True
816
817 process_test262(inDir, prTestsOutDir, strictTests, [])
818
819
820 def general_update(inDir, outDir, strictTests):
821 import subprocess
822
823 restoreLocalTestsDir = False
824 restorePrsTestsDir = False
825 localTestsOutDir = os.path.join(outDir, "local")
826 prsTestsOutDir = os.path.join(outDir, "prs")
827
828 # Stash test262/local and test262/prs. Currently the Test262 repo does not have any
829 # top-level subdirectories named "local" or "prs".
830 # This prevents these folders from being removed during the update process.
831 if os.path.isdir(localTestsOutDir):
832 shutil.move(localTestsOutDir, inDir)
833 restoreLocalTestsDir = True
834
835 if os.path.isdir(prsTestsOutDir):
836 shutil.move(prsTestsOutDir, inDir)
837 restorePrsTestsDir = True
838
839 # Create the output directory from scratch.
840 if os.path.isdir(outDir):
841 shutil.rmtree(outDir)
842 os.makedirs(outDir)
843
844 # Copy license file.
845 shutil.copyfile(os.path.join(inDir, "LICENSE"), os.path.join(outDir, "LICENSE"))
846
847 # Create the git info file.
848 with open(os.path.join(outDir, "GIT-INFO"), "w", encoding="utf-8") as info:
849 subprocess.check_call(["git", "-C", inDir, "log", "-1"], stdout=info)
850
851 # Copy the test files.
852 externManifests = []
853 process_test262(inDir, outDir, strictTests, externManifests)
854
855 # Create the external reftest manifest file.
856 with open(os.path.join(outDir, "jstests.list"), "wb") as manifestFile:
857 manifestFile.write(b"# GENERATED, DO NOT EDIT\n\n")
858 for externManifest in sorted(externManifests, key=itemgetter("name")):
859 (terms, comments) = externManifest["reftest"]
860 if terms:
861 entry = "%s script %s%s\n" % (
862 terms,
863 externManifest["name"],
864 (" # %s" % comments) if comments else "",
865 )
866 manifestFile.write(entry.encode("utf-8"))
867
868 # Move test262/local back.
869 if restoreLocalTestsDir:
870 shutil.move(os.path.join(inDir, "local"), outDir)
871
872 # Restore test262/prs if necessary after a general Test262 update.
873 if restorePrsTestsDir:
874 shutil.move(os.path.join(inDir, "prs"), outDir)
875
876
877 def update_test262(args):
878 import subprocess
879
880 url = args.url
881 branch = args.branch
882 revision = args.revision
883 outDir = args.out
884 prNumber = args.pull
885 srcDir = args.local
886
887 if not os.path.isabs(outDir):
888 outDir = os.path.join(os.getcwd(), outDir)
889
890 strictTests = args.strict
891
892 # Download the requested branch in a temporary directory.
893 with TemporaryDirectory() as inDir:
894 # If it's a local import, skip the git clone parts.
895 if srcDir:
896 return fetch_local_changes(inDir, outDir, srcDir, strictTests)
897
898 if revision == "HEAD":
899 subprocess.check_call(
900 ["git", "clone", "--depth=1", "--branch=%s" % branch, url, inDir]
901 )
902 else:
903 subprocess.check_call(
904 ["git", "clone", "--single-branch", "--branch=%s" % branch, url, inDir]
905 )
906 subprocess.check_call(["git", "-C", inDir, "reset", "--hard", revision])
907
908 # If a PR number is provided, fetches only the new and modified files
909 # from that PR. It also creates a new folder for that PR or replaces if
910 # it already exists, without updating the regular Test262 tests.
911 if prNumber:
912 return fetch_pr_files(inDir, outDir, prNumber, strictTests)
913
914 # Without a PR or a local import, follows through a regular copy.
915 general_update(inDir, outDir, strictTests)
916
917
918 if __name__ == "__main__":
919 import argparse
920
921 # This script must be run from js/src/tests to work correctly.
922 if "/".join(os.path.normpath(os.getcwd()).split(os.sep)[-3:]) != "js/src/tests":
923 raise RuntimeError("%s must be run from js/src/tests" % sys.argv[0])
924
925 parser = argparse.ArgumentParser(description="Update the test262 test suite.")
926 parser.add_argument(
927 "--url",
928 default="https://github.com/tc39/test262.git",
929 help="URL to git repository (default: %(default)s)",
930 )
931 parser.add_argument(
932 "--branch", default="main", help="Git branch (default: %(default)s)"
933 )
934 parser.add_argument(
935 "--revision", default="HEAD", help="Git revision (default: %(default)s)"
936 )
937 parser.add_argument(
938 "--out",
939 default="test262",
940 help="Output directory. Any existing directory will be removed!"
941 "(default: %(default)s)",
942 )
943 parser.add_argument(
944 "--pull", help="Import contents from a Pull Request specified by its number"
945 )
946 parser.add_argument(
947 "--local",
948 help="Import new and modified contents from a local folder, a new folder "
949 "will be created on local/branch_name",
950 )
951 parser.add_argument(
952 "--strict",
953 default=False,
954 action="store_true",
955 help="Generate additional strict mode tests. Not enabled by default.",
956 )
957 parser.set_defaults(func=update_test262)
958 args = parser.parse_args()
959 args.func(args)