1#!/usr/bin/env python3
2"""Create a tarball of intermediate output for inspection if tests fail.
3
4This is useful for seeing what exactly `ctest` is running.
5"""
6
7import os
8import subprocess as sp
9import sys
10
11from datetime import datetime, timezone
12from glob import glob
13from pathlib import Path
14
15
16def main():
17    # Find the most recently touched file named "main.c" in the target
18    # directory. This will be libc-tests's `OUT_DIR`
19    marker_files = [Path(p) for p in glob("target/**/main.c", recursive=True)]
20    marker_files.sort(key=lambda path: path.stat().st_mtime)
21    build_dir = marker_files[0].parent
22    print(f"Located build directory '{build_dir}'")
23
24    # Collect all relevant Rust and C files
25    add_files = glob("**/*.rs", recursive=True, root_dir=build_dir)
26    add_files += glob("**/*.c", recursive=True, root_dir=build_dir)
27    file_list = "\n".join(add_files).encode()
28
29    now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H%MZ")
30    archive_name = f"archive-{now}"
31    archive_path = f"{archive_name}.tar.gz"
32
33    sp.run(["tar", "czvf", archive_path, "-C", build_dir, "-T-"], input=file_list)
34
35    # If we are in GHA, set these env vars for future use
36    gh_env = os.getenv("GITHUB_ENV")
37    if gh_env is not None:
38        print("Updating CI environment")
39        with open(gh_env, "w+") as f:
40            f.write(f"ARCHIVE_NAME={archive_name}\n")
41            f.write(f"ARCHIVE_PATH={archive_path}\n")
42
43
44if __name__ == "__main__":
45    # FIXME(ci): remove after the bump to windoes-2025 GHA images
46    # Python <= 3.9 does not support the very helpful `root_dir` argument,
47    # and that is the version used by the Windows GHA images. Rather than
48    # using setup-python or doing something in the CI script, just find
49    # the newer version and relaunch if this happens to be run with an old
50    # version.
51    try:
52        glob("", root_dir="")
53    except TypeError:
54        if os.environ.get("CI") is None:
55            sys.exit(1)
56
57        # Find the next 3.1x Python version
58        dirs = sorted(list(Path(r"C:\hostedtoolcache\windows\Python").iterdir()))
59        usepy = next(x for x in dirs if r"\3.1" in str(x))
60        py = usepy.joinpath(r"x64\python.exe")
61        print(f"relaunching with {py}")
62        os.execvp(py, [__file__] + sys.argv)
63
64    main()
65