xref: /aosp_15_r20/external/executorch/build/pip_data_bin_init.py.in (revision 523fa7a60841cd1ecfb9cc4201f1ca8b03ed023a)
1# This file should be written to the wheel package as
2# `executorch/data/bin/__init__.py`.
3#
4# Setuptools will expect to be able to say something like `from
5# executorch.data.bin import mybin; mybin()` for each entry listed in the
6# [project.scripts] section of pyproject.toml. This file makes the `mybin()`
7# function execute the binary at `executorch/data/bin/mybin` and exit with that
8# binary's exit status.
9
10import subprocess
11import os
12import sys
13import types
14
15# This file should live in the target `bin` directory.
16_bin_dir = os.path.join(os.path.dirname(__file__))
17
18def _find_executable_files_under(dir):
19    """Lists all executable files in the given directory."""
20    bin_names = []
21    for filename in os.listdir(dir):
22        filepath = os.path.join(dir, filename)
23        if os.path.isfile(filepath) and os.access(filepath, os.X_OK):
24            # Remove .exe suffix on windows.
25            filename_without_ext = os.path.splitext(filename)[0]
26            bin_names.append(filename_without_ext)
27    return bin_names
28
29# The list of binaries to create wrapper functions for.
30_bin_names = _find_executable_files_under(_bin_dir)
31
32# We'll define functions named after each binary. Make them importable.
33__all__ = _bin_names
34
35def _run(name):
36    """Runs the named binary, which should live under _bin_dir.
37
38    Exits the current process with the return code of the subprocess.
39    """
40    raise SystemExit(subprocess.call([os.path.join(_bin_dir, name)] + sys.argv[1:], close_fds=False))
41
42# Define a function named after each of the binaries.
43for bin_name in _bin_names:
44    exec(f"def {bin_name}(): _run('{bin_name}')")
45